checking user auth

Problem

I have the middleware that allows me to check user auth, here is:

function checkAuth(req, res, next) {
 if (!req.session.user_id) {
   res.redirect('/login');
 } else {
    next();
 } 
}

I have the two question about it;

  1. Is it strong user auth checking? or should I check user.id in DB like the follows:

    if (!req.session.user_id) {
       res.redirect('/login');
    } else {
      User.findById(req.session.user_id, function (err, user) {
        if (!user) return res.redirect('/login');
        else return next();
     })
    }
    
  2. If the checking is failed I do redirecting to login page:

     res.redirect('/login');
    

    but if I get an AJAX request I should to send the following (I think)

     res.send(403, 'Permission denied');
    

    so how can I check a type of request and send an appropriate type of response? Is it correct approach to do like above?

Problem courtesy of: Erik

Solution

Checking the session is enough. There is a mapping between the server's session and the client's, which is why it's secure enough. Of course you're using SSL if you want "absolute" security (but 100% security doesn't exist).

Here is how Django/RoR check if the request comes from an AJAX call (converted in node.js code):

function isXHR( req, res ) {
    return !!req.header( 'HTTP_X_REQUESTED_WITH' ) === 'XMLHttpRequest';
}

However, that means that the XHR call must include this HTTP header. Most libraries do it (jQuery, Dojo, YUI, ...), but if you're doing manual XHR requests, you must not forget to include it.

Another way which might suit your needs:

function isJSON( req, res ) {
    return !!req.header( 'Content-Type' ) === 'application/json';
}

There, you're checking for the Content-Type header. If it asks some JSON datas (like most of XHR requests), you send it some JSON datas.

Solution courtesy of: Florian Margaine

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.