30 lines
941 B
TypeScript
30 lines
941 B
TypeScript
import { NextResponse } from 'next/server';
|
|
import type { NextRequest } from 'next/server';
|
|
|
|
export function middleware(request: NextRequest) {
|
|
const token = request.cookies.get('auth_token')?.value ||
|
|
request.headers.get('authorization')?.replace('Bearer ', '');
|
|
|
|
const isAdminRoute = request.nextUrl.pathname.startsWith('/admin');
|
|
const isLoginRoute = request.nextUrl.pathname === '/admin/login';
|
|
|
|
// Allow access to login page without token
|
|
if (isLoginRoute) {
|
|
// If already logged in, redirect to dashboard
|
|
if (token) {
|
|
return NextResponse.redirect(new URL('/admin/dashboard', request.url));
|
|
}
|
|
return NextResponse.next();
|
|
}
|
|
|
|
// Protect admin routes
|
|
if (isAdminRoute && !token) {
|
|
return NextResponse.redirect(new URL('/admin/login', request.url));
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: '/admin/:path*',
|
|
}; |