diff --git a/src/user/user.controller.ts b/src/user/user.controller.ts index 5b13547..91808f2 100644 --- a/src/user/user.controller.ts +++ b/src/user/user.controller.ts @@ -313,7 +313,7 @@ export class UserController { }); } - if (dto.oldPassword && !this.userService.checkPassword(user.password, dto.oldPassword)) { + if (!this.userService.checkPassword(user.password, dto.oldPassword)) { throw new BadRequestException({ code: ErrorCodes.WRONG_OLD_PASSWORD, message: 'Old password not match.', diff --git a/src/user/user.service.ts b/src/user/user.service.ts index c14b96c..dfad579 100644 --- a/src/user/user.service.ts +++ b/src/user/user.service.ts @@ -159,6 +159,9 @@ export class UserService { } checkPassword(hash: string, password: string): boolean { + if (!hash) { + return !password; + } return validateHash(hash, password); } diff --git a/test/user.e2e-spec.ts b/test/user.e2e-spec.ts index 1b08f30..3b25eb9 100644 --- a/test/user.e2e-spec.ts +++ b/test/user.e2e-spec.ts @@ -202,6 +202,37 @@ describe('User crud (e2e)', () => { .expect(400); }); + it('Update password for user without password', async () => { + const userDoc = mockUser(); + await namespaceService.upsertByKey(userDoc.ns, { + name: faker.company.name(), + }); + + const user = await userService.create({ ...userDoc, password: undefined }); + + // should set password successfully when no old password exists + await request(app.getHttpServer()) + .post(`/users/${user.id}/@updatePassword`) + .send({ newPassword: '^tR123456' }) + .set('Content-Type', 'application/json') + .set('x-api-key', auth.apiKey) + .set('Accept', 'application/json') + .expect(204); + + // should fail old password verification when user has no password + const noPasswordUser = await userService.create({ + ...mockUser(), + password: undefined, + }); + await request(app.getHttpServer()) + .post(`/users/${noPasswordUser.id}/@updatePassword`) + .send({ oldPassword: 'anything1@Aa', newPassword: '^tR123456' }) + .set('Content-Type', 'application/json') + .set('x-api-key', auth.apiKey) + .set('Accept', 'application/json') + .expect(400); + }); + it('Upsert user by id', async () => { const userId = `import-${nanoid(10)}`; const userDoc = mockUser();