-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
51 lines (46 loc) · 1.58 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
import { NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
/**
* The /auth/signin callback is '/'
* @publicRoutes Anyone can access
* @authRoutes Mustn't be signed in
* @adminRoutes Must have ADMIN role in jwt token
* @protectedRoutes Must be signed in
*/
const publicRoutes = ["/", "/schedule", "/faqs"];
const authRoutes = ["/auth"];
const adminRoutes = ["/admin"];
const protectedRoutes = ["/profile"];
// const apiAdminRoutes = [
// "/api/ranking",
// "/api/users",
// "/api/users/accreditation",
// "/api/enrollments/delete",
// "/api/enrollments/attend/qrcode",
// "/api/activities/delete",
// ];
export async function middleware(request) {
const token = await getToken({
req: request,
secret: process.env.NEXTAUTH_SECRET,
cookieName:
process.env.NODE_ENV === "production"
? "__Secure-next-auth.session-token"
: "next-auth.session-token",
});
// Admin paths
// if signed in and doesn't have role SUPER_USER, can't access /super_user/**
if (adminRoutes.some((path) => request.nextUrl.pathname.startsWith(path))) {
if (!token || token.role != "ADMIN")
return NextResponse.redirect(new URL("/", request.url));
}
// Protected paths
if (protectedRoutes.some((path) => request.nextUrl.pathname.startsWith(path))) {
if (!token) return NextResponse.redirect(new URL("/", request.url));
}
// Auth paths
// if signed in, user can't access /auth paths
if (authRoutes.some((path) => request.nextUrl.pathname.startsWith(path))) {
if (token) return NextResponse.redirect(new URL("/", request.url));
}
}