so for the past hour I've been searching the way to authenticate multiple models in a login in passport.js with no avail. My app has 2 models, teacher and student, I wanted to make a login page to check it is teacher or student, then log them in, I tried to serialize and deserialize those two models in app.js, but it seems like it doesn't know which one to authenticate, is there any way I can do this?
Edit: I have a position field in both my student and teacher's collection, 1 for student and 2 for teacher. It seems that the passport.use() is overwritten by the second passport.use() call, as the result, I'm only able to login via Student, and if I flip them, I can login to Teacher.
app.use(passport.initialize());
app.use(passport.session());
passport.use(new localStrategyTeacher (Teacher.authenticate()));
passport.use(new localStrategyStudent (Student.authenticate()));
passport.serializeUser((user, done) => {
let type;
if (user.position === 1) {
type = 'student';
} else {
type = 'teacher';
}
done(null, {id: user.id, type});
});
passport.deserializeUser((key, done) => {
if(key.type === 'student'){
Student.findById(key.id, function(err, user) {
done(err, user);
});
} else {
Teacher.findById(key.id, function(err, user) {
done(err, user);
});
}
});
Sorry I don't have a score high enough to make a comment :). Without a larger snippet it is a bit hard to tell, but it seems like the following passport issue may provide the answer you are looking for
https://github.com/jaredhanson/passport/issues/50
And your passport.serializeUser and deserializeUser would need to be a bit more complicated, example. (not tested sorry)
passport.serializeUser(function(user, done) {
let type = user.isTeacher() ? 'teacher' : 'student';
done(null, { id: user.id, type: type});
});
passport.deserializeUser(function(data, done) {
if(data.type === 'student'){
Student.findById(data.id, function(err, user) {
done(err, user);
});
} else{
Teacher.findById(data.id, function(err, user) {
done(err, user);
});
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.