All files / middleware ho-auth.middleware.ts

100% Statements 14/14
100% Branches 4/4
100% Functions 2/2
100% Lines 14/14

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                                                        1x 4x 4x 4x 4x 4x 4x 4x 4x                   1x 4x 4x 3x   1x        
// Homeowner authentication middleware
import type { MiddlewareHandler } from "hono";
import { getDb } from "../db";
import { createHomeownerAuth } from "../lib/homeowner-auth";
import { getCachedHoSession, invalidateHoSession } from "../lib/ho-session-cache";
import { createDualCache, type DualCache } from "../lib/cache";
import { UnauthorizedError } from "../lib/errors";
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 auth = createHomeownerAuth(db, c.env);
	const dualCache = createDualCache(c.env.KV_CACHE);
	const session = await getCachedHoSession(dualCache, auth, 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 };