我将使用JWT身份验证创建用户注册,同时使用bcrypt-node模块进行密码哈希和加盐。
userModel.js
var mongoose =require('mongoose');
var Schema =mongoose.Schema;
var bcrypt =require('bcrypt-node');
var UserSchema=new Schema({
name:{type:String, unique:true, required:true},
password:{type:String, required:true}
});
UserSchema.pre('save', function (next) {
var user = this;
if (this.isModified('password') || this.isNew) {
bcrypt.genSalt(10, function (err, salt) {
if (err) {
return next(err);
}
bcrypt.hash(user.password, salt, function (err, hash) {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
} else {
return next();
}
});
UserSchema.methods.comparePassword = function (passw, cb) {
bcrypt.compare(passw, this.password, function (err, isMatch) {
if (err) {
return cb(err);
}
cb(null, isMatch);
});
};
module.exports = mongoose.model('User', UserSchema);
passport.js
var JwtStrategy =require('passport-jwt').Strategy;
var User =require('../app/models/user');
var config =require('../config/database');
module.exports=function(passport){
var opts = {};
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findOne({id: jwt_payload.id}, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
}
});
}));
};
app.js
apiRoutes.post('/signup', function(req, res) {
if (!req.body.name || !req.body.password) {
res.json({success: false, msg: 'Please pass name and password.'});
} else {
var newUser = new User({
name: req.body.name,
password: req.body.password
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
当我运行这段代码时,它显示错误 -
throw "No callback function was given".
No Callback function was given
请帮我修复这段代码。 谢谢。