Files
chronus/src/middleware.ts
Atridad Lahiji 705358d44c
All checks were successful
Docker Deploy / build-and-push (push) Successful in 3m55s
Please...
2026-02-13 11:18:20 -07:00

41 lines
1.1 KiB
TypeScript

import { defineMiddleware } from "astro/middleware";
import { getUserFromToken } from "./lib/auth";
import { validateApiToken } from "./lib/api-auth";
const PUBLIC_ROUTES = ["/", "/login", "/signup"];
export const onRequest = defineMiddleware(async (context, next) => {
const { pathname } = context.url;
const authHeader = context.request.headers.get("Authorization");
if (authHeader?.startsWith("Bearer ")) {
const token = authHeader.substring(7);
const result = await validateApiToken(token);
if (result) {
context.locals.user = result.user;
context.locals.scopes = result.scopes;
return next();
}
}
const token = context.cookies.get("auth_token")?.value;
if (token) {
const user = await getUserFromToken(token);
context.locals.user = user;
} else {
context.locals.user = null;
}
context.locals.scopes = null;
const isPublic =
PUBLIC_ROUTES.includes(pathname) || pathname.startsWith("/api/");
if (!isPublic && !context.locals.user) {
return context.redirect("/login");
}
return next();
});