Skip to content

Commit

Permalink
Merge pull request #482 from curveball/password-errors
Browse files Browse the repository at this point in the history
Emit better errors for the 'password' endpoint
  • Loading branch information
evert authored Nov 22, 2023
2 parents e91f0da + e6bc0d9 commit d929ab4
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 7 deletions.
1 change: 1 addition & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Changelog
* Added new privilege for changing passwords: `a12n:user:change-password`.
* Introspection endpoint now returns the `exp`, `sub`, `aud` and `iss`
properties.
* Now returning a 422 for invalid passwords instead of 500.


0.24.0 (2023-11-09)
Expand Down
3 changes: 0 additions & 3 deletions src/user/controller/password.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,6 @@ class UserPasswordController extends Controller {
if (!userBody.newPassword || typeof userBody.newPassword !== 'string') {
throw new UnprocessableEntity('The "newPassword" property is required.');
}
if (userBody.newPassword.length < 8) {
throw new UnprocessableEntity('Passwords must be at least 8 characters.');
}

const password = userBody.newPassword;

Expand Down
21 changes: 17 additions & 4 deletions src/user/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ import * as bcrypt from 'bcrypt';
import * as otplib from 'otplib';
import db from '../database';
import { User } from '../types';
import { UnprocessableEntity } from '@curveball/http-errors';

export async function createPassword(user: User, password: string): Promise<void> {

assertValidPassword(password);
await db('user_passwords').insert({
user_id: user.id,
password: await bcrypt.hash(password, 12)
Expand All @@ -14,10 +16,13 @@ export async function createPassword(user: User, password: string): Promise<void

export async function updatePassword(user: User, password: string): Promise<void> {

const query = 'INSERT INTO user_passwords (password, user_id) VALUES (?, ?) ON DUPLICATE KEY UPDATE password = ?';
const hashedPw = await bcrypt.hash(password, 12);

await db.raw(query, [hashedPw, user.id, hashedPw]);
assertValidPassword(password);
await db('user_passwords').insert({
user_id: user.id,
password: await bcrypt.hash(password, 12)
})
.onConflict('user_id')
.merge();

}

Expand Down Expand Up @@ -92,3 +97,11 @@ export async function hasTotp(user: User): Promise<boolean> {
return result.length !== 0;

}

function assertValidPassword(password: string) {

if (password.length < 8) {
throw new UnprocessableEntity('Passwords must be at least 8 characters');
}

}

0 comments on commit d929ab4

Please sign in to comment.