我们正在开发一个电子商务网站,其中管理员和用户表在那里,我们正在对管理员和用户进行身份验证,如果他是管理员,那么他就可以访问管理网站,他可以利用管理员的好处,如果不是,他不能登录管理站点
我们的路由代码是
function ensureAdmin(req, res, next){
console.log("reached :");
if(req.isAuthenticated()){
if (req.admin.role == 'admin')
{
return next();
}
else {
req.logout();
res.redirect('/admin');
}
}
else {
res.redirect('/admin');
}
}
router.post('/admin/login', passport.authenticate('admin', {successRedirect:'/admin/dashboard',failureRedirect:'/admin',failureFlash: true}), function(req, res) {
res.redirect('/admin/dashboard');
});
在上面的代码中,身份验证 if(req.isAuthenticated)(){
条件是它本身不起作用,管理员和用户集合是不同的表
现在我能做什么
最佳答案
您可以通过使用 2 个不同的 LocalStrategies 来对用户和管理员进行不同的身份验证(在您的情况下来自不同的表)。
类似于:
passport.use('user', new LocalStrategy( //'user' strategy
function(username, password, done) {
User.findOne(/* ... */)
}
));
passport.use('admin', new LocalStrategy( //'admin' strategy
function(username, password, done) {
Admin.findOne(/* ... */)
}
));
//user login, uses the 'user' strategy
app.post('/user/login',
passport.authenticate('user', { successRedirect: '/user/home', failureRedirect: '/user/login' }));
//Admin login, uses the admin strategy
app.post('/admin/login',
passport.authenticate('admin', { successRedirect: '/admin/dashboard', failureRedirect: '/admin/login' }));
关于node.js - 多种护照本地策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40925682/