-
Notifications
You must be signed in to change notification settings - Fork 10
/
middleware.ts
73 lines (60 loc) · 1.91 KB
/
middleware.ts
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
import { NextRequest, NextResponse } from "next/server";
import jwt from "jsonwebtoken";
import Cookies from "js-cookie";
import { UserInfo } from "./types/userTypes";
const publicPages = [
"/login",
"/login/google",
"/forgot-password",
"/forgot-password/email-sent",
"/sign-up",
"/sign-up/email-sent",
"/verify",
"/reset-password",
"/reset-password/success",
"/privacy-policy",
"/terms-of-service",
];
const dynamicPublicPages = ["/lesson"];
const adminPages = ["/backoffice"];
const authMiddleware = (request: NextRequest): NextResponse | undefined => {
const token = request.cookies.get("token")?.value;
const loginUrl = new URL("/login", request.url);
if (!token) {
return NextResponse.redirect(loginUrl);
}
try {
const decodedToken = jwt.decode(token) as { expiresAt: number; user: UserInfo } | null;
if (!decodedToken || !decodedToken.expiresAt) {
Cookies.remove("token");
return NextResponse.redirect(loginUrl);
}
const currentTime = Math.floor(Date.now() / 1000);
if (decodedToken.expiresAt < currentTime) {
Cookies.remove("token");
return NextResponse.redirect(loginUrl);
}
if (adminPages.some((path) => request.nextUrl.pathname.startsWith(path))) {
if (decodedToken.user.isAdmin) {
return NextResponse.next();
}
return NextResponse.rewrite(new URL("/not-found", request.url));
}
return NextResponse.next();
} catch {
return NextResponse.redirect(loginUrl);
}
};
export default function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
const isPublicPage = publicPages.includes(pathname) || dynamicPublicPages.some((path) => pathname.startsWith(path));
if (isPublicPage) {
return;
}
return authMiddleware(req);
}
export const config = {
matcher: [
"/((?!api|_next/static|_next/image|favicon.ico|apple-touch-icon.png|favicon.svg|public|icons|manifest|assets).*)",
],
};