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

155 lines
4.4 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";
2025-01-01 21:41:31 -05:00
import { response } from "@server/lib";
2024-10-02 20:49:05 -04:00
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";
2025-01-01 21:41:31 -05:00
import { verifyTotpCode } from "@server/auth/totp";
2024-12-21 21:01:12 -05:00
import logger from "@server/logger";
import { sendEmail } from "@server/emails";
import TwoFactorAuthNotification from "@server/emails/templates/TwoFactorAuthNotification";
2025-01-01 21:41:31 -05:00
import config from "@server/lib/config";
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
2024-12-24 16:00:02 -05:00
await db.transaction(async (trx) => {
await trx
.update(users)
.set({ twoFactorEnabled: true })
.where(eq(users.userId, user.userId));
2024-10-05 17:01:49 -04:00
2024-12-24 16:00:02 -05:00
const backupCodes = await generateBackupCodes();
codes = backupCodes;
for (const code of backupCodes) {
const hash = await hashPassword(code);
2024-10-05 17:01:49 -04:00
2024-12-24 16:00:02 -05:00
await trx.insert(twoFactorBackupCodes).values({
userId: user.userId,
codeHash: hash
});
}
});
2024-10-04 23:14:40 -04:00
}
2024-10-02 20:49:05 -04:00
2024-12-23 23:59:15 -05:00
if (!valid) {
2025-01-27 22:43:32 -05:00
if (config.getRawConfig().app.log_failed_attempts) {
logger.info(
`Two-factor authentication code is incorrect. Email: ${user.email}. IP: ${req.ip}.`
);
}
2024-12-23 23:59:15 -05:00
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Invalid two-factor authentication code"
)
);
}
sendEmail(
TwoFactorAuthNotification({
email: user.email,
enabled: true
}),
{
to: user.email,
from: config.getRawConfig().email?.no_reply,
subject: "Two-factor authentication 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;
}