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;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const updatePassword = async ({ userId, password }: UpdatePasswordOptions) => {
|
|
|
|
|
// 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,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const hashedPassword = await hash(password, SALT_ROUNDS);
|
|
|
|
|
|
2023-08-30 03:22:47 +00:00
|
|
|
// Compare the new password with the old password
|
|
|
|
|
const isSamePassword = await compare(password, user.password as string);
|
|
|
|
|
|
|
|
|
|
if (isSamePassword) {
|
2023-08-30 14:01:30 +10:00
|
|
|
throw new Error('Your new password cannot be the same as your old password.');
|
2023-08-30 03:22:47 +00:00
|
|
|
}
|
|
|
|
|
|
2023-06-09 18:21:18 +10:00
|
|
|
const updatedUser = await prisma.user.update({
|
|
|
|
|
where: {
|
|
|
|
|
id: userId,
|
|
|
|
|
},
|
|
|
|
|
data: {
|
|
|
|
|
password: hashedPassword,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return updatedUser;
|
|
|
|
|
};
|