53 lines
1.4 KiB
TypeScript
53 lines
1.4 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import type { NextRequest } from 'next/server';
|
|
import jwt from 'jsonwebtoken';
|
|
|
|
const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret-CHANGE-IN-PRODUCTION';
|
|
|
|
export function proxy(request: NextRequest) {
|
|
const path = request.nextUrl.pathname;
|
|
|
|
// Define public and private paths
|
|
const isPublicPath = path === '/acesso';
|
|
const isPrivatePath = path.startsWith('/admin');
|
|
|
|
// Get the token from the cookies
|
|
const token = request.cookies.get('auth_token')?.value || '';
|
|
|
|
// Validate JWT token
|
|
let isValidToken = false;
|
|
if (token) {
|
|
try {
|
|
jwt.verify(token, JWT_SECRET);
|
|
isValidToken = true;
|
|
} catch (err) {
|
|
// Token inválido ou expirado
|
|
isValidToken = false;
|
|
}
|
|
}
|
|
|
|
// Redirect logic
|
|
if (isPrivatePath && !isValidToken) {
|
|
// If trying to access admin without valid token, redirect to login
|
|
const response = NextResponse.redirect(new URL('/acesso', request.url));
|
|
// Remover token inválido
|
|
response.cookies.delete('auth_token');
|
|
return response;
|
|
}
|
|
|
|
if (isPublicPath && isValidToken) {
|
|
// If trying to access login while already logged in, redirect to admin
|
|
return NextResponse.redirect(new URL('/admin', request.url));
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
// Configure which paths the middleware should run on
|
|
export const config = {
|
|
matcher: [
|
|
'/acesso',
|
|
'/admin/:path*',
|
|
],
|
|
};
|