Eric Zhang Eric Zhang - 2 months ago 10
Javascript Question

Why "req.user" always empty in the /user/me controller after validation with sails-auth?

I'm currently getting started with Sails.js, and I want to add user accounts to my toy app, so I installed the "sails-auth" package that creates a Passport-based user authentication system. I can create new users by sending

POST /user
, and I can sign in with
POST /auth/local
.

The documentation says:


Authenticate with the local strategy via a POST to /auth/local with params identifier (email) and password). This will also create a session. See passport.local for more.


However, when I try to
GET /user/me
, which routes to a controller action that should return the current user in the session, the page instead gives an empty response. Why is this happening? Is there some kind of configuration step that I'm missing?

By the way, I haven't changed or messed around with the sails-auth package. It's still completely new; the "me" action looks like this:

me: function (req, res) {
res.ok(req.user);
}


EDIT: I've found a temporary workaround by searching the issues in the sails-auth repo. Instead of getting a user object from
req.user
, you can get a string user ID from
req.session.passport.user
.

Answer

Your me action as written is only going to return whatever you are passing in as the user param. Sails builds on top of Express.js so req is the request from the browser and res is the response to the browser.

Most likely you are sending the data to your me action in the req body which is why your response is blank, simply put, req.user is empty so the response is empty. In that case you would access it with req.body.user, you could also try var user = req.params();

For debugging and just generally getting a feel for how the req and res objects are structured I suggest you always start sails (in development, never in production) with the verbose flag.
sails lift --verbose

Then you can do this:

me: function(req, res){
   sails.log.verbose(req);
   res.ok(req.user);
}

And have it print out the entire req object so you know what's in req.user.

Typically though you would do a database lookup as the user param would be an id. Which means your me function might look (something, obviously depending on your dbc it might be pretty different) like:

me: function(req, res){
    var userId = req.body.user;
    User.find({'user_id': userId}.exec(function(err, user){
        if(err){
            //tell peeps there was an error
        }else{
            res.ok(user);
        }
    });
}

Best debugging for routes and for the request object:

    '/*' : function(req, res, next) {
        sails.log.verbose("method: ", req.method, "\n body: ", req.body, "\n url:", req.url);
        next();
    },

Just paste that at the start of your routes module.