All files / middleware ho-auth.middleware.ts

100% Statements 15/15
100% Branches 4/4
100% Functions 3/3
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67                                                            1x 5x 5x       5x     1x 1x       5x 5x 5x 5x                   1x 4x 4x 3x   1x        
// Homeowner authentication middleware
import type { MiddlewareHandler } from "hono";
import { getDb } from "../db";
import { createDualCache, type DualCache } from "../lib/cache";
import { UnauthorizedError } from "../lib/errors";
import {
	getCachedHoSession,
	invalidateHoSession,
} from "../lib/ho-session-cache";
import { handleError } from "../lib/response";
 
type HoUser = {
	id: string;
	name: string;
	email: string;
};
 
type HoVariables = {
	hoUser: HoUser | null;
	db: ReturnType<typeof getDb>;
	cache: DualCache;
};
 
/**
 * Attach homeowner session to context.
 * Sets c.get("hoUser") to the authenticated homeowner or null.
 */
export const hoAuthSessionMiddleware: MiddlewareHandler<{
	Bindings: CloudflareBindings;
	Variables: HoVariables;
}> = async (c, next) => {
	const db = getDb(c.env.DB);
	const dualCache = createDualCache(c.env.KV_CACHE);
	// A factory, not an instance: getCachedHoSession only calls it on a cache
	// miss, so a request that hits the cache never loads Better Auth (~2.4 MB of
	// module evaluation with kysely, jose and the OpenTelemetry conventions).
	const session = await getCachedHoSession(
		dualCache,
		async () => {
			const { createHomeownerAuth } = await import("../lib/homeowner-auth");
			return createHomeownerAuth(db, c.env);
		},
		c.req.raw.headers,
	);
	c.set("hoUser", session?.user ?? null);
	c.set("db", db);
	c.set("cache", dualCache);
	await next();
};
 
/**
 * Require authenticated homeowner.
 * Returns 401 if no homeowner session is present.
 */
export const requireHoAuth: MiddlewareHandler<{
	Bindings: CloudflareBindings;
	Variables: HoVariables;
}> = async (c, next) => {
	const user = c.get("hoUser");
	if (!user) {
		return handleError(c, new UnauthorizedError("Authentication required"));
	}
	await next();
};
 
export { invalidateHoSession };