Files
sign/packages/lib/server-only/user/reset-password.ts

63 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-09-18 14:03:33 +00:00
import { compare, hash } from 'bcrypt';
import { prisma } from '@documenso/prisma';
import { SALT_ROUNDS } from '../../constants/auth';
import { sendResetPassword } from '../auth/send-reset-password';
2023-09-18 14:03:33 +00:00
export type ResetPasswordOptions = {
token: string;
password: string;
};
export const resetPassword = async ({ token, password }: ResetPasswordOptions) => {
if (!token) {
throw new Error('Invalid token provided. Please try again.');
2023-09-18 14:03:33 +00:00
}
2023-09-19 13:34:54 +00:00
const foundToken = await prisma.passwordResetToken.findFirst({
2023-09-18 14:03:33 +00:00
where: {
token,
},
include: {
User: true,
},
});
if (!foundToken) {
throw new Error('Invalid token provided. Please try again.');
2023-09-18 14:03:33 +00:00
}
const now = new Date();
if (now > foundToken.expiry) {
throw new Error('Token has expired. Please try again.');
2023-09-18 14:03:33 +00:00
}
2023-09-19 13:34:54 +00:00
const isSamePassword = await compare(password, foundToken.User.password || '');
2023-09-18 14:03:33 +00:00
if (isSamePassword) {
throw new Error('Your new password cannot be the same as your old password.');
}
const hashedPassword = await hash(password, SALT_ROUNDS);
2023-09-19 13:34:54 +00:00
await prisma.$transaction([
2023-09-18 14:03:33 +00:00
prisma.user.update({
where: {
id: foundToken.userId,
},
data: {
password: hashedPassword,
},
}),
prisma.passwordResetToken.deleteMany({
where: {
userId: foundToken.userId,
},
}),
]);
await sendResetPassword({ userId: foundToken.userId });
2023-09-18 14:03:33 +00:00
};