Skip to content
File

Blob: src/worker/auth/middleware.ts

typescript53 lines
1import { createMiddleware } from "hono/factory";
2 
3import type { AppContext, AppEnv } from "@/worker/hono";
4import { findUserById } from "@/worker/db/d1/repositories";
5import { HttpError } from "@/worker/http";
6import { clearSessionCookie, readSessionCookie, setSessionCookie } from "@/worker/auth/cookies";
7import { maybeRefreshSession, readSession, type SessionRecord } from "@/worker/auth/sessions";
8 
9const loadSession = async (c: AppContext): Promise<{ sessionId: string; session: SessionRecord }> => {
10 const sessionId = readSessionCookie(c);
11 
12 if (!sessionId) {
13 throw new HttpError(403, "missing_session", "Missing session cookie.");
14 }
15 
16 const session = await readSession(c.env, sessionId);
17 
18 if (!session) {
19 clearSessionCookie(c);
20 throw new HttpError(403, "invalid_session", "Session is missing or expired.");
21 }
22 
23 c.set("sessionId", sessionId);
24 c.set("session", session);
25 
26 return { sessionId, session };
27};
28 
29export const requireAuth = createMiddleware<AppEnv>(async (c, next) => {
30 const { sessionId, session } = await loadSession(c);
31 const user = await findUserById(c.get("db"), session.userId);
32 
33 if (!user) {
34 clearSessionCookie(c);
35 throw new HttpError(403, "invalid_session", "Session user no longer exists.");
36 }
37 
38 if (user.disabledAt !== null) {
39 clearSessionCookie(c);
40 throw new HttpError(403, "user_disabled", "User account is disabled.");
41 }
42 
43 const refreshedSession = await maybeRefreshSession(c.env, sessionId, session);
44 if (refreshedSession !== session) {
45 setSessionCookie(c, sessionId);
46 }
47 
48 c.set("session", refreshedSession);
49 c.set("user", user);
50 
51 await next();
52});