Reputation: 29
we are developing an e-commerce website in that admin and user table are there here we are authenticating the admin and user if he is admin only then he can access the admin site an he can utilise the admin benefits if not he cannot login to the admin site
for that our routing code is
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');
});
In the above code the authentication if(req.isAuthenticated)(){
that condition it self not working the admin and user collections are different tables
now what can i do
Upvotes: 1
Views: 759
Reputation: 12389
You can do it by having 2 different LocalStrategies to authenticate user and admin differently (in your case from different tables).
Something like :
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' }));
Upvotes: 6