feat: implement authenticated user password change functionality, including a new DTO, service method, and API endpoint.
This commit is contained in:
@@ -22,6 +22,7 @@ import {
|
||||
ResetPasswordDto,
|
||||
RefreshTokenDto,
|
||||
VerifyEmailDto,
|
||||
ChangePasswordDto,
|
||||
} from './dto';
|
||||
import { UserRole, AuthProvider, UserStatus } from '@prisma/client';
|
||||
import { TwoFactorService } from './two-factor/two-factor.service';
|
||||
@@ -449,6 +450,62 @@ export class AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// CHANGE PASSWORD
|
||||
// ==========================================
|
||||
async changePassword(userId: string, dto: ChangePasswordDto) {
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
|
||||
if (!user.password) {
|
||||
throw new BadRequestException(
|
||||
'This account uses social login. Password cannot be changed.',
|
||||
);
|
||||
}
|
||||
|
||||
// Verify current password
|
||||
const isCurrentPasswordValid = await argon2.verify(
|
||||
user.password,
|
||||
dto.currentPassword,
|
||||
);
|
||||
|
||||
if (!isCurrentPasswordValid) {
|
||||
throw new BadRequestException('Current password is incorrect');
|
||||
}
|
||||
|
||||
// Check if new password is same as current
|
||||
const isSamePassword = await argon2.verify(user.password, dto.newPassword);
|
||||
if (isSamePassword) {
|
||||
throw new BadRequestException(
|
||||
'New password must be different from current password',
|
||||
);
|
||||
}
|
||||
|
||||
// Hash new password
|
||||
const hashedPassword = await argon2.hash(dto.newPassword);
|
||||
|
||||
// Update password
|
||||
await this.prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { password: hashedPassword },
|
||||
});
|
||||
|
||||
// Emit event
|
||||
this.eventEmitter.emit('password.changed', {
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
});
|
||||
|
||||
return {
|
||||
message: 'Password changed successfully',
|
||||
};
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// VERIFY EMAIL
|
||||
// ==========================================
|
||||
|
||||
Reference in New Issue
Block a user