a control panel for my server
1import { Context, Next } from "hono";
2import { getSession, checkRole, SessionPayload } from "./auth";
3
4declare module "hono" {
5 interface ContextVariableMap {
6 session: SessionPayload;
7 }
8}
9
10export async function authMiddleware(c: Context, next: Next) {
11 const session = await getSession(c);
12
13 if (!session) {
14 return c.redirect("/auth/login");
15 }
16
17 if (!checkRole(session)) {
18 return c.text("Forbidden: insufficient permissions", 403);
19 }
20
21 c.set("session", session);
22 await next();
23}
24
25export async function apiAuthMiddleware(c: Context, next: Next) {
26 const session = await getSession(c);
27
28 if (!session) {
29 return c.json({ error: "Unauthorized" }, 401);
30 }
31
32 if (!checkRole(session)) {
33 return c.json({ error: "Forbidden" }, 403);
34 }
35
36 c.set("session", session);
37 await next();
38}