-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathproxy.ts
More file actions
98 lines (79 loc) · 2.21 KB
/
Copy pathproxy.ts
File metadata and controls
98 lines (79 loc) · 2.21 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { verifyToken } from "@/lib/auth";
//intro(/) -> introSolved(T?F) Cookie
//auth(/auth) -> token
// User can ONLY access /dashboard and challenge pages
export async function proxy(req: NextRequest) {
const url = req.nextUrl.clone();
const path = url.pathname;
if (path.startsWith("/api/challenges/intro")) return NextResponse.next();
if (path.startsWith("/api/user/")) return NextResponse.next();
const introSolved = req.cookies.get("introSolved")?.value;
const token = req.cookies.get("token")?.value;
console.log("TOKEN:", token);
let payload = null;
if (token) {
try {
payload = await verifyToken(token);
} catch {
payload = null;
}
}
if (path === "/") {
if (token && payload) {
url.pathname = "/dashboard";
return NextResponse.redirect(url);
}
return NextResponse.next();
}
if (path === "/auth") {
if (!introSolved) {
url.pathname = "/";
return NextResponse.redirect(url);
}
if (token && payload) {
url.pathname = "/dashboard";
return NextResponse.redirect(url);
}
return NextResponse.next();
}
if (path.startsWith("/dashboard")) {
if (!token || !payload) {
url.pathname = "/auth";
return NextResponse.redirect(url);
}
if (!introSolved) {
url.pathname = "/";
return NextResponse.redirect(url);
}
return NextResponse.next();
}
if (path.startsWith("/api/auth/signup") || path.startsWith("/api/auth/login")) {
if (!introSolved) {
return NextResponse.json(
{ message: "You must solve the intro challenge first" },
{ status: 403 }
);
}
return NextResponse.next();
}
if (path.startsWith("/api/challenges/") || path.startsWith("/api/submissions")) {
if (!token || !payload) {
return NextResponse.json({ message: "Login required" }, { status: 401 });
}
return NextResponse.next();
}
return NextResponse.next();
}
export const config = {
matcher: [
"/",
"/auth",
"/dashboard/:path*",
"/api/challenges/:path*",
"/api/submissions",
"/api/auth/signup",
"/api/auth/login",
],
};