waris
waris

Reputation: 204

loopback x3 get accesstoken in a remote model

I need to get the token in a models of loopback 3, how to get the access token and user-id in a remote model or other models?

i have been trying.

code:

module.exports = function(app) {


const User = app.models.User;
  User.userDemo= function (cb) {
console.log(here access token);
    User.find({
      fields:['username','email']
    },cb);
  };
  User.remoteMethod(
    'userDemo',
    {
      http: {path:'/user-demo', verb: 'get'},
      returns: { arg: '', type:'array',root:true}
    }
  );
};

Upvotes: 1

Views: 448

Answers (1)

Ivan Schwarz
Ivan Schwarz

Reputation: 814

Currently the suggested solution is to seed the options argument when a method is invoked via a REST call. The options argument must be annotated in remoting metadata with a specific value set in the http property.

  user.userDemo = function (options, cb) {
    // options object contains context information (accessToken, currentUser, ...)
    console.log(options); 
    user.find({
      fields: ['username', 'email']
    }, cb);
  };

  user.remoteMethod(
    'userDemo',
    {
      http: {path: '/user-demo', verb: 'get'},
      accepts: [
        {arg: 'options', type: 'object', http: 'optionsFromRequest'}
      ],
      returns: {root: true}
    }
  );

Extra information:

In LoopBack 2.x they introduced current-context APIs using the module continuation-local-storage (or later cls-hooked). It worked for many people's cases, but it had its issues making it an unreliable dependency. In Loopback 3.x, they moved away from these APIs and offered an alternative in form of options object propagation (part of it is what you see in the example code above). You can still use the old way by including loopback-context package, but it's on your own risk.

Upvotes: 2

Related Questions