feat(36-01): add requireAdmin middleware to auth.ts
- Import eq from drizzle-orm and users from schema - Export requireAdmin(c, next) that returns 401 if userId not in context, 403 if user.isAdmin is falsy
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
import type { Context, Next } from "hono";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { users } from "../../db/schema.ts";
|
||||
import { getOrCreateUser, verifyApiKey } from "../services/auth.service";
|
||||
import { getOrCreateUncategorized } from "../services/category.service";
|
||||
import { verifyAccessToken } from "../services/oauth.service";
|
||||
@@ -46,3 +48,19 @@ export async function requireAuth(c: Context, next: Next) {
|
||||
|
||||
return c.json({ error: "Authentication required" }, 401);
|
||||
}
|
||||
|
||||
export async function requireAdmin(c: Context, next: Next) {
|
||||
const db = c.get("db");
|
||||
const userId = c.get("userId");
|
||||
if (!userId) {
|
||||
return c.json({ error: "Authentication required" }, 401);
|
||||
}
|
||||
const [user] = await db
|
||||
.select({ isAdmin: users.isAdmin })
|
||||
.from(users)
|
||||
.where(eq(users.id, userId));
|
||||
if (!user?.isAdmin) {
|
||||
return c.json({ error: "Forbidden" }, 403);
|
||||
}
|
||||
return next();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user