tergd1
tergd1

Reputation: 558

Applying condition for the whole route nodejs

I have a RESTful Api in Nodejs app and I'm checking for a user role before sending a response with data or 404.

apiRouter.route('/users')
    .get(function (req, res) {
        var currentUser = req.decoded; // getting logged in user here
        if(currentUser.isInstructor || currentUser.isAdmin){ //checking for user's role
            User.find(function (err) {
                if(err)
                    res.send(err);
            }).exec(function (err, users) {
                res.json(users);
            })
        }else
            res.send(404);
    });

Currently, I have to check for the user's role in get, post, put, and delete params for /users route (for example) and write the same code, basically. Is there a better way of doing this?


Based on the adneo answer, I'm checking for a role before /user route:

apiRouter.all('/users', function (req, res, next) {
        var currentUser = req.decoded;
        var isAuthorized = false;

        if (currentUser.isInstructor || currentUser.isAdmin)
            isAuthorized = true;

        if(!isAuthorized)
            res.send(404)
    })

If the user is authorized all the logic for different verbs in /users will execute.

Upvotes: 3

Views: 1974

Answers (1)

adeneo
adeneo

Reputation: 318212

You can use router.all to attach it to all HTTP verbs etc

apiRouter.all('/users', function (req, res, next) {
    var currentUser = req.decoded; // getting logged in user here
    if(currentUser.isInstructor || currentUser.isAdmin){ //checking for user's role
        User.find(function (err) {
            if(err)
                res.send(err);
        }).exec(function (err, users) {
            res.json(users);
        })
    }else
        res.send(404);
});

Upvotes: 5

Related Questions