I'm implementing JWT authorization for each API like below:
auth.js
import expressJwt from 'express-jwt';
import compose from 'composable-middleware';
var validateJwt = expressJwt({
secret: config.secrets.session
});
function isAuthenticated() {
return compose()
.use(function(req, res, next) {
validateJwt(req, res, next);
})
.use(function(req, res, next) {
User.find({
where: {
id: req.user.id
}
}).then(function(user){
//Handle User
}).catch(function(err){
//Handle DB Error
});
});
}
index.js
import auth from '../../auth';
import express from 'express';
import controller from './user_group.controller';
import * as validators from './user_group.validations';
// Create router object
const router = express.Router();
// Get all user groups
router.get('/', [auth.isAuthenticated(), validators.index], controller.index);
Everything is working absolutely fine except error handling of JWT. I'm not understanding the function validateJwt(req, res, next);
that how to handle the Unauthorized Error stack
before moving to the next middleware.
Manish Jangir :
I've done it using the following:\n\n.use(function(err, req, res, next) {\n\n if(err) {\n return res.status(constants.INVALID_OR_NO_ACCESS_TOKEN.code).json({\n status: 'error',\n code: constants.INVALID_OR_NO_ACCESS_TOKEN.code,\n message: constants.INVALID_OR_NO_ACCESS_TOKEN.message\n }).end();\n }\n User.find({\n where: {\n id: req.user.id\n }\n })\n",
2016-06-08T13:26:43