我目前在护照上使用两种Google策略来对“学生”用户和“教师”用户进行身份验证。
注意:这两个用户具有单独的猫鼬模型,因此数据库中的单独集合。
我遇到的问题是,当将教师用户凭据保存到数据库时,它将保存到学生集合中,而不是mongodb中的教师集合中。
关于此问题的怪异之处在于,如果我注释掉或删除“学生”策略而仅使“教师”策略可用,它将保存到正确的集合(教师集合)中。仅当两种策略均可用时,它们才默认为学生集合。我可以得出结论,在任一路由上触发身份验证时,它都会自动引用最高级的策略。我需要有关如何解决此问题的建议。
Passport.js
passport.use(
"student",
new GoogleStrategy(
{
//options for the google strategy
},
(accessToken, refreshToken, profile, done) => {
/Check if user already exist in Db
Student.findOne({ googleId: profile.id }).then(currentUser => {
if (currentUser) {
//already have user
done(null, currentUser);
console.log(`${currentUser} is signed in`);
} else {
//create new user
new Student({
username: profile.username,
name: profile.displayName,
googleId: profile.id
})
.save()
.then(newUser => {
done(null, newUser);
console.log(`${newUser} was just created`);
});
}
});
}
)
);
passport.use(
"teacher",
new GoogleStrategy(
{
//options for the google strategy
},
(accessToken, refreshToken, profile, done) => {
//Check if user already exist in Db
Teacher.findOne({ googleId: profile.id }).then(currentTeacher => {
if (currentTeacher) {
//already have user
done(null, currentTeacher);
console.log(`${currentTeacher} is signed in`);
} else {
//create new user
new Teacher({
username: profile.username,
name: profile.displayName,
googleId: profile.id
})
.save()
.then(newTeacher => {
done(null, newTeacher);
console.log(`${newTeacher} was just created`);
});
}
});
}
)
);
authTeacher.js
//auth with teacher strategy
router.get(
"/teachergoogle",
passport.authenticate("teacher", {
scope: ["profile"]
})
);
//callback route for google after authorization
router.get(
"/google/redirect",
passport.authenticate("teacher"),
isTeacher,
(req, res) => {
res.send("this is teacher");
}
);
//Logout
router.get("/logout", (req, res) => {
req.logout();
res.redirect("http://localhost:8080/");
});
module.exports = router;
* authStudent.js
router.get(
"/studentgoogle",
passport.authenticate("student", {
scope: ["profile"]
})
);
router.get(
"/google/redirect",
passport.authenticate("teacher"),
isStudent,
(req, res) => {
res.send("this is teacher");
}
);
router.get("/logout", (req, res) => {
req.logout();
res.redirect("http://localhost:8080/");
});
module.exports = router;