From f4bf39ef1c3c40c9d026d79ff794107058bcc4c4 Mon Sep 17 00:00:00 2001 From: Jesse Chan Date: Thu, 10 Dec 2020 18:39:56 +0800 Subject: [PATCH] server: Users: hash password when update user password --- server/models/Users.ts | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/server/models/Users.ts b/server/models/Users.ts index 92796765..0cb04f2b 100644 --- a/server/models/Users.ts +++ b/server/models/Users.ts @@ -11,6 +11,18 @@ import services from '../services'; import type {ClientConnectionSettings} from '../../shared/schema/ClientConnectionSettings'; import type {Credentials, UserInDatabase} from '../../shared/schema/Auth'; +const hashPassword = async (password: string): Promise => { + return argon2id({ + password: password, + salt: crypto.randomBytes(16), + parallelism: 1, + iterations: 256, + memorySize: 512, + hashLength: 32, + outputType: 'encoded', + }); +}; + class Users { private db = (() => { const db = Datastore.create({ @@ -83,17 +95,7 @@ class Users { * @return {Promise} - Returns the created user or rejects with error. */ async createUser(credentials: Credentials, shouldHash = true): Promise { - const hashed = shouldHash - ? await argon2id({ - password: credentials.password, - salt: crypto.randomBytes(16), - parallelism: 1, - iterations: 256, - memorySize: 512, - hashLength: 32, - outputType: 'encoded', - }).catch(() => undefined) - : credentials.password; + const hashed = shouldHash ? await hashPassword(credentials.password).catch(() => undefined) : credentials.password; if (this.db == null || hashed == null) { throw new Error(); @@ -137,7 +139,13 @@ class Users { * @return {Promise} - Returns new username of updated user or rejects with error. */ async updateUser(username: string, userRecordPatch: Partial): Promise { - return this.db.update({username}, {$set: userRecordPatch}, {}).then((numUsersUpdated) => { + const patch = userRecordPatch; + + if (patch.password != null) { + patch.password = await hashPassword(patch.password); + } + + return this.db.update({username}, {$set: patch}, {}).then((numUsersUpdated) => { if (numUsersUpdated === 0) { throw new Error(); }