mirror of
https://github.com/pacnpal/thrillwiki_django_no_react.git
synced 2025-12-28 14:27:03 -05:00
85 lines
2.0 KiB
TypeScript
85 lines
2.0 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import type { NextRequest } from 'next/server';
|
|
import { headers } from 'next/headers';
|
|
|
|
// Paths that don't require authentication
|
|
const PUBLIC_PATHS = [
|
|
'/api/auth/login',
|
|
'/api/auth/register',
|
|
'/api/parks',
|
|
'/api/parks/search',
|
|
];
|
|
|
|
// Function to check if path is public
|
|
const isPublicPath = (path: string) => {
|
|
return PUBLIC_PATHS.some(publicPath => {
|
|
if (publicPath.endsWith('*')) {
|
|
return path.startsWith(publicPath.slice(0, -1));
|
|
}
|
|
return path === publicPath;
|
|
});
|
|
};
|
|
|
|
export async function middleware(request: NextRequest) {
|
|
const path = request.nextUrl.pathname;
|
|
const isApiRoute = path.startsWith('/api/');
|
|
|
|
// Only apply middleware to API routes
|
|
if (!isApiRoute) {
|
|
return NextResponse.next();
|
|
}
|
|
|
|
// Allow public paths
|
|
if (isPublicPath(path)) {
|
|
return NextResponse.next();
|
|
}
|
|
|
|
// Check for auth token
|
|
const authHeader = request.headers.get('authorization');
|
|
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
|
return NextResponse.json(
|
|
{ success: false, error: 'Unauthorized' },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
try {
|
|
// TODO: Implement token verification
|
|
// For now, just check if token exists
|
|
const token = authHeader.split(' ')[1];
|
|
if (!token) {
|
|
throw new Error('Invalid token');
|
|
}
|
|
|
|
// Add user info to request headers for API routes
|
|
const requestHeaders = new Headers(request.headers);
|
|
requestHeaders.set('x-user-token', token);
|
|
|
|
// Clone the request with modified headers
|
|
const response = NextResponse.next({
|
|
request: {
|
|
headers: requestHeaders,
|
|
},
|
|
});
|
|
|
|
return response;
|
|
} catch (error) {
|
|
return NextResponse.json(
|
|
{ success: false, error: 'Invalid token' },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
}
|
|
|
|
export const config = {
|
|
matcher: [
|
|
/*
|
|
* Match all API routes:
|
|
* - /api/auth/login
|
|
* - /api/parks
|
|
* - /api/reviews
|
|
* etc.
|
|
*/
|
|
'/api/:path*',
|
|
],
|
|
}; |