2024-03-07 18:30:22 +11:00
|
|
|
import { compare, hash } from '@node-rs/bcrypt';
|
2025-01-02 15:33:37 +11:00
|
|
|
import { UserSecurityAuditLogType } from '@prisma/client';
|
2023-06-09 18:21:18 +10:00
|
|
|
|
2024-01-30 17:31:27 +11:00
|
|
|
import { SALT_ROUNDS } from '@documenso/lib/constants/auth';
|
|
|
|
|
import type { RequestMetadata } from '@documenso/lib/universal/extract-request-metadata';
|
2023-06-09 18:21:18 +10:00
|
|
|
import { prisma } from '@documenso/prisma';
|
|
|
|
|
|
2024-12-06 16:01:24 +09:00
|
|
|
import { AppError } from '../../errors/app-error';
|
|
|
|
|
|
2023-06-09 18:21:18 +10:00
|
|
|
export type UpdatePasswordOptions = {
|
|
|
|
|
userId: number;
|
|
|
|
|
password: string;
|
2023-10-04 09:53:57 +05:30
|
|
|
currentPassword: string;
|
2024-01-30 17:31:27 +11:00
|
|
|
requestMetadata?: RequestMetadata;
|
2023-06-09 18:21:18 +10:00
|
|
|
};
|
|
|
|
|
|
2023-10-04 09:53:57 +05:30
|
|
|
export const updatePassword = async ({
|
|
|
|
|
userId,
|
|
|
|
|
password,
|
|
|
|
|
currentPassword,
|
2024-01-30 17:31:27 +11:00
|
|
|
requestMetadata,
|
2023-10-04 09:53:57 +05:30
|
|
|
}: 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) {
|
2024-12-06 16:01:24 +09:00
|
|
|
throw new AppError('NO_PASSWORD');
|
2023-10-04 09:53:57 +05:30
|
|
|
}
|
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) {
|
2024-12-06 16:01:24 +09:00
|
|
|
throw new AppError('INCORRECT_PASSWORD');
|
2023-10-04 09:53:57 +05:30
|
|
|
}
|
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) {
|
2024-12-06 16:01:24 +09:00
|
|
|
throw new AppError('SAME_PASSWORD');
|
2023-08-30 03:22:47 +00:00
|
|
|
}
|
|
|
|
|
|
2023-10-04 09:53:57 +05:30
|
|
|
const hashedNewPassword = await hash(password, SALT_ROUNDS);
|
|
|
|
|
|
2024-01-30 17:31:27 +11:00
|
|
|
return await prisma.$transaction(async (tx) => {
|
|
|
|
|
await tx.userSecurityAuditLog.create({
|
|
|
|
|
data: {
|
|
|
|
|
userId,
|
|
|
|
|
type: UserSecurityAuditLogType.PASSWORD_UPDATE,
|
|
|
|
|
userAgent: requestMetadata?.userAgent,
|
|
|
|
|
ipAddress: requestMetadata?.ipAddress,
|
|
|
|
|
},
|
|
|
|
|
});
|
2023-06-09 18:21:18 +10:00
|
|
|
|
2024-01-30 17:31:27 +11:00
|
|
|
return await tx.user.update({
|
|
|
|
|
where: {
|
|
|
|
|
id: userId,
|
|
|
|
|
},
|
|
|
|
|
data: {
|
|
|
|
|
password: hashedNewPassword,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
});
|
2023-06-09 18:21:18 +10:00
|
|
|
};
|