-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
87 lines (73 loc) · 2.24 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';
const protectedPaths = [
// user's
'/profile',
'/my-blogs',
'/publish-blog',
'/contact',
// admin's
'/admin',
];
const publicApiPaths = [
'/api/auth',
'/api/blog/get',
'/api/blog/search',
'/api/blog/recommend',
'/api/count',
'/api/googleIndexing/indexing'
]
export async function middleware(req) {
const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
const { pathname } = req.nextUrl;
if (token) {
// Redirect authenticated users to dashborad
if (['/user/register', '/user/login', '/admin/login'].includes(pathname)) {
const redirectUrl = req.nextUrl.clone();
redirectUrl.pathname = token.role === 'admin' ? '/admin/dashboard' : '/dashboard';
return NextResponse.redirect(redirectUrl);
}
// // Role-based route access
if (token.role === 'user' && pathname.startsWith('/admin')) {
return NextResponse.redirect(new URL('/dashboard', req.url));
}
} else {
// Allow unauthenticated access to `/admin/login`
if (pathname === '/admin/login') {
return NextResponse.next();
}
// If the path starts with `/api`, it's an unauthenticated access
if (pathname.startsWith('/api') && !publicApiPaths.some(path => pathname.startsWith(path))) {
return NextResponse.json({ msg: 'Unauthorized Access!' }, { status: 401 });
}
// Protect routes for unauthenticated users
if (protectedPaths.some((protectedPath) => pathname.startsWith(protectedPath))) {
const loginUrl = req.nextUrl.clone();
loginUrl.pathname = '/user/login';
loginUrl.searchParams.set('callback', pathname)
return NextResponse.redirect(loginUrl);
}
// Protect all `/admin/:path*` except `/admin/login`
if (pathname.startsWith('/admin') && pathname !== '/admin/login') {
return NextResponse.redirect(new URL('/admin/login', req.url));
}
}
return NextResponse.next();
}
export const config = {
matcher: [
// user's
'/profile',
'/my-blogs',
'/publish-blog',
'/contact',
'/blog/:path*',
// admin's
'/admin/:path*',
// auth
'/user/register',
'/user/login',
// api endpoint
'/api/:path*',
],
};