简体   繁体   中英

Using bcryptjs with Mongo

I am trying to encrypt user passwords using Bcrpyt for my Angular app which uses Mongodb in the backend.

Here is the code

Model

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);

Create & Login inside Controller

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('/');
    }
  })
  }
})();

The user create function is working fine, saving in the passwords encrypted. But during Login it is not properly comparing the encrypted password against the input. Lets user through regardless of any password.

Also how would I go about showing errors incase of user not found and also for password not matching(this is a secondary Q.

Primary concerned about even wrong password being accepted.

Thanks for the Help.

You are checking if there is any error during password matching but not checking if the input password matches the hashed one.

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

    if (isMatch) {
        // password matches. Log the user in
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM