首页 > 解决方案 > 如何在快速应用程序中使用 mongoose for mongoDB 验证密码以登录用户?

问题描述

我正在尝试让用户通过他们的电子邮件和密码登录。MongoDb 文档显示在用户模型中使用 bcrypt 散列密码。它还提供了一种很好的方法来验证模型中的密码。我的问题是如何使用“控制器”中的验证?我很清楚“如果(req.body.password === user.password)”将不起作用,因为一个是散列的,另一个不是。

我一直在寻找答案几个小时,似乎无法找到关于我如何在我的帖子请求中使用“UserSchema.methods.comparePassword”方法登录的联系。这不完全是真正的登录,只是尝试获取密码以验证并在登录后发回密钥。以下是文档:https ://www.mongodb.com/blog/post/password-authentication-with-mongoose-part-1

// 这是我的用户模型

let mongoose = require('mongoose'),
  Schema = mongoose.Schema,
  bcrypt = require('bcrypt'),
  SALT_WORK_FACTOR = 10
var hat = require('hat');

let UserSchema = new Schema({
  email: {
    type: String,
    required: true,
    index: {
      unique: true
    }
  },
  password: {
    type: String,
    require: true
  },
  api_key: {
    type: String
  }
});

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 using 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;
        user.api_key = hat();
        next();
    });
});


});

UserSchema.methods.comparePassword = function(candidatePassword, cb) {
    bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
        if (err) return cb(err);
        cb(null, isMatch);
    });
};

module.exports = mongoose.model('user', UserSchema);

// 这是 session.js

let UserModel = require('../../../models/user.model');
var express = require('express');
var router = express.Router();

router.post('/', (req, res, next) => {
  UserModel.findOne(
   {
     $or: [
            { email : req.body.email }
          ]
   }
)
  .then(user => {
    if (req.body.password === user.password) {
      res.setHeader("Content-Type", "application/json");
      res.status(200).send(JSON.stringify({
        "api_key": `${user.api_key}`
        }));
    } else {
      res.status(404).send("Incorrect email or password")
    }
  })
  .catch(error => {
    res.setHeader("Content-Type", "application/json");
    res.status(500).send({error})
  })
})

module.exports = router

如果我只是通过电子邮件找到用户,一切正常。只需要弄清楚如何在用户模型中使用比较密码方法。谢谢!

标签: mongodbexpressmongoosebcrypt

解决方案


也许在你的模型中有这样的东西:

User = require('./user-model');

.......

User.findOne({ username: 'jmar777' }, function(err, user) {
    if (err) throw err;
    user.comparePassword('Password123', function(err, isMatch) {
        if (err) throw err;
        console.log('Password123:', isMatch); // -> Password123: true
    });
........

其他资源:

http://devsmash.com/blog/password-authentication-with-mongoose-and-bcrypt

https://www.abeautifulsite.net/hashing-passwords-with-nodejs-and-bcrypt

https://medium.com/@mridu.sh92/a-quick-guide-for-authentication-using-bcrypt-on-express-nodejs-1d8791bb418f

希望能帮助到你!


推荐阅读