1
0
Code Issues Pull Requests Actions Packages Projects Releases Wiki Activity Security Code Quality

Add authentication

This commit is contained in:
2025-07-08 14:04:53 +07:00
parent b35066835b
commit adbe09d074
16 changed files with 992 additions and 460 deletions

61
middleware.ts Normal file
View 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).*)',
],
};