brief-20/frontend/middleware.ts
Avnyr cd5ad2e1e4 feat: implement API service, middleware, and authentication context
- Added `lib/api.ts` to centralize API communication for authentication, projects, persons, tags, and groups.
- Introduced `middleware.ts` to handle route protection based on authentication and roles.
- Created `auth-context.tsx` to manage authentication state with `AuthProvider` and `useAuth` hook.
- Updated `package.json` to include `swr` for data fetching.
- Enhanced project documentation (`RESPONSIVE_DESIGN.md` and `README.md`) with responsive design and architecture details.
2025-05-16 14:43:56 +02:00

61 lines
1.8 KiB
TypeScript

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
// Define public routes that don't require authentication
const publicRoutes = [
'/',
'/auth/login',
'/auth/callback',
];
// Define routes that require admin role
const adminRoutes = [
'/admin',
];
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Allow access to public routes without authentication
if (publicRoutes.some(route => pathname === route || pathname.startsWith(`${route}/`))) {
return NextResponse.next();
}
// Get the auth token from cookies
const token = request.cookies.get('auth_token')?.value;
const userRole = request.cookies.get('user_role')?.value;
// If no token, redirect to login
if (!token) {
// Store the original URL to redirect back after login
const url = new URL('/auth/login', request.url);
url.searchParams.set('callbackUrl', pathname);
return NextResponse.redirect(url);
}
// Check if the route requires admin role
if (adminRoutes.some(route => pathname === route || pathname.startsWith(`${route}/`))) {
// If not admin role, redirect to dashboard
if (userRole !== 'ADMIN') {
return NextResponse.redirect(new URL('/dashboard', request.url));
}
}
return NextResponse.next();
}
// Configure the middleware to run on all routes except static files and api routes
export const config = {
matcher: [
/*
* Match all request paths except for:
* 1. /api routes
* 2. /_next (Next.js internals)
* 3. /_static (static files)
* 4. /_vercel (Vercel internals)
* 5. /favicon.ico, /robots.txt, /sitemap.xml (common static files)
*/
'/((?!api|_next|_static|_vercel|favicon.ico|robots.txt|sitemap.xml).*)',
],
};