All files / apps/web/src/handlers/auth confirm-email.ts

100% Statements 9/9
100% Branches 2/2
100% Functions 1/1
100% Lines 9/9

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                  6x                       2x 2x           2x 1x         1x         1x       1x 1x        
import { TRPCError } from "@trpc/server";
import { z } from "zod";
 
import { AUTH_COOKIE } from "~app/utils/auth";
import { confirmEmailTokenSchema } from "~app/utils/validation";
import { createAuthorizationSession } from "~web/handlers/auth/utils";
import { unauthProcedure } from "~web/handlers/trpc";
import { setCookie } from "~web/utils/cookies";
 
export const procedure = unauthProcedure
	.meta({
		title: "Confirm email",
		description:
			"Confirms an account's email using a confirmation token and logs the account in.",
	})
	.input(
		z.strictObject({
			token: confirmEmailTokenSchema,
		}),
	)
	.mutation(async ({ input, ctx }) => {
		const { database } = ctx;
		const account = await database
			.selectFrom("users")
			.select(["id", "email"])
			.where("confirmationToken", "=", input.token)
			.limit(1)
			.executeTakeFirst();
		if (!account) {
			throw new TRPCError({
				code: "NOT_FOUND",
				message: `There is no account with confirmation token "${input.token}".`,
			});
		}
		await database
			.updateTable("users")
			.set({ confirmationToken: null, confirmationTokenTimestamp: null })
			.where("users.id", "=", account.id)
			.executeTakeFirst();
		const { authToken, expirationDate } = await createAuthorizationSession(
			ctx,
			account.id,
		);
		setCookie(ctx, AUTH_COOKIE, authToken, { expires: expirationDate });
		return {
			email: account.email,
		};
	});