-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmiddleware.js
More file actions
89 lines (71 loc) · 2.36 KB
/
Copy pathmiddleware.js
File metadata and controls
89 lines (71 loc) · 2.36 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
import { NextResponse } from "next/server";
import { verifyToken } from "./lib/verify-token";
const unprotectedRoutes = [
"/about-us",
"/privacy",
"/ToS",
"/server-not-found",
];
const semiProtectedRoutes = ["/template"];
export async function middleware(req) {
const { pathname, search } = req.nextUrl;
const token = req.cookies.get("token");
const lastTeamId = req.cookies.get("lastTeamId");
const isSemiProtected = semiProtectedRoutes.some((route) =>
pathname.startsWith(route),
);
if (unprotectedRoutes.some((route) => pathname.startsWith(route))) {
return NextResponse.next();
}
if (!token) {
if (pathname === "/") return NextResponse.next();
if (isSemiProtected) {
const response = NextResponse.next();
response.headers.set("X-User-Status", "inactive");
return response;
}
const loginUrl = new URL("/", req.url);
if (search) loginUrl.search = search;
return NextResponse.redirect(loginUrl);
}
try {
const { payload } = await verifyToken(`Bearer ${token.value}`);
if (!payload) {
if (isSemiProtected) {
const response = NextResponse.next();
response.headers.set("X-User-Status", "inactive");
return response;
}
if (pathname === "/") return NextResponse.next();
const loginUrl = new URL("/", req.url);
if (search) loginUrl.search = search;
return NextResponse.redirect(loginUrl);
}
if (pathname === "/" && lastTeamId) {
const dashboardUrl = new URL("/dashboard", req.url);
if (search) dashboardUrl.search = search;
return NextResponse.redirect(dashboardUrl);
}
if (!lastTeamId && pathname !== "/teams") {
const teamsUrl = new URL("/teams", req.url);
if (search) teamsUrl.search = search;
return NextResponse.redirect(teamsUrl);
}
const response = NextResponse.next();
response.headers.set("X-User-Status", "active");
return response;
} catch (error) {
console.error("Authentication error:", error);
if (isSemiProtected) {
const response = NextResponse.next();
response.headers.set("X-User-Status", "inactive");
return response;
}
return NextResponse.redirect(new URL("/", req.url));
}
}
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|.*\\.(?:jpg|jpeg|gif|png|svg|ico|webp)).*)",
],
};