31 lines
990 B
TypeScript
31 lines
990 B
TypeScript
import { defineMiddleware } from 'astro:middleware';
|
|
import { getSessionFromRequest } from './lib/auth';
|
|
|
|
const EXACT_PUBLIC = ['/', '/verify'];
|
|
const PREFIX_PUBLIC = ['/cv/', '/api/auth/'];
|
|
|
|
export const onRequest = defineMiddleware(async (context, next) => {
|
|
const url = new URL(context.request.url);
|
|
const path = url.pathname;
|
|
|
|
// Always allow public routes
|
|
const isPublic = EXACT_PUBLIC.includes(path) || PREFIX_PUBLIC.some(r => path.startsWith(r));
|
|
|
|
if (!isPublic) {
|
|
const session = getSessionFromRequest(context.request);
|
|
if (!session) {
|
|
if (path.startsWith('/api/')) {
|
|
return new Response(JSON.stringify({ error: 'Unauthorized' }), {
|
|
status: 401,
|
|
headers: { 'Content-Type': 'application/json' }
|
|
});
|
|
}
|
|
return context.redirect(`/?redirect=${encodeURIComponent(path)}`);
|
|
}
|
|
context.locals.user = { id: session.user_id, email: session.email };
|
|
context.locals.session = session;
|
|
}
|
|
|
|
return next();
|
|
});
|