fosrl.pangolin/server/routers/auth/verifyTotp.ts

118 lines
3.3 KiB
TypeScript
Raw Normal View History

import { Request, Response, NextFunction } from "express";
import createHttpError from "http-errors";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import HttpCode from "@server/types/HttpCode";
2024-10-02 20:49:05 -04:00
import { response } from "@server/utils";
import { db } from "@server/db";
2024-10-05 15:31:28 -04:00
import { twoFactorBackupCodes, User, users } from "@server/db/schema";
2024-10-02 20:49:05 -04:00
import { eq } from "drizzle-orm";
2024-10-05 15:31:28 -04:00
import { alphabet, generateRandomString } from "oslo/crypto";
2024-10-05 22:31:30 -04:00
import { hashPassword } from "@server/auth/password";
import { verifyTotpCode } from "@server/auth/2fa";
export const verifyTotpBody = z.object({
code: z.string(),
});
export type VerifyTotpBody = z.infer<typeof verifyTotpBody>;
export type VerifyTotpResponse = {
valid: boolean;
2024-10-05 17:01:49 -04:00
backupCodes?: string[];
};
export async function verifyTotp(
req: Request,
res: Response,
next: NextFunction,
): Promise<any> {
const parsedBody = verifyTotpBody.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString(),
),
);
}
const { code } = parsedBody.data;
2024-10-03 20:55:54 -04:00
const user = req.user as User;
2024-10-02 21:55:49 -04:00
if (user.twoFactorEnabled) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Two-factor authentication is already enabled",
),
);
}
2024-10-02 20:49:05 -04:00
if (!user.twoFactorSecret) {
2024-10-02 21:55:49 -04:00
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"User has not requested two-factor authentication",
),
2024-10-02 20:49:05 -04:00
);
}
2024-10-04 23:14:40 -04:00
try {
2024-10-05 15:45:01 -04:00
const valid = await verifyTotpCode(code, user.twoFactorSecret, user.id);
2024-10-02 20:49:05 -04:00
2024-10-05 17:01:49 -04:00
let codes;
2024-10-04 23:14:40 -04:00
if (valid) {
// if valid, enable two-factor authentication; the totp secret is no longer temporary
await db
.update(users)
.set({ twoFactorEnabled: true })
.where(eq(users.id, user.id));
2024-10-05 17:01:49 -04:00
const backupCodes = await generateBackupCodes();
codes = backupCodes;
for (const code of backupCodes) {
const hash = await hashPassword(code);
await db.insert(twoFactorBackupCodes).values({
userId: user.id,
codeHash: hash,
});
}
2024-10-04 23:14:40 -04:00
}
2024-10-02 20:49:05 -04:00
2024-10-05 17:01:49 -04:00
// TODO: send email to user confirming two-factor authentication is enabled
2024-10-05 15:31:28 -04:00
return response<VerifyTotpResponse>(res, {
2024-10-05 17:01:49 -04:00
data: {
valid,
...(valid && codes ? { backupCodes: codes } : {}),
},
2024-10-04 23:14:40 -04:00
success: true,
error: false,
message: valid
? "Code is valid. Two-factor is now enabled"
: "Code is invalid",
status: HttpCode.OK,
});
} catch (error) {
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to verify two-factor authentication code",
),
);
}
}
2024-10-05 15:31:28 -04:00
async function generateBackupCodes(): Promise<string[]> {
const codes = [];
for (let i = 0; i < 10; i++) {
const code = generateRandomString(8, alphabet("0-9", "A-Z", "a-z"));
codes.push(code);
}
return codes;
}