likwid/frontend/src/middleware.ts

65 lines
1.6 KiB
TypeScript

import { defineMiddleware } from 'astro:middleware';
function isEnabled(v: string | undefined): boolean {
if (!v) return false;
const n = v.trim().toLowerCase();
return n === '1' || n === 'true' || n === 'yes' || n === 'on';
}
const DEMO_COOKIE = 'likwid_demo_unlocked';
export const onRequest = defineMiddleware(async (context, next) => {
const publicDemoSite = isEnabled((globalThis as any).process?.env?.PUBLIC_DEMO_SITE);
if (!publicDemoSite) {
return next();
}
const url = new URL(context.request.url);
const path = url.pathname;
if (path === '/demo' && url.searchParams.get('enter') === '1') {
let nextPath = url.searchParams.get('next') || '/communities';
if (!nextPath.startsWith('/')) {
nextPath = '/communities';
}
context.cookies.set(DEMO_COOKIE, '1', {
path: '/',
httpOnly: true,
sameSite: 'lax',
maxAge: 60 * 60 * 12,
});
return context.redirect(nextPath);
}
if (path.startsWith('/_astro') || path.startsWith('/favicon') || path.startsWith('/robots')) {
return next();
}
if (path === '/setup' || path === '/register') {
return context.redirect('/demo');
}
const isProtected =
path === '/login' ||
path === '/dashboard' ||
path === '/delegations' ||
path === '/notifications' ||
path === '/settings' ||
path.startsWith('/admin') ||
path.startsWith('/communities') ||
path.startsWith('/proposals') ||
path.startsWith('/users');
if (!isProtected) {
return next();
}
const unlocked = context.cookies.get(DEMO_COOKIE)?.value === '1';
if (!unlocked) {
return context.redirect('/demo');
}
return next();
});