-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
75 lines (64 loc) · 2.15 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
import cookie from 'cookie';
import { NextResponse } from 'next/server'
import {jwtDecode} from 'jwt-decode';
const secretkey = process.env.SECRET_KEY;
export async function middleware(request) {
const path = request.nextUrl.pathname;
const cookies = cookie.parse(request.headers.get('cookie') || '');
const isAuthenticated = !!cookies.token;
const token = cookies.token;
let isAdmin = false;
if (token) {
try {
const decodedToken = jwtDecode(token);
const admin = decodedToken.isAdmin;
if (admin) {
isAdmin = true;
}
} catch (error) {
console.error('Token verification failed:', error);
}
}
if (!isAuthenticated && path === '/user/profile') {
const loginUrl = new URL('/user/login', request.url);
loginUrl.searchParams.set('redirectTo', path);
return NextResponse.redirect(loginUrl);
}
if (!isAuthenticated && path === '/cabs/bookcab') {
const loginUrl = new URL('/user/login', request.url);
loginUrl.searchParams.set('redirectTo', path);
return NextResponse.redirect(loginUrl);
}
const dynamicRoutePackages = /^\/cabs\/allpackages\/[^\/]+$/;
if (!isAuthenticated && dynamicRoutePackages.test(path)) {
const loginUrl = new URL('/user/login', request.url);
loginUrl.searchParams.set('redirectTo', path);
return NextResponse.redirect(loginUrl);
}
const dynamicRouteCabtypes = /^\/cabs\/cabtypes\/[^\/]+$/;
if (!isAuthenticated && dynamicRouteCabtypes.test(path)) {
const loginUrl = new URL('/user/login', request.url);
loginUrl.searchParams.set('redirectTo', path);
return NextResponse.redirect(loginUrl);
}
const publicPath = path === '/user/login' || path === '/user/signup';
if (isAuthenticated && publicPath) {
return NextResponse.redirect(new URL('/', request.nextUrl));
}
if (!isAdmin && path === '/admin') {
return NextResponse.redirect(new URL('/unauthorized', request.nextUrl));
}
return NextResponse.next();
}
export const config = {
matcher: [
'/',
'/user/profile',
'/user/login',
'/user/signup',
'/cabs/bookcab',
'/admin',
'/cabs/allpackages/:packageid*',
'/cabs/cabtypes/:cabtypeid*'
],
};