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

95 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-10-02 21:55:49 -04:00
import { Request, Response, NextFunction } from "express";
import createHttpError from "http-errors";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import { encodeHex } from "oslo/encoding";
import HttpCode from "@server/types/HttpCode";
2024-10-03 20:55:54 -04:00
import { unauthorized } from "@server/auth";
2024-10-02 21:55:49 -04:00
import { response } from "@server/utils";
import { db } from "@server/db";
2024-10-03 20:55:54 -04:00
import { User, users } from "@server/db/schema";
2024-10-02 21:55:49 -04:00
import { eq } from "drizzle-orm";
import { verify } from "@node-rs/argon2";
import { createTOTPKeyURI } from "oslo/otp";
2024-10-12 18:21:31 -04:00
import config from "@server/config";
2024-10-02 21:55:49 -04:00
export const requestTotpSecretBody = z.object({
password: z.string(),
});
export type RequestTotpSecretBody = z.infer<typeof requestTotpSecretBody>;
export type RequestTotpSecretResponse = {
secret: string;
};
export async function requestTotpSecret(
req: Request,
res: Response,
next: NextFunction,
): Promise<any> {
const parsedBody = requestTotpSecretBody.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString(),
),
);
}
const { password } = parsedBody.data;
2024-10-03 20:55:54 -04:00
const user = req.user as User;
2024-10-02 21:55:49 -04:00
2024-10-04 23:14:40 -04:00
try {
const validPassword = await verify(user.passwordHash, password, {
memoryCost: 19456,
timeCost: 2,
outputLen: 32,
parallelism: 1,
});
if (!validPassword) {
return next(unauthorized());
}
if (user.twoFactorEnabled) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"User has already enabled two-factor authentication",
),
);
}
const hex = crypto.getRandomValues(new Uint8Array(20));
const secret = encodeHex(hex);
2024-10-12 18:21:31 -04:00
const uri = createTOTPKeyURI(config.app.name, user.email, hex);
2024-10-04 23:14:40 -04:00
await db
.update(users)
.set({
twoFactorSecret: secret,
})
2024-10-13 17:13:47 -04:00
.where(eq(users.userId, user.userId));
2024-10-02 21:55:49 -04:00
2024-10-04 23:14:40 -04:00
return response<RequestTotpSecretResponse>(res, {
data: {
secret: uri,
},
success: true,
error: false,
message: "TOTP secret generated successfully",
status: HttpCode.OK,
});
} catch (error) {
2024-10-02 21:55:49 -04:00
return next(
createHttpError(
2024-10-04 23:14:40 -04:00
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to generate TOTP secret",
2024-10-02 21:55:49 -04:00
),
);
}
}