49 lines
1.6 KiB
Plaintext
49 lines
1.6 KiB
Plaintext
import { NextResponse } from 'next/server';
|
|
import type { NextRequest } from 'next/server';
|
|
import { verifyToken } from '@/lib/auth';
|
|
|
|
export function middleware(request: NextRequest) {
|
|
const token = request.cookies.get('auth-token')?.value;
|
|
const pathname = request.nextUrl.pathname;
|
|
|
|
console.log('[Middleware]', pathname, 'Token:', token ? 'YES' : 'NO');
|
|
|
|
// Check if user is trying to access login page
|
|
const isLoginPage = pathname === '/login';
|
|
|
|
// If no token and not on login page, redirect to login
|
|
if (!token && !isLoginPage) {
|
|
console.log('[Middleware] No token, redirecting to /login');
|
|
return NextResponse.redirect(new URL('/login', request.url));
|
|
}
|
|
|
|
// If token exists, verify it
|
|
if (token) {
|
|
const payload = verifyToken(token);
|
|
console.log('[Middleware] Token payload:', payload ? 'VALID' : 'INVALID');
|
|
|
|
// If token is invalid and not on login page, redirect to login
|
|
if (!payload && !isLoginPage) {
|
|
console.log('[Middleware] Invalid token, redirecting to /login');
|
|
const response = NextResponse.redirect(new URL('/login', request.url));
|
|
response.cookies.delete('auth-token');
|
|
return response;
|
|
}
|
|
|
|
// If token is valid and on login page, redirect to home
|
|
if (payload && isLoginPage) {
|
|
console.log('[Middleware] Valid token on login page, redirecting to /');
|
|
return NextResponse.redirect(new URL('/', request.url));
|
|
}
|
|
}
|
|
|
|
console.log('[Middleware] Allowing request to', pathname);
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: [
|
|
'/((?!api|_next/static|_next/image|favicon.ico).*)',
|
|
],
|
|
};
|