Files
InsanityLab-web/src/middleware.ts
T

35 lines
1.2 KiB
TypeScript

import { defineMiddleware } from 'astro:middleware';
import { getDb } from './lib/db';
import { getSessionUser, SESSION_COOKIE, canAccessAdminPath } from './lib/auth';
export const onRequest = defineMiddleware((context, next) => {
const { pathname } = context.url;
const isProtected =
(pathname.startsWith('/admin') && pathname !== '/admin/login') ||
pathname.startsWith('/api/admin');
if (!isProtected) return next();
const token = context.cookies.get(SESSION_COOKIE)?.value;
const user = token ? getSessionUser(getDb(), token) : null;
if (!user) {
if (pathname.startsWith('/api/')) {
return new Response(JSON.stringify({ error: 'Non autorizzato' }), {
status: 401, headers: { 'Content-Type': 'application/json' },
});
}
return context.redirect('/admin/login');
}
if (!canAccessAdminPath(user.role, pathname)) {
if (pathname.startsWith('/api/')) {
return new Response(JSON.stringify({ error: 'Permessi insufficienti' }), {
status: 403, headers: { 'Content-Type': 'application/json' },
});
}
return context.redirect('/admin/content');
}
context.locals.user = user;
return next();
});