4
votes

I am using sails-generate-auth in my sails.js app. I followed this tutorial to integrate this with my app. When I call localhost:1337/auth/local/register it routes to my callback action in AuthController. My callback action is as follows

callback: function (req, res) {
        function tryAgain(err) {
                //some validation
                }
        }

passport.callback(req, res, function (err, user, challenges, statuses) {
            if (err || !user) {
                return tryAgain(challenges);
            }

            req.login(user, function (err) {
                if (err) {
                    return tryAgain(err);
                }

                //Return the access token created by passport instead of success.
                res.send("Success");
            });
        });

I want to replace res.send("Success"); with the access token created by passport. But User.passport seems to be null at this point. How do I get the user's access token at this point?

2

2 Answers

3
votes

The User You Get only contains the data from the 'User Collection' which contains the username email and id. The 'Passport' collection is a seperate collection which contains hashed password, ID, userID(which is equal to the ID In the 'User' Collection) and a token. You need to search in the 'passport' collection for the relavent User. Here is the algoritem:

passport.callback(req, res, function (err, user, challenges, statuses) {
  if (err || !user) {
    console.log(err);
    return tryAgain(challenges);
  }

  req.login(user, function (err) {
    if (err) {
      console.log(err);
      return tryAgain(err);
    }

    // Mark the session as authenticated to work with default Sails sessionAuth.js policy
    req.session.authenticated = true

    console.log(user);
    var userID = user.id;
    Passport.find({user: userID}, function(err, items){
        if(err) return err;

        console.log(items[0].accessToken);
        // Make sure you dont give them any sensetive data
        res.json({userData: user, token: items[0].accessToken});
    });
    // Upon successful login, send the user to the homepage were req.user
    //res.redirect('/');
  });
});

0
votes

If you want to use sails built-in sessions, you do not need to send any token to the client, everything is stored server-side in the sessions and it is tied to the user by the sid (session id) cookie, therefore you can redirect to any page.

As long as you have your sessionAuth policy it will check that the user is logged-in before accessing your protected routes.

If you would like to use something like Json Web Tokens (JWT) though, sails-generate-auth / sails-auth do not support it yet