-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.ts
More file actions
54 lines (42 loc) · 1.44 KB
/
middleware.ts
File metadata and controls
54 lines (42 loc) · 1.44 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { auth } from "./auth"
import { ADMIN_ROUTES, AuthPages, PUBLIC_ROUTES } from "./routes";
export default auth((req) => {
const { nextUrl } = req;
const isLoggedIn = !!req.auth;
const isAdmin = req.auth?.isAdmin;
const isPublicRoute = PUBLIC_ROUTES.some((route) => {
if (route.exact) {
return route.path === nextUrl.pathname;
}
return nextUrl.pathname.startsWith(route.path);
});
const isAuthRoute = AuthPages.includes(nextUrl.pathname);
if (process.env.NODE_ENV === 'development') {
console.log("middleware", { path: nextUrl.pathname, login: isLoggedIn, isPublicRoute, isAuthRoute });
}
if (isPublicRoute) {
return;
}
const isAdminRoute = ADMIN_ROUTES.some((route) => {
if (route.exact) {
return route.path === nextUrl.pathname;
}
return nextUrl.pathname.startsWith(route.path);
});
if (isAuthRoute) {
if (isLoggedIn) {
return Response.redirect(new URL('/', nextUrl));
}
return;
}
if (!isLoggedIn) {
const redirectUrl = new URL(`/auth/login?callback=${nextUrl.pathname}`, nextUrl);
return Response.redirect(redirectUrl);
}
if (isAdminRoute && !isAdmin) {
return Response.redirect(new URL('/auth/admin-account-required', nextUrl));
}
})
export const config = {
matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
}