我有两个可以登录的模型(没有一个是用户)一个是申请人,另一个是雇主。 passportEmployer配置文件与passportApplicant配置文件类似。
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var Employer = require('../controllers/EmployerController');
//passport middleware
passport.serializeUser(function(employer, done) {
done(null, employer._id);
});
passport.deserializeUser(function(id, done) {
Employer.findById(id, function (err, employer) {
done(err, employer);
});
});
//passport local strategy
passport.use( 'employer', new LocalStrategy({usernameField: 'email',
passwordField: 'password',
session: false
},
function(username, password, done){
Employer.find({email:username}, function(err, employers){
if(err) {
return done(err, null, null);
}
var employer = employers[0];
if(!employer){
return done(null, false, { 'confirmation':'fail', message: 'Unknown Employer'});
}
Employer.comparePassword(password, employer.password, function(err, isMatch){
if(err) {
return done(err, null, null);
}
else if(isMatch){
return done(null, Employer, {'confirmation':'success', 'result':employer});
}else{
return done(null, false, {'confirmation':'fail', message: 'Invalid Password'});
}
});
});
}
));
module.exports = passport;
以及以下登录路线:
router.post('/employer/login', function(req, res, next){
employerPassport.authenticate('employer', function(err, employer, info){
if(err) {
res.status(400).json({'confirmation':'fail', 'message':err})
}
else if(!employer){
res.status(400).json(info)
}
else{
req.login(employer, function(err){
if(err){
res.status(400).json({'confirmation':'fail', 'message':'error'+err})
}else{
console.log('Authentication Successful');
res.json(info)
}
});
}
})(req, res, next);
});
但是这会出现以下错误: " message":" errorError:无法将用户序列化为会话"
请帮忙。
答案 0 :(得分:1)
将您的本地策略与以下策略进行比较。您的代码中存在拼写错误。此外,使用Employer.findOne()
代替Employer.find()
查询单个雇主
//passport local strategy
passport.use( 'employer', new LocalStrategy({usernameField: 'email',
passwordField: 'password',
session: false
},
function(username, password, done){
Employer.findOne({email:username}, function(err, employer){
if(err) {
return done(err, null, null);
}
if(!employer){
return done(null, false, { 'confirmation':'fail', message: 'Unknown Employer'});
}
Employer.comparePassword(password, employer.password, function(err, isMatch){
if(err) {
return done(err, null, null);
}
else if(isMatch){
return done(null, employer, {'confirmation':'success', 'result':employer});
}else{
return done(null, false, {'confirmation':'fail', message: 'Invalid Password'});
}
});
});
}
));