-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
74 lines (62 loc) · 1.83 KB
/
Copy pathmiddleware.ts
File metadata and controls
74 lines (62 loc) · 1.83 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { verifyJwt } from './lib/jwt';
export async function middleware(req: NextRequest) {
const token = req.cookies.get('token')?.value;
const { pathname } = req.nextUrl;
// Disable caching → always check fresh
// If no token → handle unauthorized
if (!token) {
return handleUnauthorized(req);
}
// Verify token
let payload;
try {
payload = await verifyJwt(token);
} catch {
return handleUnauthorized(req);
}
if (!payload) {
return handleUnauthorized(req);
}
// 🔴 Extra check → if accessing /admin/* and role is not admin → block
if (pathname.startsWith('/admin') && payload.role !== 'admin') {
return NextResponse.redirect(new URL('/unauthorized', req.url));
}
const res = NextResponse.next();
// Attach user info
res.headers.set('x-user-id', String(payload.userId));
res.headers.set('x-user-role', payload.role || '');
res.headers.set('Cache-Control', 'no-store');
return res;
}
function handleUnauthorized(req: NextRequest) {
const { pathname } = req.nextUrl;
// If request is for API → return JSON
if (pathname.startsWith('/api')) {
return NextResponse.json(
{ data: null, message: 'Unauthorized' },
{ status: 401 }
);
}
if (pathname === '/unauthorized') {
return NextResponse.next(); // don’t redirect loop
}
// If request is for a page → redirect to login
const loginUrl = new URL('/unauthorized', req.url);
return NextResponse.redirect(loginUrl);
}
// Protect both frontend & backend routes
export const config = {
matcher: [
'/cart/:path*',
'/wishlist/:path*',
'/checkout/:path*',
'/profile/:path*',
'/admin/:path*',
'/api/cart/:path*',
'/api/wishlist/:path*',
'/api/checkout/:path*',
'/api/profile/:path*',
],
};