first commit
This commit is contained in:
28
src/middleware.ts
Normal file
28
src/middleware.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { defineMiddleware } from 'astro:middleware';
|
||||
import { ADMIN_COOKIE, verifySession } from './lib/auth';
|
||||
|
||||
export const onRequest = defineMiddleware(async (context, next) => {
|
||||
const { pathname } = context.url;
|
||||
|
||||
const isAdminPage = pathname.startsWith('/admin') && pathname !== '/admin/login';
|
||||
const isAdminApi =
|
||||
pathname.startsWith('/api/content') ||
|
||||
pathname.startsWith('/api/upload') ||
|
||||
pathname === '/api/auth/logout';
|
||||
|
||||
if (isAdminPage || isAdminApi) {
|
||||
const token = context.cookies.get(ADMIN_COOKIE)?.value;
|
||||
const ok = await verifySession(token);
|
||||
if (!ok) {
|
||||
if (isAdminApi) {
|
||||
return new Response(JSON.stringify({ error: 'unauthorized' }), {
|
||||
status: 401,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
return context.redirect('/admin/login');
|
||||
}
|
||||
}
|
||||
|
||||
return next();
|
||||
});
|
||||
Reference in New Issue
Block a user