Passport LocalStrategy 不适用于两个登录系统

Passport LocalStrategy Not working on Two login system

所以在我的项目中我使用了两个登录系统。一个用于管理员,即 Seperate,另一个用于用户。 已经在 Passport 的帮助下实现了管理员登录系统。 现在,当我当时在用户登录系统中使用相同的概念时,它不起作用。我的意思是它会影响我的管理员登录。 我的代码是

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.getUserByUsername(username, function(err, user){
        if(err) throw err;
        if(!user){
            return done(null, false, {message: 'Unknown User'});
        }
        User.comparePassword(password, user.password, function(err, isMatch){
            if(err) throw err;
            if(isMatch){
                return done(null, user);
            }else{
                return done(null, false, {message: 'Invalid Credential, please check carefully...!'})
            }
        });
    });
  }
));

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    User.getUserById(id, function(err, user) {
        done(err, user);
    });
});

router.post('/login',
  passport.authenticate('local', {
    failureRedirect: '/user/login',
    badRequestMessage: 'Field cannot be blank.!!', //missing credentials
    failureFlash: true
  }),
  function(req, res) {
    req.flash('success_msg', 'Welcome ' + req.user.name);
    res.redirect('/user/dashboard');
  });

我认为 LocalStrategy 会产生错误,所以我也使用了 basicStrategy,但我的管理员登录与之前一样完美,但我的用户登录不起作用。每次都说基础境界="Users"。 任何帮助将不胜感激

实际上它不在本地或基本策略上。它完全取决于 passport.serializeUser 和 deserializeUser。 我们必须发送用户数据,而不是 serializeUser 上的用户 ID。而在 deserializeUser 上,我们必须选择一些唯一性,然后根据条件查询 运行。实际上,deserializeUser 函数一次只能处理一个 DB。

尝试这样做。它创建两个模式,一个用于管理员,一个用于用户。因此,通过命名它们来创建两个本地策略,然后我们可以根据用户的凭据对用户进行序列化和反序列化。希望这会有所帮助:)

app.get("/register", function(req, res){
    res.render("reg")
})

app.post("/register", function(req, res){
    var type = req.body.type
    if(type=="student"){
    var newUser = new Student({
        username: req.body.username,
        gender: req.body.gender,
        rollnumber: req.body.rollnumber,
        dob: req.body.dob,
        email: req.body.email,
        type: req.body.type,
        password: req.body.password
    })

    req.checkBody('username','UserName is Required').notEmpty();
    req.checkBody('rollnumber','Roll Number is Required').notEmpty();
    req.checkBody('email','Email Required').notEmpty();
    req.checkBody('email','Email Invalid').isEmail();
    req.checkBody('password','Password is Required').notEmpty();
    req.checkBody('password1','Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();
    if(errors){
        res.render('Sregister', {errors: errors});
    }else{
    bcrypt.genSalt(10, function(err,  salt){
        bcrypt.hash(newUser.password, salt, function(err, hash){
            if(!err){
                newUser.password = hash;
            }
            newUser.save(function(err){
                if(!err){
                    console.log("success in reg");
                    res.redirect("/student/login")
                }
            })
        })
    })
    }}
    else if(type=="teacher"){
        var newUser = new Teacher({
        username: req.body.username,
        gender: req.body.gender,
        rollnumber: req.body.rollnumber,
        dob: req.body.dob,
        email: req.body.email,
        type: req.body.type,
        password: req.body.password
    })

    req.checkBody('username','UserName is Required').notEmpty();
    req.checkBody('rollnumber','Roll Number is Required').notEmpty();
    req.checkBody('email','Email Required').notEmpty();
    req.checkBody('email','Email Invalid').isEmail();
    req.checkBody('password','Password is Required').notEmpty();
    req.checkBody('password1','Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();
    if(errors){
        res.render('Sregister', {errors: errors});
    }else{

             bcrypt.genSalt(10, function(err,  salt){
                 bcrypt.hash(newUser.password, salt, function(err, hash){
                    if(!err){
                         newUser.password = hash;
                  }
                        newUser.save(function(err){
                     if(!err){
                         console.log("success in reg");
                         res.redirect("/teacher/login")
                }
            })
        })
    })
    }}
})

//strategies

passport.use('student', new LocalStrategy(function(username, password, done){
    var query = {username: username};
    Student.findOne(query, function(err, student){
        if(err) throw err;
        if(!student){
            return done(null, false);
        }
        bcrypt.compare(password,student.password, function(err, isMatch){
            if(err) throw err;
            if(isMatch)
                return done(null, student);
            else
                return done(null,false);
        })
    })
}))

passport.use('teacher', new LocalStrategy(function(username, password, done){
    var query = {username: username};
    Teacher.findOne(query, function(err, teacher){
        if(err) throw err;
        if(!teacher){
            console.log("no teach")
            return done(null, false);
        }
        bcrypt.compare(password,teacher.password, function(err, isMatch){
            if(err) throw err;
            if(isMatch)
                return done(null, teacher);
            else
                return done(null,false);
        })
    })
}))

//serialize deserizlize

passport.serializeUser(function (entity, done) {
    done(null, { id: entity.id, type: entity.type });
});

passport.deserializeUser(function (obj, done) {
    switch (obj.type) {
        case 'student':
            Student.findById(obj.id)
                .then(user => {
                    if (user) {
                        done(null, user);
                    }
                    else {
                        done(new Error('user id not found:' + obj.id, null));
                    }
                });
            break;
        case 'teacher':
            Teacher.findById(obj.id)
                .then(device => {
                    if (device) {
                        done(null, device);
                    } else {
                        done(new Error('device id not found:' + obj.id, null));
                    }
                });
            break;
        default:
            done(new Error('no entity type:', obj.type), null);
            break;
    }
});
//login routes

app.get("/student/login", function(req, res){
    res.render("slogin")
})

app.get("/teacher/login", function(req, res){
    res.render("tlogin")
})

app.post('/student/login', 
  passport.authenticate('student', { successRedirect: '/student/home', failureRedirect: '/student/login' }));

app.post('/teacher/login', 
  passport.authenticate('teacher', { successRedirect: '/teacher/home', failureRedirect: '/teacher/login' }));


app.get("/", function(req, res){
  res.render("home");  
})

app.get("/student/home", function(req, res){
  res.send("hi student")
})

app.get("/teacher/home", function(req, res){
  res.send("hi teacher")  
})