How do Allow only Admins to have access to the Admin page in Nodejs `AdminBro`

1.1k Views Asked by At

How do Allow only Admins to have access to the Admin page in AdminBro? Nodejs

All that I want is for only Admins to have access to the adminBro page, is there any specific method to get this done?

I did this in my app.js file but it's not working

app.get("/admin", function (req, res, next) {
  res.locals.login = req.user;
  if (res.locals.login.roles == "admin") {
     app.use("/admin", adminRouter);
  } else {
    res.redirect("/");
 }
});
1

There are 1 best solutions below

1
On BEST ANSWER

You cannot use new app.use inside app.get, as (req, res, next) are already consumed. You have two of choice:

  1. Your route in if condition body
if (res.locals.login.roles === 'admin') {
   // your admin route logic
   res.send('admin page')
} else {
  res.redirect('/')
}
  1. I'm used to use small middleware function like this one:
const isAdmin = (req, res, next) => {
  if (req.user.roles === 'admin') {
    return next();
  }
  res.redirect('/');
};

Then you use it in whichever route this way:

app.get('/admin', isAdmin, adminRouter)