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

126 lines
3.5 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";
2024-12-21 21:01:12 -05:00
import logger from "@server/logger";
2024-12-21 21:01:12 -05:00
export const verifyTotpBody = z
.object({
code: z.string()
})
.strict();
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 21:55:49 -04:00
);
}
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 {
const valid = await verifyTotpCode(
code,
user.twoFactorSecret,
user.userId
);
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 })
2024-10-13 17:13:47 -04:00
.where(eq(users.userId, user.userId));
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({
2024-10-13 17:13:47 -04:00
userId: user.userId,
2024-12-21 21:01:12 -05:00
codeHash: hash
2024-10-05 17:01:49 -04:00
});
}
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,
2024-12-21 21:01:12 -05:00
...(valid && codes ? { backupCodes: codes } : {})
2024-10-05 17:01:49 -04:00
},
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",
2024-12-21 21:01:12 -05:00
status: HttpCode.OK
2024-10-04 23:14:40 -04:00
});
} catch (error) {
2024-12-21 21:01:12 -05:00
logger.error(error);
2024-10-04 23:14:40 -04:00
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to verify two-factor authentication code"
)
2024-10-04 23:14:40 -04:00
);
}
}
2024-10-05 15:31:28 -04:00
async function generateBackupCodes(): Promise<string[]> {
const codes = [];
for (let i = 0; i < 10; i++) {
2024-12-22 17:20:24 -05:00
const code = generateRandomString(6, alphabet("0-9", "A-Z", "a-z"));
2024-10-05 15:31:28 -04:00
codes.push(code);
}
return codes;
}