【发布时间】:2018-10-31 15:17:51
【问题描述】:
在 MEAN 应用程序中,我定义我的用户模型并使用字段哈希和盐加密密码,如下所示:
var mongoose = require('mongoose');
var crypto = require('crypto');
var jwt = require('jsonwebtoken');
var UsersSchema = new mongoose.Schema({
personalId: {
type: String,
unique: "Personal Id already exists",
required: true
},
name: {
type: String,
required: true
},
surname:{
type: String,
required: true
},
username: {
type: String,
unique: "Username already exists",
required: "Please fill in a username",
lowercase: true
},
hash: String,
salt: String,
email:{
type: String,
unique: true,
lowercase: true,
trim: true
},
contract:{
type: String
},
role:{
type: String,
required: true
},
dateUpdated: {
type: Date
},
dateCreated: {
type: Date,
default: Date.now
}
});
UsersSchema.methods.setPassword = function (password) {
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha512').toString('hex');
};
UsersSchema.methods.validPassword = function (password) {
var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha512').toString('hex');
return this.hash === hash;
};
UsersSchema.methods.generateJwt = function () {
var expiry = new Date();
expiry.setDate(expiry.getDate() + 7);
return jwt.sign({
_id: this._id,
username: this.username,
exp: parseInt(expiry.getTime() / 1000),
}, "MY_SECRET"); // DO NOT KEEP YOUR SECRET IN THE CODE!
};
mongoose.model('Users', UsersSchema);
当我创建一个新用户时,返回对象用户完整(所有值), 当我得到用户列表时,也会返回每个用户的所有值。
我的问题是:当我询问用户对象时返回盐和哈希值是否正确?
【问题讨论】:
标签: javascript security encryption hash get