嗨所以我遇到了这个为Node js创建加密的随机令牌。
require('crypto').randomBytes(48, function(ex, buf) {
var token = buf.toString('hex');
});
我想弄清楚如何将它添加到我的路由文件中?我已经在我的猫鼬模式中将一个令牌字段设置为一个类型字符串。
exports.forgotPasswordPost = function(req, res, next) {
console.log("Forgot Password Post");
if(req.body.email === '') {
console.log('err');
} else {
crypto.randomBytes(48, function(ex, buf) {
var userToken = buf.toString('hex');
console.log(userToken);
User.findOne({email: (req.body.email)}, function(err, usr) {
if(err || !usr) {
console.log('err');
}
console.log(usr);
usr.token = new User({token: userToken});
usr.save(function(err, usr){
res.redirect('login', {title: 'Weblio', message: 'Your token was sent by email. Please enter it on the form below.'});
});
});
});
}
};
猫鼬文件:
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = mongoose.Schema.Types.ObjectId,
bcrypt = require('bcrypt-nodejs'),
SALT_WORK_FACTOR = 10;
var UserSchema = new Schema({
email: { type: String, required: true, lowercase:true, index: { unique: true } },
password: { type: String, required: true },
firstName: {type: String, required: true},
lastName: {type: String, required: true},
phone: {type: Number, required: true},
birthday: {type: Date, required: true},
friendRequest: {type: Object},
notifications: {type: Object},
friend: {type: Object},
date_created: {type: Date},
token: {type: String},
tokenCreated: {type: Date, default: Date.now}
}, {collection: "users"});
UserSchema.methods.hasExpired = function() {
var now = new Date();
return (now - createDate) > 2;
};
module.exports = mongoose.model('User', UserSchema);
这是查询结果:
"token" : "{ token: 'fa9e573e5ec8ed6d7bf53c9296f703b4ea6895c0a5438a0e0c4
b9a43f4db9bce7dd55e82c3188056efdc9ab53b9b5185',\n _id: 51fe1bcaa32f6b300c000001
}"
我刚刚用我的新用法更新了代码,并且也包括了我的猫鼬模式......