title: Nodejs Express3 using sessions to check if user is logged in
body: <p>I have the following <code>app.js</code> code</p>
  
  <pre><code>app.configure(function(){
    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/views');
    app.enable('jsonp callback');
    app.set('view engine', 'jade');
    app.set('view options', {layout : false});
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.cookieParser());
    app.use(express.session({
      secret : 'abcdefg'      
    }));
    app.use(app.router);
    app.use(express.static(__dirname + '/public'));
    app.use(function(req, res, next){
      res.locals.user = req.session.user;
      next();
    })
  
  });
  </code></pre>
  
  <p>I'm trying to make it so that the following code on my <code>.jade</code> view will work</p>
  
  <pre><code>- if(session.user)
            div#logoutsection.pull-right
              a#logout-btn.btn.btn-info.pull-right.top-bar-form-button(href='logout/') Logout
              p#loginprompt.pull-right.login-prompt #{session.user.username} logged In
          - else
            ul.pull-right
              li
            a#signup-btn.btn.pull-right.top-bar-form-button(href='#signup-modal', data-toggle="modal") Sign Up
  </code></pre>
  
  <p>So if they are not signed in, provide the option to sign up, and if they are signed in, tell them they are 'logged in'. I added in the function at the end of the <code>app.configure</code> code as before it was using <code>dynamicHelpers()</code> I was told that <code>cookieParser()</code> was the way to go, but how would I code this in so that I could check whether my user was logged in and provide their username as I am trying to above?</p>
  
  <p>Any help appreciated.</p>
  
  <p>Thanks!</p>
  
  <p>EDIT: index.js</p>
  
  <pre><code>'use strict'
  
  var util = require('util');
  var Logger = require('devnull');
  var logger = new Logger({namespacing : 0});
  var User  = require('../schemas/User');
  var Post = require('../schemas/Post');
  
  /**
    * Get Meta information about all the Post's
    */
  var getAllMeta = function(req, res, next){
    Post.getAllMeta(function(err, postsList){
      if(!err &amp;&amp; postsList){
        req.postsList = postsList;
      }
      next(err);
    });
  };
  
  /**
    * validate the signup credentials entered by the user
    * @param {String} username 
    * @param {String} pass1 : first password
    * @param {String} pass2 : verification password
    */
  var validateUserData = function(username, pass1, pass2){
    if(pass1.trim() !== pass2.trim()){
      util.log('Passwords not Matching ' + pass1 + ' ' + pass2);
      return 'Passwords not Matching';
    }
    return '';
    //put any other validations here
  };
  
  /*
   * GET home page.
   */
  module.exports = function(app){
    /**
      * Map the URL '/' to the callback
      */
    app.get('/', function(req, res){
      logger.log('Serving request for url [GET]' + req.route.path)
      Post.getAll(function(err, allPosts){
        if(!err &amp;&amp; allPosts){
          res.render('index', {'allPosts' : allPosts});
        }else{
          util.log('Error fetching posts from database : ' + err);
          res.render('error');
        }
      });
    });
  
    /**
      * Map the URL '/login' to the callback
      */
    app.post('/login', function(req, res){
      logger.log('Serving request for url [POST] ' + req.route.path);
      var username = req.body.User;
      var password = req.body.Password;
  
      User.validateUser(username, password, function(err, user){
        if(err &amp;&amp; !user){
          res.json({
            retStatus : 'failure'  
          });
        }else{
          console.log(user);
          req.session.user = user;
          res.json({
            retStatus : 'success',
            user : user ,
          });
        }
      });
    });
  
    /**
      * Logout the current user and clear the session
      */
    app.get('/logout', function(req, res){
      logger.log('Serving request for url [GET] ' + req.route.path);
      req.session.user = undefined;
      res.redirect('/');
    });
  
    /**
      * Add a new User to database
      */
    app.post('/signup', function(req, res){
      util.log('Serving request for url [POST] ' + req.route.path);
      var signupForm = req.body.signupForm;
      var username = signupForm.username;
      var pass1 = signupForm.pass1;
      var pass2 = signupForm.pass2;
  
      var validateMsg = validateUserData(username, pass1, pass2);
      if(validateMsg !== ''){
        res.json({
          'retStatus' : 'failure',
          'message' : validateMsg
        });
      }else{
        var newUser = new User();
        newUser.username = username;
        newUser.password = pass1;
  
        newUser.save(function(err, savedUser){
          var message = '';
          var retStatus = '';
          if(!err){
            util.log('Successfully created new user with Username : ' + username);
            message = 'Successfully created new user : ' + username;
            retStatus = 'success';
            req.session.user = savedUser;
          }else{
            util.log('Error while creating user : ' + username + ' error : ' + util.inspect(err));
            if(err.code === 11000){
              message = "User already exists";
            }
            retStatus = 'failure';
          }
          res.json({
            'retStatus' : retStatus,
            'message' : message
          });
        });
      }
    });
  
    app.get('/admin', getAllMeta, function(req, res){
      util.log('Serving request for url [GET] ' + req.route.path);    
      if(req.session.user){
        res.render('post', {'postsList' : req.postsList});
      }else{
        res.redirect('/');
      }
    });
  
    /**
      * Save the post to database
      */
    app.post('/admin/save/post', function(req, res){
      var postContent = req.body.postContent;
  
      if(postContent.postKey === '' || postContent.postKey === undefined){
        var post = new Post();
        post.subject  = postContent.postSubject;
        post.content  = postContent.postContent;
        post.author   = req.session.user.username;
        post.tags     = postContent.postTags;
  
        post.save(function(err, response){
          if(!err &amp;&amp; response){
            util.log('Successfully saved Post with id : ' + response.id);
            res.json({
              'retStatus' : 'success',
              'data' : response
            })
          }else{
            util.log('Error saving the Post : ' + err);
            res.json({
            'retStatus' : 'failure',
              'error' : err
            });
          }
        });
      }else{
        var conditions = {'key' : postContent.postKey};
        var update = {
          'subject' : postContent.postSubject,
          'content' : postContent.postContent,
          'tags' : postContent.postTags
        };
  
        Post.update(conditions, update, null, function(err, numAffected){
          if(!err &amp;&amp; numAffected){
            util.log('Successfully updated the Post with id : ' + postContent.postKey);
            res.json({
              'retStatus' : 'success',
              'numAffected' : numAffected
            });
          }else{
            util.log('Error updating the Post with id : ' + postContent.postKey + ' ' + err);
            res.json({
              'retStatus' : 'failure'
            });
          }
        });
      }
    });
  
    app.get('/post/show/:key', function(req, res){
      Post.findByKey(req.params.key, function(err, postData){
        if(!err &amp;&amp; postData){
        postData = postData[0];
          res.json({
            'retStatus' : 'success',
            'postData' : postData
          });
        }else{
          util.log('Error in fetching Post by key : ' + req.params.key);
          res.json({
            'retStatuts' : 'failure',
            'msg' : 'Error in fetching Post by key ' + req.params.key
          });
        }
      }); 
    });
  
    app.post('/admin/save/', function(req, res){
      //container for saving a post
    });
  
    app.get('/admin/remove/:key', function(req, res){
      //container for deleting a post
    });
  
    app.get('/contact', function(req, res){
      util.log('Serving request for url[GET] ' + req.route.path);
      res.render('contact');
    });
  };
  </code></pre>
  
  <p>User.js</p>
  
  <pre><code>'use strict'
  
  var util    = require('util');
  var bcrypt  = require('bcrypt');
  var mongoose = require('mongoose');
  var Schema   = mongoose.Schema;
  
  var validatePresenceOf = function(value){
    return value &amp;&amp; value.length; 
  };
  
  var toLower = function(string){
    return string.toLowerCase();
  };
  
  var User = new Schema({
    'username' : { type : String, 
                validate : [validatePresenceOf, 'a Username is required'],
                set : toLower,
                index : { unique : true }
                },
    'password' : String,
  });
  
  User.statics.findUser = function(username, password, cb){
    return  this.find({'username' : username}, cb);
  };
  
  User.statics.validateUser = function(username, password, cb){
    this.find({'username' : username}, function(err, response){
      var user = response[0];
      if(!user || response.length === 0){
        cb(new Error('AuthFailed : Username does not exist'));
      }else{
        if(password == user.password){
          util.log('Authenticated User ' + username);
          cb(null, user);
        }else{
          cb(new Error('AuthFailed : Invalid Password'));
        }
      }
    });
  };
  
  module.exports = mongoose.model('User' , User);
  </code></pre>