我正在用 Express 和 Mongo 制作一个简单的 Node.js API,我会在晚些时候用 React 制作一个前端,但现在我只是添加模型,我遇到了问题(用'用户'模型)密码没有被存储。
这是我的代码:
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”似乎strong>' 受实例方法影响,完全不受影响。
我在控制台中打印哈希和盐,它们正在生成但没有保存,事实上,当我检查 Mongo 时,所有内容都被存储但哈希和盐没有。我做错了什么吗?
最佳答案
问题是您的setPassword
和validPassword
方法是箭头函数。
箭头函数将 this
绑定(bind)到周围范围的上下文。在您的情况下,它将是全局范围。
将您的方法更改为常规函数,它将起作用:
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;
}
关于node.js - 使用 Mongoose 保存身份验证凭据时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45090976/