-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathproxy.ts
More file actions
47 lines (40 loc) · 1.42 KB
/
Copy pathproxy.ts
File metadata and controls
47 lines (40 loc) · 1.42 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
import { NextResponse } from "next/server"
import type { NextRequest } from "next/server"
import { jwtVerify } from "jose"
function getSessionSecret() {
const raw = process.env.JWT_SECRET || process.env.AUTH_SESSION_SECRET || process.env.PRIVY_APP_SECRET
return raw ? new TextEncoder().encode(raw) : null
}
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl
const tokenCookie = request.cookies.get("token")?.value
const secret = getSessionSecret()
if (pathname.startsWith("/dashboard")) {
if (!tokenCookie || !secret) {
return NextResponse.redirect(new URL("/signin", request.url))
}
try {
await jwtVerify(tokenCookie, secret)
return NextResponse.next()
} catch {
const response = NextResponse.redirect(new URL("/signin", request.url))
response.cookies.delete("token")
return response
}
}
if ((pathname === "/signin" || pathname === "/auth") && tokenCookie && secret) {
try {
const { payload } = await jwtVerify(tokenCookie, secret)
const role = typeof payload.role === "string" ? payload.role : null
if (role) {
return NextResponse.redirect(new URL(`/dashboard/${role}`, request.url))
}
} catch {
return NextResponse.next()
}
}
return NextResponse.next()
}
export const config = {
matcher: ["/dashboard/:path*", "/signin", "/auth"],
}