Files
GearBox/src/server/routes/auth.ts
Jean-Luc Makiola e78002208a feat(16-03): wire userId from context into all route handlers
- Extract userId via c.get('userId') in every route handler
- Pass userId to all service function calls as second argument
- Update settings routes to use composite key [userId, key]
- Update Env type to include userId in Variables
- Auth routes pass userId to API key management functions
2026-04-05 10:49:51 +02:00

73 lines
1.9 KiB
TypeScript

import { zValidator } from "@hono/zod-validator";
import { getAuth } from "@hono/oidc-auth";
import { Hono } from "hono";
import { z } from "zod";
import { parseId } from "../lib/params.ts";
import { requireAuth } from "../middleware/auth.ts";
import {
createApiKey,
deleteApiKey,
listApiKeys,
} from "../services/auth.service.ts";
type Env = { Variables: { db?: any; userId?: number } };
const createKeySchema = z.object({ name: z.string().min(1) });
const app = new Hono<Env>();
// ── Auth Status ──────────────────────────────────────────────────────
app.get("/me", async (c) => {
const auth = await getAuth(c);
if (auth) {
return c.json({
user: { id: auth.sub, email: auth.email },
authenticated: true,
});
}
return c.json({ user: null, authenticated: false });
});
// ── API Key Management (protected) ───────────────────────────────────
app.get("/keys", requireAuth, async (c) => {
const db = c.get("db");
const userId = c.get("userId")!;
const keys = await listApiKeys(db, userId);
return c.json(keys);
});
app.post(
"/keys",
requireAuth,
zValidator("json", createKeySchema),
async (c) => {
const db = c.get("db");
const userId = c.get("userId")!;
const { name } = c.req.valid("json");
const result = await createApiKey(db, userId, name);
return c.json(
{
id: result.id,
name: result.name,
key: result.rawKey,
prefix: result.keyPrefix,
},
201,
);
},
);
app.delete("/keys/:id", requireAuth, async (c) => {
const db = c.get("db");
const userId = c.get("userId")!;
const id = parseId(c.req.param("id"));
if (!id) return c.json({ error: "Invalid key ID" }, 400);
await deleteApiKey(db, userId, id);
return c.json({ ok: true });
});
export const authRoutes = app;