将bcryptjs与Mongo一起使用

Using bcryptjs with Mongo

本文关键字:一起 Mongo bcryptjs      更新时间:2023-09-26

我正在尝试使用Bcrpyt为我的Angular应用程序加密用户密码,该应用程序在后端使用Mongodb。

这是代码

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
bcrypt = require('bcryptjs'),
    SALT_WORK_FACTOR = 10;
var UserSchema = new mongoose.Schema({
  name: String,
  username: { type: String, required: true, index: { unique: true } },
  email: String,
  password:  { type: String, required: true },
  created_at: Date,
  topics: [{type: Schema.Types.ObjectId, ref: 'Topic'}],
  posts: [{type: Schema.Types.ObjectId, ref: 'Post'}],
  comments: [{type: Schema.Types.ObjectId, ref: 'Comment'}]
});

UserSchema.pre('save', function(next) {
    var user = this;
    // only hash the password if it has been modified (or is new)
    if (!user.isModified('password')) return next();
    // generate a salt
    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
        if (err) return next(err);
        // hash the password along with our new salt
        bcrypt.hash(user.password, salt, function(err, hash) {
            if (err) return next(err);
            // override the cleartext password with the hashed one
            user.password = hash;
            next();
        });
    });
});
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
    bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
        if (err) return cb(err);
        cb(null, isMatch);
    });
};
mongoose.model('User', UserSchema);

在控制器中创建和登录

var mongoose = require('mongoose');
var User = mongoose.model('User');
module.exports = (function() {
 return {
  login: function(req, res) {
     User.findOne({email: req.body.email}, function(err, user) {
       if(user === null) {
          var error = "User not found"
          console.log(error);
       }
       else{
        user.comparePassword(req.body.password, function(err, isMatch){
          if(err){
            console.log("Password dont match");
          } else{
              console.log(user)
              res.json(user);
            }
        })
       }
     })
  },
   create: function(req, res) {
  var user = new User({name: req.body.name, username:req.body.username, email:req.body.email, password:req.body.password, created_at: req.body.created_at});
  user.save(function(err) {
    if(err) {
      console.log('something went wrong');
    } else { 
      console.log('successfully added a user!');
      res.redirect('/');
    }
  })
  }
})();

用户创建功能工作正常,保存在加密的密码中。但是在登录期间,它没有正确地将加密的密码与输入进行比较。允许用户通过,而不考虑任何密码。

另外,如果找不到用户以及密码不匹配,我将如何显示错误(这是次要问题。

主要担心甚至错误的密码也被接受。

感谢您的帮助。

您正在检查密码匹配期间是否有任何错误,但不检查输入的密码是否与散列密码匹配。

user.comparePassword(req.body.password, function(err, isMatch){
    if(err){
        return console.log("Password dont match");
    } 
    if (isMatch) {
        // password matches. Log the user in
    }
});