每个人我都是NodeJ的初学者。我尝试实施本地护照实施。 passport.authenticate('register')没有调用 passport.use('register')中间件。就像sameway passport.authenticate('login')一样也无法正常工作。我已经附加了代码。任何人都可以修复该错误...谢谢。...
config/passport.js:
const LocalStrategy=require('passport-local').Strategy;
const User=require('../models/user');
console.log(`Outside passport`);
module.exports=(passport)=>{
console.log(`Inside passport`);
passport.serializeUser(function(user,done){
console.log(`SerializeUser:${user}`);
done(null,user.id);
});
passport.deserializeUser(function(id,done){
console.log(`Deserialize User:${id}`);
User.findById(id,function(err,user){
done(err,user);
});
});
console.log(`Above register...`);
passport.use('register',new LocalStrategy({
usernameField:'email',
passwordField:'password',
passReqToCallback:true
},function(req,email,password,done){
console.log(`Abovefind...`);
User.findOne({email:email},function(err,user){
if(err){
return done(err);
}
else if(user){
return done(null,false,req.flash('registerMessage',{message:'User already exist'}));
}
else{
var newuser=new user();
newuser.email=email,
newuser.password=newuser.generateHash(password);
console.log(newuser);
}
newuser.save(function(err){
if(err){
throw err;
}
return done(null,newuser);
});
});
}));
passport.use('login',new LocalStrategy({
usernameField:'email',
passwordField:'Password',
passReqToCallback:true
},function(req,email,password,done){
User.findOne({email:email},function(err,user){
if(err){
return done(err);
}
else if(!user){
return done(null,false,req.flash('loginMessage',{message:'Incorrect Username'}));
}
if (!user.validPassword(password)) {
return done(null,false,req.flash('loginMessage',{message:'Incorrect Password'}));
}
return done(null,user);
});
}));
}
models/user.js
const mongoose=require('mongoose');
const bcrypt=require('bcrypt');
const userSchema=new mongoose.Schema({
email:{
type:String,
unique:true
},
password:{
type:String
}
});
userSchema.methods.generateHash=(password)=>{
const p=bcrypt.hashSync(password,bcrypt.genSaltSync(10),null);
console.log(`Hash password: ${p}`);
return p;
}
userSchema.methods.validPassword=(hashpassword)=>{
console.log(`Given hash password: ${hashpassword}`);
const op=bcrypt.compareSync(hashpassword,this.password);
console.log(`Decode password: ${op}`);
return op;
}
module.exports=mongoose.model('people',userSchema);
<!-- begin snippet: js hide: false console: true babel: false -->
routes/routes/js:
app.post('/register',passport.authenticate('register',{
successRedirect:'/profile',
failureRedirect:'/register',
failureFlash:true
}));
app.post('/login',passport.authenticate('login',{
successRedirect:'/profile',
failureRedirect:'/login',
failureFlash:true
}));