0

Im using PassportJS in ExpressJS application:

In app.js, I have route for admin-only and requiresAdmin function:

var requiresAdmin = function() {
    return [
        ensureLoggedIn('/login'),
        function(req, res, next) {
            if (req.user && req.user.admin === true){
                next();
            }else{
                res.send(401, 'Unauthorized');
            }
        }
    ];
};

app.all('/admin/*', requiresAdmin());

I created another route that will return JSON object. Also can be accessed by admin.

app.all('/api/admin/*', requiresAdmin());

If users are not logged in or non-admin, how to return JSON using the above approach? Thanks

1
  • Why not using the content negotiation feature of express? see this link: res.format Commented Sep 6, 2013 at 2:47

1 Answer 1

1

I would use Express.js content negotiation feature by just replacing your res.send with the following:

res.format({
  'text/plain': function(){
    res.send(401, 'Unauthorized');
  },

  'application/json': function(){
    res.send(401, { message: 'Unauthorized' });
  }
});

More info here: http://expressjs.com/api.html#res.format

Don't forget to replace your res.send within ensureLoggedIn, and remember that you will might need to enforce your clients to send the proper accept header within their http requests.

Sign up to request clarification or add additional context in comments.

2 Comments

Im using module github.com/jaredhanson/connect-ensure-login, where to replace res.send?
Sorry I thought it was a function you wrote your self. Have a look at this issue: github.com/jaredhanson/connect-ensure-login/pull/3 - Not sure how you will have to deal with this scenario as you are using a third party library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.