Skip to content

Instantly share code, notes, and snippets.

@matt212
Created January 11, 2017 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matt212/a9fc715abfc81f125d59f5226c98053b to your computer and use it in GitHub Desktop.
Save matt212/a9fc715abfc81f125d59f5226c98053b to your computer and use it in GitHub Desktop.
function isAuth(req, res, next) {
var token = req.body.token || req.param('token') || req.headers['x-access-token'];
//check whether request has token !
if (token != undefined) {
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
if (err) {
return res.json({
success: false,
message: 'Failed to authenticate token.'
});
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
})
}
} else {
//check whether request is api or normal request !
var string = req.url,
substring = "api";
if (string.indexOf(substring) !== -1) {
res.status(403).send({
success: false,
message: 'No token provided.'
})
} else {
//check whether request is authenticated or not !
if (req.isAuthenticated())
return next();
/* res.status(401).json({authenticated: false});*/
res.redirect('/login');
}
}
}
@matt212
Copy link
Author

matt212 commented May 21, 2017

Usage of my above codebase !

var employees = require('./routes/employees');
app.use('/employees ', isAuth, employees );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment