【问题标题】:Problems saving authentication credentials with Mongoose使用 Mongoose 保存身份验证凭据时出现问题
【发布时间】:2017-12-18 20:19:45
【问题描述】:

我正在使用 Express 和 Mongo 制作一个简单的 Node.js API,我将在不久的将来使用 React 制作一个前端,但现在我只是添加模型并且我遇到了问题(使用'users' 模型)没有存储密码。

这是我的代码:

const mongoose = require('mongoose');
const crypto = require('crypto');

const UserSchema = new mongoose.Schema({
    name: {type: String, required: true},
    username: {type: String, required: true},
    email: {type: String, required: true, lowercase: true, index: true},
    hash: String,
    salt: String
});

UserSchema.methods.setPassword = (password) => {
    this.salt = crypto.randomBytes(16).toString('hex');
    this.hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha').toString('hex');
};

UserSchema.methods.validPassword = (password) => {
    let hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha').toString('hex');
    return this.hash === hash;
}

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

我在我的架构中定义了两个实例方法,我只能使用该架构的一个实例来访问这些实例方法,而我正在这里尝试这样做:

const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const UserSchema = require('./User');
router.use(bodyParser.urlencoded({extended: true}));

router.post('/users', (req, res) => {
    let body = req.body;
    const User = new UserSchema();

    User.name = body.name;
    User.username = body.username;
    User.email = body.email;
    User.setPassword(body.password);

    User.save((err, user) => {
        if (err) return res.status(500).send('There were problems while creating the user.');
        res.status(200).send(user);
    })
});

我正在创建架构的新实例,并使用该实例访问实例方法,问题是字段 'hash' 和 'salt' 受实例方法影响,完全不受影响。

我在控制台中打印哈希和盐,它们正在生成但没有保存,事实上,当我检查 Mongo 时,所有内容都已存储,但哈希和盐没有。我做错了吗?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    问题在于您的setPasswordvalidPassword 方法是箭头函数。 箭头函数将this 绑定到周围作用域的上下文。在您的情况下,它将是全局范围。

    将您的方法更改为常规函数,它将起作用:

    UserSchema.methods.setPassword = function(password) {
        this.salt = crypto.randomBytes(16).toString('hex');
        this.hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha').toString('hex');
    };
    
    UserSchema.methods.validPassword = (password) {
        let hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha').toString('hex');
        return this.hash === hash;
    }
    

    【讨论】:

    • 让我检查一下,我会告诉你!
    • 对不起,我最近很忙。是的!它工作得很好。谢谢你。 @victorkohl。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    相关资源
    最近更新 更多