Diego
Diego

Reputation: 651

How to handle authorization in a layered nodejs with passport app?

So I'm trying to build an app with nodejs, using express and passport, but as I try to do some kind of TDD, I want to decouple bussiness logic from controllers.

So I have a common scenario like this:

So I was wondering if there is any way to get the current user from any layer without passing it from the controller.

Upvotes: 0

Views: 304

Answers (1)

gfpacheco
gfpacheco

Reputation: 3215

You should ensure the user owns the item before even passing it to the controller, in the routes configuration:

app.del('/api/item/1', ensureUserOwnsItem, itemController.delete);

This will cause the function ensureUserOwnsItem to be called before calling the controller. It should looks like this:

function ensureUserOwnsItem(req, res, next) {
    if (/* user owns item */) {
        next();
    } else {
        res.send(401, 'You can\'t delete an item you don\'t own');
    }
}

You would be able to reuse it on the POST route:

app.post('/api/item/1', ensureUserOwnsItem, itemController.post);

I recommend you put this function inside an AuthController or something like that.

Upvotes: 1

Related Questions