-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.js
56 lines (37 loc) · 1.56 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
import { auth } from '@/auth';
import { apiPrefix, publicRoutes } from '@/routes';
import { isTokenValid } from '@/utils/functions/is-token-valid';
import { NextResponse } from 'next/server';
import { isUserAuthorized } from '@/utils/functions/is-user-authorized';
export const config = {
matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)']
};
export default auth((req) => {
const reqUrl = new URL(req.url);
const auth = req.auth;
const currentPath = reqUrl.pathname;
const isLoggedIn = !!auth?.user;
const isApiAuthRoute = currentPath.startsWith(apiPrefix);
const isPublicRoute = publicRoutes.includes(currentPath);
const isValidToken = isTokenValid(auth?.accessToken);
const isOnProtectedRoute = currentPath.startsWith('/dashboard');
const isOnLoginRoute = currentPath.startsWith('/login');
if (isApiAuthRoute) return NextResponse.next();
if (isOnLoginRoute) {
if (isLoggedIn && isValidToken)
return NextResponse.redirect(new URL('/dashboard', reqUrl));
return NextResponse.next();
}
if (!isLoggedIn || !isValidToken) {
return NextResponse.redirect(new URL('/login', reqUrl));
}
if (isPublicRoute) {
return NextResponse.redirect(new URL('/dashboard', reqUrl));
} else if (isOnProtectedRoute) {
const canAccess = isUserAuthorized(auth?.user?.role, currentPath);
if (!canAccess)
return NextResponse.redirect(new URL('/unauthorized', reqUrl));
return NextResponse.next();
}
return NextResponse.next();
});