-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.ts
More file actions
39 lines (31 loc) · 1.35 KB
/
middleware.ts
File metadata and controls
39 lines (31 loc) · 1.35 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
import { NextResponse, NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";
export const middleware = async (request: NextRequest) => {
// Check if the user is authenticated
const token = await getToken({ req: request });
const referer = request.headers.get("referer");
// If the user is authenticated and trying to access login or signup, redirect to home
if (token && (request.nextUrl.pathname === "/login" || request.nextUrl.pathname === "/signup")) {
return NextResponse.redirect(new URL("/", request.url));
}
// If no token is found and the route requires authentication, redirect to the login page
if (!token && (request.nextUrl.pathname.startsWith("/account-settings") || request.nextUrl.pathname.startsWith("/users"))) {
return NextResponse.redirect(new URL("/login", request.url));
}
// NOW BEGINS ROLE MANAGEMENT
if (token?.role !== "admin" && request.nextUrl.pathname.startsWith("/admin")) {
return NextResponse.redirect(new URL("/", request.url));
}
// Allow the request to continue if all conditions pass
return NextResponse.next();
};
export const config = {
matcher: [
"/login",
"/signup",
"/account-settings:path*",
"/users/:path*",
"/admin/:path*",
],
};
export { default } from "next-auth/middleware";