【发布时间】: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 时,所有内容都已存储,但哈希和盐没有。我做错了吗?
【问题讨论】: