-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmiddleware.ts
More file actions
41 lines (32 loc) · 1.18 KB
/
middleware.ts
File metadata and controls
41 lines (32 loc) · 1.18 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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { verifyJWT } from '@/lib/auth';
export async function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname;
// Admin routes protection
if (pathname.startsWith('/admin') && pathname !== '/admin/login') {
const token = request.cookies.get('auth_token')?.value;
if (!token) {
return NextResponse.redirect(new URL('/admin/login', request.url));
}
const payload = await verifyJWT(token);
if (!payload || payload.type !== 'admin') {
return NextResponse.redirect(new URL('/admin/login', request.url));
}
}
// User routes protection
if (pathname.startsWith('/user') && pathname !== '/user/login') {
const token = request.cookies.get('auth_token')?.value;
if (!token) {
return NextResponse.redirect(new URL('/user/login', request.url));
}
const payload = await verifyJWT(token);
if (!payload || payload.type !== 'user') {
return NextResponse.redirect(new URL('/user/login', request.url));
}
}
return NextResponse.next();
}
export const config = {
matcher: ['/admin/:path*', '/user/:path*'],
};