Add authentication
This commit is contained in:
61
middleware.ts
Normal file
61
middleware.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import type { NextRequest } from 'next/server';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';
|
||||
|
||||
// Define protected routes
|
||||
const protectedRoutes = ['/modules'];
|
||||
|
||||
|
||||
export function middleware(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl;
|
||||
|
||||
// Check if the current path is a protected route
|
||||
const isProtectedRoute = protectedRoutes.some(route =>
|
||||
pathname.startsWith(route)
|
||||
);
|
||||
|
||||
|
||||
|
||||
// Get token from cookies
|
||||
const token = request.cookies.get('auth-token')?.value;
|
||||
|
||||
// If accessing a protected route without a token, redirect to login
|
||||
if (isProtectedRoute && !token) {
|
||||
return NextResponse.redirect(new URL('/auth/login', request.url));
|
||||
}
|
||||
|
||||
// Verify token if it exists
|
||||
if (token) {
|
||||
try {
|
||||
jwt.verify(token, JWT_SECRET);
|
||||
|
||||
// If user is authenticated and trying to access login page, redirect to modules
|
||||
if (pathname === '/auth/login') {
|
||||
return NextResponse.redirect(new URL('/modules/user', request.url));
|
||||
}
|
||||
} catch {
|
||||
// Invalid token - remove it and redirect to login if accessing protected route
|
||||
const response = NextResponse.redirect(new URL('/auth/login', request.url));
|
||||
response.cookies.delete('auth-token');
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
// Allow the request to continue
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: [
|
||||
/*
|
||||
* Match all request paths except for the ones starting with:
|
||||
* - api (API routes)
|
||||
* - _next/static (static files)
|
||||
* - _next/image (image optimization files)
|
||||
* - favicon.ico (favicon file)
|
||||
*/
|
||||
'/((?!api|_next/static|_next/image|favicon.ico).*)',
|
||||
],
|
||||
};
|
||||
Reference in New Issue
Block a user