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

67 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-03-07 18:30:22 +11:00
import { compare, hash } from '@node-rs/bcrypt';
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-01-30 17:31:27 +11:00
import { UserSecurityAuditLogType } from '@documenso/prisma/client';
2023-06-09 18:21:18 +10:00
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;
currentPassword: string;
2024-01-30 17:31:27 +11:00
requestMetadata?: RequestMetadata;
2023-06-09 18:21:18 +10:00
};
export const updatePassword = async ({
userId,
password,
currentPassword,
2024-01-30 17:31:27 +11:00
requestMetadata,
}: 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) {
2024-12-06 16:01:24 +09:00
throw new AppError('NO_PASSWORD');
}
2023-06-09 18:21:18 +10:00
const isCurrentPasswordValid = await compare(currentPassword, user.password);
if (!isCurrentPasswordValid) {
2024-12-06 16:01:24 +09:00
throw new AppError('INCORRECT_PASSWORD');
}
// 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');
}
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
};