Expressjs Session


How can we use the sessions middleware?

Every page which starts with /admin should be protected. To achieve this, we are going to use Express's middleware: Sessions. It simply attaches an object to the request called session. We should now change our Admin controller to do two additional things:

  • It should check if there is a session available. If not, then display a login form.
  • It should accept the data sent by the login form and authorize the user if the username and password match.

Here is a little helper function we can use to accomplish this:

authorize: function(req) {
    return (
        req.session && 
        req.session.fastdelivery && 
        req.session.fastdelivery === true
    ) || (
        req.body &&
        req.body.username === this.username &&
        req.body.password === this.password

First, we have a statement which tries to recognize the user via the session object. Secondly, we check if a form has been submitted. If so, the data from the form is available in the request.body object which is filled by the bodyParser middleware. Then we just check if the username and password matches.

And now here is the run method of the controller, which uses our new helper. We check if the user is authorized, displaying either the control panel itself, otherwise we display the login page:

run: function(req, res, next) {
    if(this.authorize(req)) {
        req.session.fastdelivery = true; {
            var v = new View(res, 'admin');
                title: 'Administration',
                content: 'Welcome to the control panel'
    } else {
        var v = new View(res, 'admin-login');
            title: 'Please login'
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License