From 4c9dbdb3781635ea6a97d69f6ca060bbb41927cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Sch=C3=A4fer?= Date: Tue, 16 Jul 2019 20:06:26 +0200 Subject: [PATCH] Refactor changePassword resolver with neode --- .../src/schema/resolvers/user_management.js | 36 ++++++++----------- 1 file changed, 15 insertions(+), 21 deletions(-) diff --git a/backend/src/schema/resolvers/user_management.js b/backend/src/schema/resolvers/user_management.js index ab7438a17..d382c2aa7 100644 --- a/backend/src/schema/resolvers/user_management.js +++ b/backend/src/schema/resolvers/user_management.js @@ -2,6 +2,9 @@ import encode from '../../jwt/encode' import bcrypt from 'bcryptjs' import { AuthenticationError } from 'apollo-server' import { neo4jgraphql } from 'neo4j-graphql-js' +import { neode } from '../../bootstrap/neo4j' + +const instance = neode() export default { Query: { @@ -46,33 +49,24 @@ export default { } }, changePassword: async (_, { oldPassword, newPassword }, { driver, user }) => { - const session = driver.session() - let result = await session.run('MATCH (user:User {id:$id}) RETURN user', { id: user.id }) + let currentUser = await instance.find('User', user.id) - const [currentUser] = result.records.map(record => record.get('user').properties) - - if (!(await bcrypt.compareSync(oldPassword, currentUser.encryptedPassword))) { + const encryptedPassword = currentUser.get('encryptedPassword') + if (!(await bcrypt.compareSync(oldPassword, encryptedPassword))) { throw new AuthenticationError('Old password is not correct') } - if (await bcrypt.compareSync(newPassword, currentUser.encryptedPassword)) { + if (await bcrypt.compareSync(newPassword, encryptedPassword)) { throw new AuthenticationError('Old password and new password should be different') - } else { - const newEncryptedPassword = await bcrypt.hashSync(newPassword, 10) - session.run( - `MATCH (user:User)-[:PRIMARY_EMAIL]->(e:EmailAddress {email: $userEmail}) - SET user.encryptedPassword = $newEncryptedPassword - RETURN user - `, - { - userEmail: user.email, - newEncryptedPassword, - }, - ) - session.close() - - return encode(currentUser) } + + const newEncryptedPassword = await bcrypt.hashSync(newPassword, 10) + await currentUser.update({ + encryptedPassword: newEncryptedPassword, + updatedAt: new Date().toISOString() + }) + + return encode(await currentUser.toJson()) }, }, }