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

148 lines
4.1 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";
2025-01-01 21:41:31 -05:00
import { response } from "@server/lib";
2024-10-02 21:55:49 -04:00
import { db } from "@server/db";
2025-06-04 12:02:07 -04:00
import { User, users } from "@server/db";
2025-07-13 21:43:09 -07:00
import { eq, and } from "drizzle-orm";
2024-10-02 21:55:49 -04:00
import { createTOTPKeyURI } from "oslo/otp";
2024-12-21 21:01:12 -05:00
import logger from "@server/logger";
2024-12-22 16:59:30 -05:00
import { verifyPassword } from "@server/auth/password";
2025-01-01 21:41:31 -05:00
import { unauthorized } from "@server/auth/unauthorizedResponse";
2025-04-13 17:57:27 -04:00
import { UserType } from "@server/types/UserTypes";
2025-07-13 21:43:09 -07:00
import { verifySession } from "@server/auth/sessions/verifySession";
import config from "@server/lib/config";
2024-10-02 21:55:49 -04:00
2024-12-21 21:01:12 -05:00
export const requestTotpSecretBody = z
.object({
2025-07-13 21:43:09 -07:00
password: z.string(),
email: z.string().email().optional()
2024-12-21 21:01:12 -05:00
})
.strict();
2024-10-02 21:55:49 -04:00
export type RequestTotpSecretBody = z.infer<typeof requestTotpSecretBody>;
export type RequestTotpSecretResponse = {
secret: string;
uri: string;
2024-10-02 21:55:49 -04:00
};
export async function requestTotpSecret(
req: Request,
res: Response,
2024-12-21 21:01:12 -05:00
next: NextFunction
2024-10-02 21:55:49 -04:00
): Promise<any> {
const parsedBody = requestTotpSecretBody.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
2024-12-21 21:01:12 -05:00
fromError(parsedBody.error).toString()
)
2024-10-02 21:55:49 -04:00
);
}
2025-07-13 21:43:09 -07:00
const { password, email } = parsedBody.data;
2024-10-02 21:55:49 -04:00
2025-07-13 21:43:09 -07:00
const { user: sessionUser, session: existingSession } = await verifySession(req);
let user: User | null = sessionUser;
if (!existingSession) {
if (!email) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Email is required for two-factor authentication setup"
)
);
}
const [res] = await db
.select()
.from(users)
.where(
and(eq(users.type, UserType.Internal), eq(users.email, email))
);
user = res;
}
2024-10-02 21:55:49 -04:00
2025-07-13 21:43:09 -07:00
if (!user) {
if (config.getRawConfig().app.log_failed_attempts) {
logger.info(
`Username or password incorrect. Email: ${email}. IP: ${req.ip}.`
);
}
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"Username or password is incorrect"
)
);
}
2024-10-02 21:55:49 -04:00
2025-04-13 17:57:27 -04:00
if (user.type !== UserType.Internal) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Two-factor authentication is not supported for external users"
)
);
}
2024-10-04 23:14:40 -04:00
try {
2025-07-13 21:43:09 -07:00
const validPassword = await verifyPassword(
password,
user.passwordHash!
);
2024-10-04 23:14:40 -04:00
if (!validPassword) {
return next(unauthorized());
}
if (user.twoFactorEnabled) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
2024-12-21 21:01:12 -05:00
"User has already enabled two-factor authentication"
)
2024-10-04 23:14:40 -04:00
);
}
const hex = crypto.getRandomValues(new Uint8Array(20));
const secret = encodeHex(hex);
2025-07-13 21:57:24 -07:00
const uri = createTOTPKeyURI(
"Pangolin",
user.email!,
hex
);
2024-10-04 23:14:40 -04:00
await db
.update(users)
.set({
2024-12-21 21:01:12 -05:00
twoFactorSecret: secret
2024-10-04 23:14:40 -04:00
})
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
2024-10-04 23:14:40 -04:00
},
success: true,
error: false,
message: "TOTP secret generated successfully",
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-02 21:55:49 -04:00
return next(
createHttpError(
2024-10-04 23:14:40 -04:00
HttpCode.INTERNAL_SERVER_ERROR,
2024-12-21 21:01:12 -05:00
"Failed to generate TOTP secret"
)
2024-10-02 21:55:49 -04:00
);
}
}