forked from KryptikApp/kryptikwebapp
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.ts
More file actions
57 lines (54 loc) · 1.72 KB
/
middleware.ts
File metadata and controls
57 lines (54 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import {} from "cookies-next";
import { NextApiResponse } from "next";
import { jwtVerify } from "jose";
import { NextRequest, NextResponse } from "next/server";
export async function middleware(req: NextRequest, res: NextApiResponse) {
const cookies = req.cookies;
const accessToken = cookies.get("accessToken")?.value;
const refreshToken = cookies.get("refreshToken")?.value;
console.log("running middleware!!");
if (!accessToken || !refreshToken || !process.env.JWT_ACCESS_SECRET) {
req.nextUrl.searchParams.set("from", req.nextUrl.pathname);
req.nextUrl.pathname = "/wallet/create";
return NextResponse.redirect(req.nextUrl);
}
const secret = process.env.JWT_ACCESS_SECRET;
const adaptedSecret: Uint8Array = new TextEncoder().encode(secret);
try {
const { payload, protectedHeader } = await jwtVerify(
accessToken,
adaptedSecret
);
const requestHeaders = new Headers(req.headers);
// Add new request headers
console.log("setting header");
requestHeaders.set("user-id", `${payload.userId}`);
// You can also set request headers in NextResponse.rewrite
const response = NextResponse.next({
request: {
// New request headers
headers: requestHeaders,
},
});
return response;
} catch (e: any) {
req.nextUrl.searchParams.set("from", req.nextUrl.pathname);
req.nextUrl.pathname = "/wallet/create";
return NextResponse.redirect(req.nextUrl);
}
}
export const config = {
matcher: [
"/api/user/:path*",
"/api/shares/:path*",
"/api/account/:path*",
"/wallet/send",
"/wallet/receive",
"/wallet/createName",
"/wallet/delete",
"/profile/:path*",
"/wallet",
"/sync/:path*",
"/api/sync/:path*",
],
};