2017-06-14 59 views
0

如果密碼輸入爲空,我正在努力防止更新數據庫中用戶的密碼。如果輸入保持空白,防止更新用戶的密碼?

這裏是負責更新用戶數據的路由:

module.exports.updateUser = function (user, callback) { 

    if (user.password) { 
     bcrypt.genSalt(10, (err, salt) => { 
      bcrypt.hash(user.password, salt, (err, hash) => { 
       if (err) throw err; 

       user.password = hash; 
      }); 
     }); 
    } 

    user.save(callback); 
}; 

router.put('/update', passport.authenticate('jwt', {session: false}), (req, res) => { 
    let user = req.user; 

    user.firstname = req.body.firstname; 
    user.lastname = req.body.lastname; 
    user.username = req.body.username; 
    user.email = req.body.email; 
    user.password = req.body.password || null; 

    User.updateUser(user, (err) => { 
     if (err) { 
      res.json({ 
       success: false, 
       message: 'User details couldn\'t be updated.' 
      }); 
     } else { 
      res.json({ 
       success: true, 
       message: 'User updated' 
      }); 
     } 
    }); 
}); 

這裏是產生密碼的哈希,並在數據庫中保存新數據的用戶模型方法

我檢查是否給出了密碼值,但如果沒有爲密碼給出新值,我不知道如何將舊的加密密碼保留在數據庫中。如果用戶沒有填寫密碼輸入,它將被保存爲空,正如預期的那樣...

我希望有一種方法來實現這一點,我只是無法弄清楚,是初學者。

預先感謝您!

+1

如果您是初學者,請閱讀手冊[更新文檔](https://docs.mongodb.com/manual/tutorial/update-documents/)。這可能會讓你瞭解爲什麼你不應該在這裏使用'.save()'這樣的方法。 –

回答

0

我想你正在使用Mongoose與數據庫進行通信。 改變這一行代碼的:

user.password = req.body.password || null; 

與此:

if(req.body.password != null) { 
user.password = req.body.password 
}else{ 
/* find each user with a last name matching 'user.userame', selecting 
/*the `password` field and returning the result in 'usr' 
*/ 
    User.find({'username' : user.username}, 'password', function (err, usr) { 
    if (err) return handleError(err); 
    user.password = usr.password; 
    }) 
} 
+0

我想過這樣做,但這更像是一種解決方法。我想保留模型內的數據庫方法,並在需要時從外部調用它們。 – Eseth

0

基於@Neil倫恩的有關檢查文檔的建議,我想出了一個解決方案。我改變了updateUser方法是:

module.exports.updateUser = function (user, callback) { 
    if (user.password) { 
     bcrypt.genSalt(10, (err, salt) => { 
      bcrypt.hash(user.password, salt, (err, hash) => { 
       if (err) throw err; 

       user.password = hash; 
       user.save(callback); 
      }); 
     }); 
    } else { 
     User.findById(user.id).update({ 
      username: user.username, 
      email: user.email, 
      firstname: user.firstname, 
      lastname: user.lastname 
     }, callback); 
    } 
}; 

如果密碼存在,則更新的一切,是,如果沒有密碼設置,然後更新只除密碼所需字段。

也許這不是最好的解決方案,但它現在可行。

謝謝!