-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
71 lines (63 loc) · 2.06 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
import { NextRequest, NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
import { publicRoutes, apiAuthPrefix, authRoutes, defaultLoginRedirect } from "./route";
export async function middleware(req: NextRequest) {
const url = req.nextUrl.clone();
const session = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
const isLoggedIn = !!session;
const isApiRoute = url.pathname.startsWith(apiAuthPrefix);
const isPublicRoute = publicRoutes.some((route) => {
const regex = new RegExp(`^${route.replace(/\[.*\]/, ".*")}$`);
return regex.test(url.pathname);
});
const isAuthRoute = authRoutes.includes(url.pathname);
if (isApiRoute) {
return NextResponse.next();
}
if (isLoggedIn) {
// Admin specific redirection logic
//@ts-ignore
if (session.user.isAdmin) {
// Redirect admins to /admin if they are not already on /admin
if (
!url.pathname.startsWith("/admin") &&
!isPublicRoute &&
!url.pathname.startsWith("/cart") &&
!url.pathname.startsWith("/thank-you")
) {
url.pathname = `/admin`;
return NextResponse.redirect(url);
}
} else {
// Redirect non-admins away from /admin
if (url.pathname.startsWith("/admin")) {
url.pathname = "/";
return NextResponse.redirect(url);
}
}
if (isAuthRoute) {
url.pathname = defaultLoginRedirect;
return NextResponse.redirect(url);
}
return NextResponse.next();
}
if (isAuthRoute) {
//@ts-ignore
if (isLoggedIn && session.user.isAdmin && !url.pathname.startsWith("/admin")) {
url.pathname = "/admin";
return NextResponse.redirect(url);
} else if (isLoggedIn) {
url.pathname = defaultLoginRedirect;
return NextResponse.redirect(url);
}
return NextResponse.next();
}
if (!isLoggedIn && !isPublicRoute) {
url.pathname = "/signin";
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
};