From 308d07785f811ff470d0e90b11680926a823027b Mon Sep 17 00:00:00 2001 From: piotrruss Date: Sun, 29 May 2022 17:45:54 +0100 Subject: add change password option --- models/User.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'models/User.js') diff --git a/models/User.js b/models/User.js index bcf2523..4992b20 100644 --- a/models/User.js +++ b/models/User.js @@ -97,6 +97,29 @@ userSchema.statics.saveSettings = async function ({ _id, theme, language }) { return userResponse(user) } +userSchema.statics.savePassword = async function ({ _id, currentPassword, newPassword }) { + const user = await User.findOne({ _id }) + + if (!user) { + throw new Error('Unable to change password') + } + + const isMatch = await bcrypt.compare(currentPassword, user.password) + + if (!isMatch) { + throw new Error('Wrong password') + } + + const password = await bcrypt.hash(newPassword, 8) + const newUser = await User.findOneAndUpdate({ _id }, { password }, { new: true }) + + if (!newUser) { + throw new Error('Could not update password') + } + + return userResponse(newUser) +} + userSchema.statics.state = async function (_id) { const user = await User.findOne({ _id }) -- cgit v1.2.3