-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.js
58 lines (48 loc) · 1.55 KB
/
middleware.js
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
// middleware.js
import { NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
export async function middleware(req) {
const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
const { pathname } = req.nextUrl;
const publicRoutes = [
"/",
"/seller/login",
"/seller/register",
"/customer/login",
"/customer/register",
];
if (token) {
const userRole = token.role;
if (publicRoutes.includes(pathname)) {
if (userRole === "seller") {
return NextResponse.redirect(new URL("/seller/dashboard", req.url));
} else if (userRole === "customer") {
return NextResponse.redirect(new URL("/customer/dashboard", req.url));
}
}
if (pathname.startsWith("/seller")) {
if (userRole !== "seller") {
return NextResponse.redirect(new URL("/customer/dashboard", req.url));
}
} else if (pathname.startsWith("/customer")) {
if (userRole !== "customer") {
return NextResponse.redirect(new URL("/seller/dashboard", req.url));
}
}
return NextResponse.next();
}
if (!token) {
if (publicRoutes.includes(pathname)) {
return NextResponse.next();
}
if (pathname.startsWith("/seller")) {
return NextResponse.redirect(new URL("/seller/login", req.url));
} else if (pathname.startsWith("/customer")) {
return NextResponse.redirect(new URL("/customer/login", req.url));
}
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};