1

I am little new to node js and so my all concepts regarding app.js configuration is not clear. Hence seeking some help from the community.

Currently I have following code as middleware for authentication in app.js file.

          var authChecker = function(req, res, next){
        if(req.query && (req.query.userName || req.query.username)){ // if api query is dependent on the user, validate its token.
          try{
            var authToken;
            req.headers.authorization.split(' ')[0] == "Bearer" ? authToken = req.headers.authorization.split(' ')[1] : "";
            var user = jwt.verify(authToken, 'secretkey');
            if(req.query.userName == user.username){
              next();
            }
            else{
              res.cookie('username', '', {expires: new Date(0)});
              res.cookie('token', '', {expires: new Date(0)});
              return res.status(401).json({"msg": "Authentication required."});
            }
          }
          catch(err){ // if not able to validate the token, then expire all the available token
            res.cookie('username', '', {expires: new Date(0)});
            res.cookie('token', '', {expires: new Date(0)});
            return res.status(401).json({"msg": "Authentication required."})
          }
        }
        else{
          next();
        }
      };

And I use this in same app.js file for authenticating some of the APIs.

          app.namespace('/api', function () {
          app.get('/abc', authChecker, abc.cde);

          app.get('/cde', efg.ghi); //authentication not required for this API.

Now I want to modularize this. Instead of defining authChecker in app.js, I want to have it define in a different file, and use it similarly. Can anyone please help me here. I think we can achieve this somehow by using app.js, but not sure exactly how. Please let me know if you need any more information.

3 Answers 3

1

create auth.js file, put your code then export authChecker function like this

var authChecker = function(req, res, next){
  if(req.query && (req.query.userName || req.query.username)){ // if api query is dependent on the user, validate its token.
    try{
      var authToken;
      req.headers.authorization.split(' ')[0] == "Bearer" ? authToken = req.headers.authorization.split(' ')[1] : "";
      var user = jwt.verify(authToken, 'secretkey');
      if(req.query.userName == user.username){
         next();
      } else {
         res.cookie('username', '', {expires: new Date(0)});
         res.cookie('token', '', {expires: new Date(0)});
         return res.status(401).json({"msg": "Authentication required."});
       }
     } catch(err) { // if not able to validate the token, then expire all the available token
       res.cookie('username', '', {expires: new Date(0)});
       res.cookie('token', '', {expires: new Date(0)});
       return res.status(401).json({"msg": "Authentication required."})
     }
   } else {
     next();
   }
};

module.exports = {
  authChecker: authChecker,
}

in app.js import like this

var auth = require('./auth.js'); // path to auth.js file
app.get('/abc', auth.authChecker, abc.cde);

learn more about nodejs module here: https://nodejs.org/api/modules.html

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks everyone for the answer. All answer seems right but since this answer is more detailed and answered first, I am accepting this.
1

Create new file:

authChecker.js

var authChecker = function(req,res,next) {
//your code goes here
}
export default authChecker; // you have to write this line

So in any other js files you can require this:

var authChecker = require("./pathToAuthChecker");

Comments

1

You can put the authChecker in a separate file and export it for use in app.js

auth.js

module.exports = {
  authChecker: function(req, res, next){..logic..}
}

app.js

auth = require("auth") //path to auth.js
app.get("/abc", auth.authChecker, function(req, res){});
app.get("/cde", function(req, res){});

Assuming your project layout is:

/root
  |-app.js
  |-auth.js

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.