Get Off My Lawn
Get Off My Lawn

Reputation: 36351

Express.js require session to access particular routes

I have an app where certain pages require that the user be logged in.

I am not sure if there is something built in for this, but what I have for doing this is as follows:

app.use((req, res, next) => {
  if (req.session.username) {
    app.get('/project/create', projectCtrl.create)
    app.get('/project/create/save', projectCtrl.save)
  } else {
    return res.redirect('/')
  }
  next()
})

Is this the correct way of doing this, or is there a better way in express? The way I am doing it kind of feels a little hacky.

Upvotes: 1

Views: 45

Answers (2)

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38992

Yes, that's one correct way of doing it. What you have is an application-level middleware in express. It gets called for every request the application receives.

You can extract the username check and apply that as a route middleware substack. This way the middleware only gets executed for the routes it's applied to.

function gatePass(req, res, next) {
   if(req.session.username) {
      next();
   }
   else {
     return res.redirect('/');
   }
}

app.get('/project/create', gatePass, projectCtrl.create)
app.get('/project/create/save', gatePass, projectCtrl.save)

You can take this a bit further if you'll like to separate concerns by using express router together with route-level middleware. This also applies a middleware directly to the routes.

var router = express.Router();

router.use('/project/create', gatePass);
router.use('/project/create/save', gatePass);

router.get('/project/create', projectCtrl.create);
router.get('/project/create/save', projectCtrl.save);

app.use('/', router);

Upvotes: 1

sheplu
sheplu

Reputation: 2975

this solution work. It's not the best but for small project it will be good. The only drawback is that you will need to define every route you want to be check with a session.

Nodejs is the world of middleware, so why not use one? I think it's the best thing to do.

Verify is a file where I export my middleware and I apply it on all my router.. (in this case it's just to check if the user is logged or not)

var verify = require('./verify');

router.all('/*', verify.isLogged, function(req, res, next) {
  if(req.decoded._doc.isLogged == "") {
    next();
  }
  else {
    res.json("error");
  }
});

This way, if in the future you need to check one thing, then another one, you will just need to call you function where you want to check

router.get('/test', verify.isLogged, verify.isAdmin function(req, res, next) {
  if(req.decoded._doc.isAdmin == "") {
    next();
  }
  else {
    res.json("error");
  }
});

Upvotes: 0

Related Questions