Is this the only and recommended way?
To a large extent, yes.
this is not a “controller function”. This is an example of middleware that you want to use in this case.
a more complete example would be:
var router = new express.Router();
var processjwt = jwt({secret: 'shhhhhhared-secret'});
function authorizationCheck(req, res, next) {
if (!req.user.admin) {
return res.sendStatus(401);
} else {
next();
}
}
function myRouteHandler(req, res){
doSomeWork(function(err, data){
if (err) { return next(err); }
res.json(data);
});
}
router.use("/protected", processjwt, authorizationCheck);
router.get("/protected", myRouteHandler);
There are dozens of options for this setup that you can use, but it gives an idea.
source
share