feat: add auth middleware for write endpoint protection
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
38
src/server/middleware/auth.ts
Normal file
38
src/server/middleware/auth.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
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);
|
||||
}
|
||||
Reference in New Issue
Block a user