Roco CTZ
Roco CTZ

Reputation: 1117

How can you define multiple isAuthenticated functions in Passport.js?

I am building an app using Express/Node.js with Passport.js(passport-local) & Mongoose.

There are two kind of users:

  1. regular users (they login using /user-login page and passport strategy 'local-user-login'; regular users are stored in "Users" MongoDB collection)
  2. admins (they login using /admin-login page and passport strategy 'local-admin-login'; admins are stored in "Admins" MongoDB collection)

I also have 2 pages: /user_home (needs to be accessible to logged regular users only) and /admin_home (for logged admins only)

Route for /user_home:

app.get('/user_home', isLoggedIn, function(req, res) {
    // render the page
});

function isLoggedIn(req, res, next) {
    if (req.isAuthenticated())
        return next();
    res.redirect('/login');
}

If I log in as an admin and try to access /user_home, it doesn't allow me, which is fine. My question is: how can I define another "isLoggedIn" function that checks if I am logged in as an admin rather than a regular user? Ideally I would like to have a function "isLoggedInAsUser" and another one "isLoggedInAsAdmin".

So far I tried defining the /admin_home route the same way:

app.get('/admin_home', isLoggedIn, function(req, res) {
    // render the page
});

But it's obvious why it doesn't work. The code doesn't know that I want it to check if it's an admin rather than a regular user.

Upvotes: 2

Views: 1994

Answers (2)

zaynetro
zaynetro

Reputation: 2308

Passport stores authenticated user in req.user. So you can write middleware functions like this:

function allowAdmins(req, res, next) {
  if (req.user.role === 'Admin') return next();
  res.redirect('/user-login');
}

function allowRegular(req, res, next) {
  if (req.user.role === 'Regular') return next();
  res.redirect('/admin-login');
}

And then in routes:

var userRouter = express.Router();

userRouter.use(isLoggedIn);
// Only authenticated users are allowed
userRouter.get('/home', isRegular, function (req, res) {});
userRouter.get('/admin', isAdmin, function (req, res) {});

app.use('/user', userRouter);

Upvotes: 5

HDK
HDK

Reputation: 814

in session object store role information

in the route configuration level, write middleware like

    var adminRoutes = express.routes();

    adminRoutes.route('/admin/*', function (req, res,next)
    {

    if(req.session.role==='Admin')

    return next();

   else
   {
   res.send("Authorization Error")
   }


    }
    app.use(adminRoutes);

same for user routes

Upvotes: 1

Related Questions