loopback icon indicating copy to clipboard operation
loopback copied to clipboard

How to get current authenticated user

Open cajoy opened this issue 12 years ago • 75 comments

In requeest I have valid access token so user available in beforeRemote as part of ctx

But how can I get userId from inside of function. For example:

model.js

var loopback = require('loopback');

module.exports = function(someModel) {

someModel.getUserId = function(callback) {
    // ??? How ???
    var userId = loopback.request.getUserId();
};

spent 3 hours on it and can't find easy solution... Basically how can I get user ID from any place in the code?

cajoy avatar Sep 18 '14 17:09 cajoy

In the beforeRemote, you can find the userId in ctx.res.token.userId Not sure this is the best solution or not.

meng-zhang avatar Sep 19 '14 13:09 meng-zhang

Yes I know it.

But what if I need it inside of function? not in hook? Or how can I pass it to the function without using global variables?

Thanks

cajoy avatar Sep 19 '14 14:09 cajoy

I am afraid there is no way how to pass the current user to the remoted method. We are working on a solution that will make this possible - see https://github.com/strongloop/loopback/pull/337

bajtos avatar Sep 20 '14 00:09 bajtos

A hacky workaround: use the new header argument source (see https://github.com/strongloop/strong-remoting/pull/104) to get the access-token from the request header, then look up the userId by querying access tokens.

bajtos avatar Sep 20 '14 00:09 bajtos

For anyone else having this problem, here is my implementation of the "hacky workaround" suggested by @bajtos . I put this in my server.js file.

// Retrieve the currently authenticated user
app.use(function (req, res, next) {
  // First, get the access token, either from the url or from the headers
  var tokenId = false;
  if (req.query && req.query.access_token) {
    tokenId = req.query.access_token;
  }
  // @TODO - not sure if this is correct since I'm currently not using headers
  // to pass the access token
  else if (req.headers && req.headers.access_token) {
    // tokenId = req.headers.access_token
  }

  // Now, if there is a tokenId, use it to look up the currently authenticated
  // user and attach it to the app
  app.currentUser = false;
  if (tokenId) {
    var UserModel = app.models.User;

    // Logic borrowed from user.js -> User.logout()
    UserModel.relations.accessTokens.modelTo.findById(tokenId, function(err, accessToken) {
      if (err) return next(err);
      if ( ! accessToken) return next(new Error('could not find accessToken'));

      // Look up the user associated with the accessToken
      UserModel.findById(accessToken.userId, function (err, user) {
        if (err) return next(err);
        if ( ! user) return next(new Error('could not find a valid user'));

        app.currentUser = user;
        next();
      });

    });
  }

  // If no tokenId was found, continue without waiting
  else {
    next();
  }
});

brainthinks avatar Oct 27 '14 20:10 brainthinks

This is the workaround I used on a custom route /whoami

    router.get('/whoami', function (req, res) {
        var app = require('../server');
        var AccessToken = app.models.AccessToken;
        AccessToken.findForRequest(req, {}, function (aux, accesstoken) {
            console.log(aux, accesstoken);
            if (accesstoken == undefined) {
                res.status(401);
                res.send({
                    'Error': 'Unauthorized',
                    'Message': 'You need to be authenticated to access this endpoint'
                });
            } else {
                var UserModel = app.models.user;
                UserModel.findById(accesstoken.userId, function (err, user) {
                    console.log(user);
                                       res.status(200);
                                       res.send();
                });
            }
        });
    });

this route is inside /server/boot/root.js

ffflabs avatar Oct 27 '14 21:10 ffflabs

@amenadiel - thanks for posting your solution! I didn't know about that AccessToken method findForRequest. Here is my solution updated to use that method, which solves my original TODO:

// Retrieve the currently authenticated user
app.use(function (req, res, next) {
  app.currentUser = null;

  // Retrieve the access token used in this request
  var AccessTokenModel = app.models.AccessToken;
  AccessTokenModel.findForRequest(req, {}, function (err, token) {
    if (err) return next(err);
    if ( ! token) return next(); // No need to throw an error here

    // Logic borrowed from user.js -> User.logout() to get access token object
    var UserModel = app.models.User;
    UserModel.relations.accessTokens.modelTo.findById(token.id, function(err, accessToken) {
      if (err) return next(err);
      if ( ! accessToken) return next(new Error('could not find the given token'));

      // Look up the user associated with the access token
      UserModel.findById(accessToken.userId, function (err, user) {
        if (err) return next(err);
        if ( ! user) return next(new Error('could not find a valid user with the given token'));

        app.currentUser = user;
        next();
      });

    });
  });

});

brainthinks avatar Oct 28 '14 14:10 brainthinks

I don't recommend attaching the user to the app object, it will stop working once you have more than one request being handled in parallel.

Setting that aside, here is a simpler solution:

app.use(loopback.token());
app.use(function(req, res, next) {
  app.currentUser = null;
  if (!req.accessToken) return next();
  req.accessToken.user(function(err, user) {
    if (err) return next(err);
    app.currentUser = user;
    next();
  });
});

But as I said, don't do that. It creates a hard to debug bug where Request A sees app.currentUser filled by Request B in case these requests arrive at the server (almost) in parallel.

bajtos avatar Oct 29 '14 13:10 bajtos

@bajtos - wow, thank you for taking the time to point this out. To take your advice and avoid this potential (serious) problem, I have attached the currentUser to the request object rather than the app object so that it is specific to the remote context, as follows:

app.use(loopback.token());
app.use(function (req, res, next) {
  if ( ! req.accessToken) return next();
  app.models.User.findById(req.accessToken.userId, function(err, user) {
    if (err) return next(err);
    if ( ! user) return next(new Error('No user with this access token was found.'));
    req.currentUser = user;
  });
});

I tried first using req.accessToken.user(), but user kept being returned as null.

Now, I am able to access this currentUser in all of my beforeRemote hooks via ctx.req.currentUser. I think this should avoid any issues of user B's credentials being available in user A's request, as each request is a different object, thus each request will have the correct user's information.

brainthinks avatar Oct 29 '14 19:10 brainthinks

@mymainmanbrown - this helped a lot, thank you! I am quite satisfied with the end result of this thread.

Small note: your sample above is missing a final next() call after the currentUser is assigned.

doublemarked avatar Nov 10 '14 16:11 doublemarked

@bajtos - thanks for the commit!

@doublemarked - thanks for the catch. Since implementing this in my own project, I've discovered a "more proper" way of doing this, though the steps and end result are the same. Looking through the expressjs docs, I came across the entry on res.locals, which appears to be intended to store session/state data for the current request. Thus, without further ado, here is the code I'm using now, with the next() call:

app.use(loopback.token());
app.use(function (req, res, next) {
  if ( ! req.accessToken) return next();
  app.models.User.findById(req.accessToken.userId, function(err, user) {
    if (err) return next(err);
    if ( ! user) return next(new Error('No user with this access token was found.'));
    res.locals.currentUser = user;
    next();
  });
});

This is parallel-safe and can be access anywhere you have access to ctx or res.

brainthinks avatar Nov 12 '14 01:11 brainthinks

And if you want to use the new context functionality, you can store the user in the loopback context too:

app.use(loopback.context());
app.use(loopback.token());
app.use(function (req, res, next) {
  if (!req.accessToken) return next();
  app.models.User.findById(req.accessToken.userId, function(err, user) {
    if (err) return next(err);
    if (!user) return next(new Error('No user with this access token was found.'));
    res.locals.currentUser = user;
    var loopbackContext = loopback.getCurrentContext();
    if (loopbackContext) loopbackContext.set('currentUser', user);
    next();
  });
});

// anywhere in the app
var ctx = loopback.getCurrentContext();
var currentUser = ctx && ctx.get('currentUser');

bajtos avatar Nov 12 '14 09:11 bajtos

Beautiful, thank you guys.

@bajtos What is this new context functionality and where is it documented? It is new as of what version?

doublemarked avatar Nov 12 '14 15:11 doublemarked

What is this new context functionality and where is it documented? It is new as of what version?

It was not released yet, we are expecting to release it early next week. You can give it a try by installing loopback from github master (npm install strongloop/loopback). The documentation is in progress, it's not done yet.

bajtos avatar Nov 12 '14 16:11 bajtos

Until we have real docs, you can learn about the feature from the pull request - see #337.

bajtos avatar Nov 12 '14 16:11 bajtos

Ok, thank you very much! I enjoy your enthusiasm for upcoming features :)

doublemarked avatar Nov 12 '14 16:11 doublemarked

@mymainmanbrown - How would you access res.locals.currentUser inside a remote method?

pulkitsinghal avatar Dec 13 '14 23:12 pulkitsinghal

@pulkitsinghal - You need to have a res handle, which you can pass in as a parameter when you declare the remote method. However, since the recent release we've swapped to using the loopback.getCurrentContext() method that @bajtos recommended and which does not require a res handle.

doublemarked avatar Dec 13 '14 23:12 doublemarked

@doublemarked - But I just don't know how to get at the loopback variable inside a common/models/model.js file, can you suggest?

pulkitsinghal avatar Dec 14 '14 21:12 pulkitsinghal

It's a handle for the loopback module,

var loopback = require('loopback');

doublemarked avatar Dec 14 '14 21:12 doublemarked