30 lines
973 B
TypeScript
30 lines
973 B
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { jwtVerify } from 'jose';
|
|
|
|
export async function middleware(req: NextRequest) {
|
|
const token = req.cookies.get('token')?.value;
|
|
const url = req.nextUrl.clone();
|
|
const jwtSecret = process.env.JWT_SECRET;
|
|
|
|
if (req.nextUrl.pathname.startsWith('/admin') && req.nextUrl.pathname !== '/admin/login') {
|
|
if (!token || !jwtSecret || jwtSecret === 'replace-with-generated-secret') {
|
|
url.pathname = '/admin/login';
|
|
return NextResponse.redirect(url);
|
|
}
|
|
|
|
try {
|
|
const { payload } = await jwtVerify(token, new TextEncoder().encode(jwtSecret));
|
|
if (payload.role !== 'admin') throw new Error('Invalid role');
|
|
} catch {
|
|
url.pathname = '/admin/login';
|
|
return NextResponse.redirect(url);
|
|
}
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ['/admin', '/admin/:path*'],
|
|
};
|