-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmiddleware.ts
More file actions
43 lines (37 loc) · 1.43 KB
/
Copy pathmiddleware.ts
File metadata and controls
43 lines (37 loc) · 1.43 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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { jwtVerify } from 'jose';
export async function middleware(request: NextRequest) {
// Protect all admin routes (API and UI)
if (request.nextUrl.pathname.startsWith('/api/admin') || request.nextUrl.pathname.startsWith('/admin')) {
const token = request.cookies.get('token')?.value;
if (!token) {
if (request.nextUrl.pathname.startsWith('/api/')) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
} else {
return NextResponse.redirect(new URL('/login', request.url));
}
}
try {
const secret = new TextEncoder().encode(process.env.JWT_SECRET || 'gravity_super_secret_key');
const { payload } = await jwtVerify(token, secret);
if (payload.role !== 'admin') {
if (request.nextUrl.pathname.startsWith('/api/')) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
} else {
return NextResponse.redirect(new URL('/', request.url));
}
}
} catch (e) {
if (request.nextUrl.pathname.startsWith('/api/')) {
return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
} else {
return NextResponse.redirect(new URL('/login', request.url));
}
}
}
return NextResponse.next();
}
export const config = {
matcher: ['/api/admin/:path*', '/admin/:path*'],
};