-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiddleware.ts
executable file
·53 lines (47 loc) · 1.37 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
import { NextResponse } from "next/server";
import { auth } from "@/auth";
import {
publicRoutes,
authRoutes,
nextApiRoutes,
adminRoute,
REDIRECT_URL,
} from "@/lib/auth";
export default auth((req) => {
const { nextUrl } = req;
const isLoggedIn = !!req.auth;
const isNextApiRoute = nextUrl.pathname.startsWith(nextApiRoutes);
const isAuthRoute = authRoutes.includes(nextUrl.pathname);
const isPublicRoute = publicRoutes.includes(nextUrl.pathname);
const isAdminRoute = nextUrl.pathname.startsWith(adminRoute);
if (isNextApiRoute) return NextResponse.next();
if (isAuthRoute) {
if (isLoggedIn) {
const url = new URL(REDIRECT_URL, nextUrl.origin);
return NextResponse.redirect(url);
}
return NextResponse.next();
}
if (!isLoggedIn && !isPublicRoute) {
const url = new URL("/signin", nextUrl.origin);
return NextResponse.redirect(url);
}
if (isAdminRoute) {
if (isLoggedIn) {
if (req.auth?.user) {
const role = req.auth?.user.role;
if (role !== "ADMIN") {
const url = new URL("/", nextUrl.origin);
return NextResponse.redirect(url);
}
}
}
return NextResponse.next();
}
});
export const config = {
matcher: [
"/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
"/(api|trpc)(.*)",
],
};