Add database reset script and update package.json for db commands; refactor middleware for CORS support and error handling in parks page

This commit is contained in:
pacnpal
2025-02-23 18:09:27 -05:00
parent c9ab1f40ed
commit 046257d06c
6 changed files with 255 additions and 279 deletions

View File

@@ -1,85 +1,25 @@
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/');
const response = NextResponse.next();
// Only apply middleware to API routes
if (!isApiRoute) {
return NextResponse.next();
// Add additional headers
response.headers.set('x-middleware-cache', 'no-cache');
// CORS headers for API routes
if (request.nextUrl.pathname.startsWith('/api/')) {
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}
// 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 }
);
}
return response;
}
// Configure routes that need middleware
export const config = {
matcher: [
/*
* Match all API routes:
* - /api/auth/login
* - /api/parks
* - /api/reviews
* etc.
*/
'/api/:path*',
],
]
};