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

196 lines
5.9 KiB
TypeScript
Raw Normal View History

2025-01-01 21:41:31 -05:00
import config from "@server/lib/config";
2024-10-05 17:01: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 HttpCode from "@server/types/HttpCode";
2025-01-01 21:41:31 -05:00
import { response } from "@server/lib";
2024-10-05 17:01:49 -04:00
import { db } from "@server/db";
import { passwordResetTokens, users } from "@server/db/schema";
import { eq } from "drizzle-orm";
2024-12-22 16:59:30 -05:00
import { hashPassword, verifyPassword } from "@server/auth/password";
2025-01-01 21:41:31 -05:00
import { verifyTotpCode } from "@server/auth/totp";
2024-10-05 17:01:49 -04:00
import { isWithinExpirationDate } from "oslo";
2025-01-01 21:41:31 -05:00
import { invalidateAllSessions } from "@server/auth/sessions/app";
2024-12-21 21:01:12 -05:00
import logger from "@server/logger";
2024-12-22 17:27:09 -05:00
import ConfirmPasswordReset from "@server/emails/templates/NotifyResetPassword";
import { sendEmail } from "@server/emails";
2025-01-01 21:41:31 -05:00
import { passwordSchema } from "@server/auth/passwordSchema";
2024-10-05 17:01:49 -04:00
2024-12-21 21:01:12 -05:00
export const resetPasswordBody = z
.object({
2025-01-21 18:36:50 -05:00
email: z
.string()
.email()
.transform((v) => v.toLowerCase()),
2024-12-22 16:59:30 -05:00
token: z.string(), // reset secret code
2024-12-21 21:01:12 -05:00
newPassword: passwordSchema,
2024-12-22 16:59:30 -05:00
code: z.string().optional() // 2fa code
2024-12-21 21:01:12 -05:00
})
.strict();
2024-10-05 17:01:49 -04:00
export type ResetPasswordBody = z.infer<typeof resetPasswordBody>;
export type ResetPasswordResponse = {
codeRequested?: boolean;
};
export async function resetPassword(
req: Request,
res: Response,
2024-12-21 21:01:12 -05:00
next: NextFunction
2024-10-05 17:01:49 -04:00
): Promise<any> {
const parsedBody = resetPasswordBody.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-05 17:01:49 -04:00
);
}
2024-12-22 16:59:30 -05:00
const { token, newPassword, code, email } = parsedBody.data;
2024-10-05 17:01:49 -04:00
try {
const resetRequest = await db
.select()
.from(passwordResetTokens)
2024-12-22 16:59:30 -05:00
.where(eq(passwordResetTokens.email, email));
if (!resetRequest || !resetRequest.length) {
2025-01-27 22:43:32 -05:00
if (config.getRawConfig().app.log_failed_attempts) {
logger.info(
`Password reset code is incorrect. Email: ${email}. IP: ${req.ip}.`
);
}
2024-12-22 16:59:30 -05:00
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Invalid password reset token"
)
);
}
2024-10-05 17:01:49 -04:00
2024-12-22 16:59:30 -05:00
if (!isWithinExpirationDate(new Date(resetRequest[0].expiresAt))) {
2024-10-05 17:01:49 -04:00
return next(
createHttpError(
HttpCode.BAD_REQUEST,
2024-12-22 16:59:30 -05:00
"Password reset token has expired"
2024-12-21 21:01:12 -05:00
)
2024-10-05 17:01:49 -04:00
);
}
const user = await db
.select()
.from(users)
2024-10-13 17:13:47 -04:00
.where(eq(users.userId, resetRequest[0].userId));
2024-10-05 17:01:49 -04:00
if (!user || !user.length) {
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
2024-12-21 21:01:12 -05:00
"User not found"
)
2024-10-05 17:01:49 -04:00
);
}
if (user[0].twoFactorEnabled) {
if (!code) {
return response<ResetPasswordResponse>(res, {
data: { codeRequested: true },
success: true,
error: false,
message: "Two-factor authentication required",
2024-12-21 21:01:12 -05:00
status: HttpCode.ACCEPTED
2024-10-05 17:01:49 -04:00
});
}
const validOTP = await verifyTotpCode(
code!,
user[0].twoFactorSecret!,
2024-12-21 21:01:12 -05:00
user[0].userId
2024-10-05 17:01:49 -04:00
);
if (!validOTP) {
2025-01-27 22:43:32 -05:00
if (config.getRawConfig().app.log_failed_attempts) {
logger.info(
`Two-factor authentication code is incorrect. Email: ${email}. IP: ${req.ip}.`
);
}
2024-10-05 17:01:49 -04:00
return next(
createHttpError(
HttpCode.BAD_REQUEST,
2024-12-21 21:01:12 -05:00
"Invalid two-factor authentication code"
)
2024-10-05 17:01:49 -04:00
);
}
}
2024-12-22 16:59:30 -05:00
const isTokenValid = await verifyPassword(
token,
resetRequest[0].tokenHash
);
if (!isTokenValid) {
2025-01-27 22:43:32 -05:00
if (config.getRawConfig().app.log_failed_attempts) {
logger.info(
`Password reset code is incorrect. Email: ${email}. IP: ${req.ip}.`
);
}
2024-12-22 16:59:30 -05:00
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Invalid password reset token"
)
);
}
2024-10-05 17:01:49 -04:00
const passwordHash = await hashPassword(newPassword);
2024-12-24 16:00:02 -05:00
await db.transaction(async (trx) => {
await trx
.update(users)
.set({ passwordHash })
.where(eq(users.userId, resetRequest[0].userId));
await trx
.delete(passwordResetTokens)
.where(eq(passwordResetTokens.email, email));
});
2024-10-05 17:01:49 -04:00
2025-02-14 13:12:29 -05:00
try {
await invalidateAllSessions(resetRequest[0].userId);
} catch (e) {
logger.error("Failed to invalidate user sessions", e);
}
try {
await sendEmail(ConfirmPasswordReset({ email }), {
from: config.getNoReplyEmail(),
to: email,
subject: "Password Reset Confirmation"
});
} catch (e) {
logger.error("Failed to send password reset confirmation email", e);
}
2024-10-05 17:01:49 -04:00
return response<ResetPasswordResponse>(res, {
data: null,
success: true,
error: false,
message: "Password reset successfully",
2024-12-21 21:01:12 -05:00
status: HttpCode.OK
2024-10-05 17:01:49 -04:00
});
} catch (e) {
2024-12-21 21:01:12 -05:00
logger.error(e);
2024-10-05 17:01:49 -04:00
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
2024-12-21 21:01:12 -05:00
"Failed to reset password"
)
2024-10-05 17:01:49 -04:00
);
}
}