Set current user in NodeJS with Express

We always want to access currentUser in all the controllers. I have seen many people use the token to fetch the user all the time.

Instead I think it’s better we set the currentUser in the middleware at the time of authentication.

var jwt = require('jsonwebtoken');
var config = require('./../config/config.constants');

module.exports = function (req, res, next) {

  // check header or url parameters or post parameters for token
  var token = req.body.token || req.query.token || req.headers['x-access-token'] || req.headers['authorization'];

  // decode token
  if (token) {

    var hash = config.secret.replace(/^\$2y(.+)$/i, '\$2a$1');
    // verifies secret
    jwt.verify(token, hash, function (err, decoded) {
      if (err) {
        return res.status(403).json({ message: 'Invalid token' });
      } else {
        // if everything is good, save to request for use in other routes
        req.decoded = decoded;
        wpUserModel.getUserInformationById(req.decoded.id, function (err, user) {
          req.currentUser = user;
          next();
        });
      }
    });
  } else {
    // if there is no token

    return res.status(403).json({
      message: 'Invalid token'
    });
  }
};

As you can see in the above gist, I have set currentUser after successfully check the authentication token.

So, now we can easily access currentUser in all your controllers like req.currentUser

If you are looking to get an application developed may it be a web application or a mobile application just drop us a message and experts from Third Rock Techkno will get back to you in 4 hours.

Visit Third Rock Techkno to know more about our expertise in AngularJS, NodeJS and IONIC.

· · · ·

Third Rock Techkno is a leading IT services company. We are a top-ranked web, voice and mobile app development company with over 10 years of experience. Client success forms the core of our value system.

We have expertise in the latest technologies including angular, react native, iOs, Android and more. Third Rock Techkno has developed smart, scalable and innovative solutions for clients across a host of industries.

Our team of dedicated developers combine their knowledge and skills to develop and deliver web and mobile apps that boost business and increase output for our clients.

5 Reasons Why a Bad UX Can be dangerous for your App

As we approach the year 2020 the emphasis on consumer or user-driven products could not be any stronger. The narrative has now changed from Customer is King to Value Creation for Your Users.

Read More

How angular routing works?

Angular Routing to help in navigating from one page to another page in a web application.

Read More

11 Must-Have eCommerce Mobile App Features

When it comes to shopping, smartphones provide the most accessible platform to users across the globe. It is estimated that mobile apps will dominate online sales by 2021, accounting for 54% of total online sales. Unsurprisingly then, the eCommerce mobile app development industry is booming.

Read More