import type { Context, Next } from "jsr:@hono/hono@4"; import { getCookie } from "jsr:@hono/hono@4/cookie"; import type { AuthSdk } from "./mod.ts"; export function createAuthMiddleware(sdk: AuthSdk) { return async (c: Context, next: Next) => { let token = getCookie(c, "session_id"); if (!token) { const authHeader = c.req.header("Authorization"); if (authHeader && authHeader.startsWith("Bearer ")) { token = authHeader.substring("Bearer ".length); } } if (!token) { return c.json({ error: "Unauthorized" }, 401); } try { const userId = await sdk.requireAuth(token); c.set("userId", userId); await next(); } catch (_e) { return c.json({ error: "Unauthorized" }, 401); } }; }