Erik
Erik

Reputation: 14750

checking user auth

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?

Upvotes: 0

Views: 703

Answers (1)

Florian Margaine
Florian Margaine

Reputation: 60717

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.

Upvotes: 4

Related Questions