-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
31 lines (27 loc) · 955 Bytes
/
middleware.ts
File metadata and controls
31 lines (27 loc) · 955 Bytes
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
import { NextRequest, NextResponse } from 'next/server';
import { jwtVerify } from 'jose';
const secret_key = process.env.NEXT_PUBLIC_SECRET_KEY!;
if (!secret_key) {
throw new Error("SECRET_KEY is not defined in environment variables.");
}
const secret = new TextEncoder().encode(secret_key);
export async function middleware(req: NextRequest) {
const authHeader = req.headers.get('Authorization');
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return new NextResponse('Access Denied', { status: 403 });
}
const token = authHeader.replace('Bearer ', '');
try {
const { payload }:any = await jwtVerify(token, secret);
const response = NextResponse.next();
response.headers.set('x-user-role', payload.role);
return response;
} catch (error) {
return new NextResponse('Invalid Token', { status: 403 });
}
}
export const config = {
matcher: [
'/api/:path((?!student/login|user/login).*)',
],
};