-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
50 lines (40 loc) · 1.34 KB
/
Copy pathproxy.ts
File metadata and controls
50 lines (40 loc) · 1.34 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
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { jwtVerify } from "jose";
const SECRET = new TextEncoder().encode(
process.env.NEXTAUTH_SECRET || process.env.AUTH_SECRET || "secret-key"
);
const PUBLIC_PATHS = ["/login", "/register", "/api/login", "/api/logout"];
const PUBLIC_PREFIXES = ["/api/auth"];
async function verifyToken(token: string) {
try {
const { payload } = await jwtVerify(token, SECRET);
return payload;
} catch {
return null;
}
}
export async function proxy(req: NextRequest) {
const { pathname } = req.nextUrl;
const isPublicPath = PUBLIC_PATHS.includes(pathname);
const isPublicPrefix = PUBLIC_PREFIXES.some(
(prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`)
);
if (isPublicPath || isPublicPrefix) {
return NextResponse.next();
}
// Check session token from cookie
const token = req.cookies.get("session-token")?.value;
const session = token ? await verifyToken(token) : null;
if (session) {
return NextResponse.next();
}
const loginUrl = new URL("/login", req.url);
loginUrl.searchParams.set("callbackUrl", req.nextUrl.pathname + req.nextUrl.search);
return NextResponse.redirect(loginUrl);
}
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
],
};