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

53 lines
1.2 KiB
TypeScript
Raw Normal View History

import { compare, hash } from 'bcrypt';
2023-06-09 18:21:18 +10:00
import { prisma } from '@documenso/prisma';
import { SALT_ROUNDS } from '../../constants/auth';
export type UpdatePasswordOptions = {
userId: number;
password: string;
currentPassword: string;
2023-06-09 18:21:18 +10:00
};
export const updatePassword = async ({
userId,
password,
currentPassword,
}: UpdatePasswordOptions) => {
2023-06-09 18:21:18 +10:00
// Existence check
const user = await prisma.user.findFirstOrThrow({
2023-06-09 18:21:18 +10:00
where: {
id: userId,
},
});
if (!user.password) {
throw new Error('User has no password');
}
2023-06-09 18:21:18 +10:00
const isCurrentPasswordValid = await compare(currentPassword, user.password);
if (!isCurrentPasswordValid) {
throw new Error('Current password is incorrect.');
}
// Compare the new password with the old password
const isSamePassword = await compare(password, user.password);
if (isSamePassword) {
throw new Error('Your new password cannot be the same as your old password.');
}
const hashedNewPassword = await hash(password, SALT_ROUNDS);
2023-06-09 18:21:18 +10:00
const updatedUser = await prisma.user.update({
where: {
id: userId,
},
data: {
password: hashedNewPassword,
2023-06-09 18:21:18 +10:00
},
});
return updatedUser;
};