39 lines
925 B
TypeScript
39 lines
925 B
TypeScript
import type { Context, Next } from "hono";
|
|
import { getCookie } from "hono/cookie";
|
|
import {
|
|
getSession,
|
|
getUserCount,
|
|
refreshSession,
|
|
verifyApiKey,
|
|
} from "../services/auth.service";
|
|
|
|
export async function requireAuth(c: Context, next: Next) {
|
|
const db = c.get("db");
|
|
|
|
// Check if any users exist at all
|
|
if (getUserCount(db) === 0) {
|
|
return c.json({ error: "setup_required" }, 403);
|
|
}
|
|
|
|
// Check API key first
|
|
const apiKey = c.req.header("X-API-Key");
|
|
if (apiKey) {
|
|
const valid = await verifyApiKey(db, apiKey);
|
|
if (valid) return next();
|
|
return c.json({ error: "Invalid API key" }, 401);
|
|
}
|
|
|
|
// Check session cookie
|
|
const sessionId = getCookie(c, "gearbox_session");
|
|
if (sessionId) {
|
|
const session = getSession(db, sessionId);
|
|
if (session) {
|
|
// Refresh session expiry on use
|
|
refreshSession(db, sessionId);
|
|
return next();
|
|
}
|
|
}
|
|
|
|
return c.json({ error: "Authentication required" }, 401);
|
|
}
|