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.
I've done it using the following:
.use(function(err, req, res, next) {
if(err) {
return res.status(constants.INVALID_OR_NO_ACCESS_TOKEN.code).json({
status: 'error',
code: constants.INVALID_OR_NO_ACCESS_TOKEN.code,
message: constants.INVALID_OR_NO_ACCESS_TOKEN.message
}).end();
}
User.find({
where: {
id: req.user.id
}
})