2023-08-30 03:22:47 +00:00
|
|
|
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;
|
2023-10-04 09:53:57 +05:30
|
|
|
currentPassword: string;
|
2023-06-09 18:21:18 +10:00
|
|
|
};
|
|
|
|
|
|
2023-10-04 09:53:57 +05:30
|
|
|
export const updatePassword = async ({
|
|
|
|
|
userId,
|
|
|
|
|
password,
|
|
|
|
|
currentPassword,
|
|
|
|
|
}: UpdatePasswordOptions) => {
|
2023-06-09 18:21:18 +10:00
|
|
|
// Existence check
|
2023-08-30 03:22:47 +00:00
|
|
|
const user = await prisma.user.findFirstOrThrow({
|
2023-06-09 18:21:18 +10:00
|
|
|
where: {
|
|
|
|
|
id: userId,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
2023-10-04 09:53:57 +05:30
|
|
|
if (!user.password) {
|
|
|
|
|
throw new Error('User has no password');
|
|
|
|
|
}
|
2023-06-09 18:21:18 +10:00
|
|
|
|
2023-10-04 09:53:57 +05:30
|
|
|
const isCurrentPasswordValid = await compare(currentPassword, user.password);
|
|
|
|
|
if (!isCurrentPasswordValid) {
|
|
|
|
|
throw new Error('Current password is incorrect.');
|
|
|
|
|
}
|
2023-08-30 03:22:47 +00:00
|
|
|
|
2023-10-04 09:53:57 +05:30
|
|
|
// 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.');
|
2023-08-30 03:22:47 +00:00
|
|
|
}
|
|
|
|
|
|
2023-10-04 09:53:57 +05:30
|
|
|
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: {
|
2023-10-04 09:53:57 +05:30
|
|
|
password: hashedNewPassword,
|
2023-06-09 18:21:18 +10:00
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return updatedUser;
|
|
|
|
|
};
|