我正在我的应用程序中使用passport.js进行身份验证(本地)。我有两种类型的用户-用户和管理员。两者都插入了本地护照猫鼬。用户的身份验证工作正常。然后,我对 Admin 应用了相同的身份验证过程。
用户都不起作用,而在向 Admin 添加身份验证代码之前,该用户不能正常工作。 在注册 Admin 的过程中,它显示为未经授权。
我发现了一个与我的here类似的问题。我尝试了那里给出的解决方案,但情况变得更糟。我的整个应用程序崩溃了,并显示了一些strategy.authenticate is not a function
错误。
那么,为什么会显示此错误?如何在同一应用程序中同时验证,序列化和反序列化 Admin 和 User ?
这是我到目前为止所做的。
const passport = require("passport"),
localStrategy = require("passport-local").Strategy;
const User = require("./models/user"),
Admin = require("./models/admin");
passport.use(require("express-session") ({
secret : "Wubba lubba dub dub",
saveUninitialized : false,
resave : false
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
passport.use("user", new localStrategy(User.authenticate()));
passport.use("admin", new localStrategy(Admin.authenticate()));
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser(function(user, done) {
if(user!=null)
done(null,user);
});
app.use(function(req, res, next) {
res.locals.currentUser = req.user;
res.locals.error = req.flash("error");
res.locals.success = req.flash("success");
next();
});
router.get("/userLogin", (req, res) => {
res.render("user/userLogin");
});
router.post("/userLogin", passport.authenticate("user", {
successRedirect : "/user/1",
failureRedirect : "/userLogin",
}), (req, res)=> {
});
//user sign up handler
router.get("/signUp", (req, res) => {
res.render("user/userSignup");
});
router.post("/signUp", (req, res) => {
const newUser = new User({
firstName : req.body.firstName,
lastName : req.body.lastName,
username : req.body.username,
email : req.body.email,
gender : req.body.gender,
address : req.body.address,
});
User.register(newUser, req.body.password, (err, user) =>{
if(err) {
return res.render("user/userSignup");
}
passport.authenticate("local")(req, res, ()=> {
res.redirect("/user/1");
});
});
});
/admin login handler
router.get("/adminLogin", (req, res) => {
res.render("admin/adminLogin");
});
router.post("/adminLogin", passport.authenticate("admin", {
successRedirect : "/admin",
failureRedirect : "/adminLogin",
}), (req, res)=> {
});
//admin logout handler
router.get("/adminLogout", (req, res) => {
res.redirect("/");
});
// sign up
router.get("/adminSignup", (req, res) => {
res.render("signup");
});
router.post("/adminSignup", (req, res) => {
const newAdmin = new Admin({
username : req.body.username,
email : req.body.email,
});
Admin.register(newAdmin, req.body.password, (err, user) =>{
if(err) {
return res.render("signup");
}
passport.authenticate("local")(req, res, function() {
res.redirect("/admin");
});
});
});
middleware.isLoggedIn = function(req, res, next) {
if(req.isAuthenticated()) {
return next();
}
req.flash("error", "You need to be logged in first");
res.redirect("/");
};