Refactor changePassword resolver with neode

This commit is contained in:
Robert Schäfer 2019-07-16 20:06:26 +02:00
parent 46cd21db1f
commit 4c9dbdb378

View File

@ -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())
},
},
}