-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
75 lines (64 loc) · 1.83 KB
/
Copy pathproxy.ts
File metadata and controls
75 lines (64 loc) · 1.83 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import * as jose from "jose";
import { invalidateSession } from "./lib/actions/manage-sessions";
const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET);
const PROTECTED = ["/me", "/posts", "/api", "/admin"];
const PUBLIC_ONLY = ["/login", "/register"];
function isProtected(path: string) {
if (path === "/api/auth/logout") return false;
return PROTECTED.some((p) => path.startsWith(p));
}
function isPublicOnly(path: string) {
return PUBLIC_ONLY.some((p) => path.startsWith(p));
}
function redirectToLogin(request: NextRequest, path: string) {
const response = NextResponse.redirect(new URL("/login", request.url));
response.cookies.set("post_login_redirect", path, {
httpOnly: true,
sameSite: "lax",
maxAge: 60 * 5,
path: "/",
});
return response;
}
export async function proxy(request: NextRequest) {
const path = request.nextUrl.pathname;
const token = request.cookies.get("token")?.value;
if (!token) {
if (isProtected(path)) return redirectToLogin(request, path);
return NextResponse.next();
}
try {
await jose.jwtVerify(token, JWT_SECRET);
if (isPublicOnly(path))
return NextResponse.redirect(new URL("/", request.url));
return NextResponse.next();
} catch (err) {
if (err instanceof jose.errors.JWTExpired) {
await invalidateSession(token);
}
const response = isProtected(path)
? redirectToLogin(request, path)
: NextResponse.next();
response.cookies.delete("token");
return response;
}
}
export const config = {
matcher: [
"/",
"/login",
"/register",
"/posts/new",
"/posts/:path*",
"/callback",
"/api",
"/api/me",
"/api/my-blogs",
"/me",
"/me/:path*",
"/admin",
"/admin/:path*",
],
};