43 lines
1.3 KiB
TypeScript
43 lines
1.3 KiB
TypeScript
import type { Context } from "jsr:@hono/hono@4";
|
|
import { deleteCookie, getCookie } from "jsr:@hono/hono@4/cookie";
|
|
import {
|
|
type AuthenticatedUser,
|
|
getAuthenticatedUser,
|
|
getCookieDomain,
|
|
isGlobalAdmin,
|
|
isSessionAdmin,
|
|
} from "../server/auth-session.ts";
|
|
|
|
export interface UiAuthResult {
|
|
auth: AuthenticatedUser;
|
|
isAdmin: boolean;
|
|
isSessionAdminRole: boolean;
|
|
}
|
|
|
|
/**
|
|
* Helper to ensure a user is authenticated for UI routes.
|
|
* If not authenticated, clears cookies and redirects to /login.
|
|
* Returns the AuthenticatedUser and admin status if successful, or a Hono Response (redirect).
|
|
*/
|
|
export async function requireUiAuth(
|
|
c: Context,
|
|
): Promise<UiAuthResult | Response> {
|
|
const auth = await getAuthenticatedUser(c);
|
|
if (!auth) {
|
|
if (getCookie(c, "session_id")) {
|
|
deleteCookie(c, "session_id", { path: "/" }); // clear host cookie
|
|
deleteCookie(c, "session_id", {
|
|
domain: getCookieDomain(Deno.env.get("RP_ID")),
|
|
path: "/",
|
|
}); // clear domain cookie
|
|
}
|
|
c.header("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
|
|
return c.redirect("/login");
|
|
}
|
|
|
|
const isAdmin = await isGlobalAdmin(auth.userId);
|
|
const isSessionAdminRole = await isSessionAdmin(auth);
|
|
|
|
return { auth, isAdmin, isSessionAdminRole };
|
|
}
|