I am working on a middleware restructuring where I am not able to call a middleware from another middleware. This is to avoid messy lines of code in the router level and move them to the function or design pattern level. Below is the example of a router code:
router.post("/v1/user", jwt.auth(), common.checkBasicValidations, auth.checkRBACAccess([auth.access.user], [auth.operation.create, auth.operation.update], auth.checkDomainAccessFromUserEmail, ["email"]), auth.checkRBACAccess([auth.access.user], [auth.operation.create, auth.operation.update], auth.checkDomainAccessFromUserId, ["_id"]), auth.checkAuthorized(), users.postUser);
jwt.auth()
, common.checkBasicValidations
, auth.checkAuthorized()
is repeating almost in every router. To get rid of the above code I did something like this:
router.get("/v1/user", policy.validatePolicies("course"), users.getLoginguserInfo);
policy.validatePolicies("course")
is a function which is handling all the above functions sequentially.
const validatePolicies = (category) => async (req, res, next) => {
try {
// validate JWT Token
jwt.auth();
//fetch users info by email
req.user = users.sessionUserInfo(req, res, next)
// validate Payload
//Validate RBAC Accsess
rbac.checkRBACAccess();
//Validate Resourse access
resource.checkResourceAccess(category)
} catch (err) {
log.warn("Problem in validatePolicies: ", err);
return next(ApiError.internal("Something went wrong")) && next(e.message);
}
next();
}
I don't know why jwt.auth()
isn't getting call. If you have any suggestions for using a different design pattern or improving the current flow, please share them with me.
const auth = () => (req, res, next) => {
// varify jwt token
}
module.exports = {
auth
}
Aucun commentaire:
Enregistrer un commentaire