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.