All files / routes/auth accept-terms.ts

100% Statements 13/13
100% Branches 6/6
100% Functions 1/1
100% Lines 13/13

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                            5x                           5x 5x 5x 1x     4x 1x           3x 3x 2x           1x 1x               1x        
import { Hono } from "hono";
import { eq } from "drizzle-orm";
import { users } from "../../db/schema";
import { CURRENT_TERMS_VERSION } from "../../lib/terms";
import type { getDb } from "../../db";
import type { Dal } from "../../dal";
import type { Services } from "../../services";
import type { DualCache } from "../../lib/cache";
import type { createAuth } from "../../lib/auth";
 
type AuthSession = NonNullable<
	Awaited<ReturnType<ReturnType<typeof createAuth>["api"]["getSession"]>>
>;
 
const acceptTermsRoute = new Hono<{
	Bindings: CloudflareBindings;
	Variables: {
		user: AuthSession["user"] | null;
		session: AuthSession["session"] | null;
		dal: Dal;
		services: Services;
		db: ReturnType<typeof getDb>;
		cache: DualCache;
		proId: string;
		proRole: string;
	};
}>();
 
acceptTermsRoute.patch("/accept-terms", async (c) => {
	const user = c.get("user");
	if (!user) {
		return c.json({ error: "Unauthorized" }, 401);
	}
 
	if (!CURRENT_TERMS_VERSION) {
		return c.json(
			{ error: "Terms enforcement is not currently active" },
			400,
		);
	}
 
	const body = await c.req.json<{ terms_version?: string }>();
	if (body.terms_version !== CURRENT_TERMS_VERSION) {
		return c.json(
			{ error: `Invalid terms version. Expected ${CURRENT_TERMS_VERSION}` },
			400,
		);
	}
 
	const db = c.get("db");
	await db
		.update(users)
		.set({
			termsAcceptedAt: new Date(),
			termsVersion: CURRENT_TERMS_VERSION,
		})
		.where(eq(users.id, user.id));
 
	return c.json({ success: true });
});
 
export default acceptTermsRoute;