Skip to content

loopback.getCurrentContext() seems to return null when MySQL is used #878

Closed

Description

@diasalvatore

As in #569 I was trying to set currentUser in context in order to retrieve it after in requests.

  app.use(loopback.token()); // this calls getCurrentContext
  app.use(loopback.context()); // the context is started here

  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();
    });
  });

the problem is that loopback.getCurrentContext() returns null so it will not be set.
Why does this happen?

Activity

  1. doublemarked commented on Nov 27, 2014

    @doublemarked

    I am using almost precisely the same code, also extracted from #569. It works okay for me. Where are you placing the code?

  2. diasalvatore commented on Nov 27, 2014

    @diasalvatore
    Author

    In my server.js.

    I am using loopback 2.8.2, node 0.10

  3. doublemarked commented on Nov 27, 2014

    @doublemarked

    All the same on my side, sorry. If you post a more complete code snippet I can do a more thorough comparison, if you like.

  4. diasalvatore commented on Nov 28, 2014

    @diasalvatore
    Author

    Here it is: http://pastebin.com/kiHwaVeh but it's almost the default server.js, thank you.
    Have I to set something in configuration somewhere?

  5. doublemarked commented on Nov 28, 2014

    @doublemarked

    There is no special configuration for it that I have done.

    Can I suggest you do an npm upgrade on your project to ensure related modules are not at an incompatible version?

  6. diasalvatore commented on Nov 28, 2014

    @diasalvatore
    Author

    I did it, nothing changed.

    This is the getCurrentContext() function in loopback, ns is created, but ns.active is null so it returns null.

      function createContext(scope) {
          // Make the namespace globally visible via the process.context property
          process.context = process.context || {};
          var ns = process.context[scope];
          if (!ns) {
            ns = cls.createNamespace(scope);
            process.context[scope] = ns;
            // Set up loopback.getCurrentContext()
            loopback.getCurrentContext = function() {
              return ns && ns.active ? ns : null;
            };
    
            chain(juggler);
            chain(remoting);
          }
          return ns;
      }
    

    I really don't know why it doesn't work, it seems that everyone uses this code snippet

  7. doublemarked commented on Nov 28, 2014

    @doublemarked

    I have built you a very simple project which implements this routine. Everything seems to work fine. Perhaps you can use it to find what's broken in your project: http://goo.gl/CCrbgM

  8. diasalvatore commented on Nov 28, 2014

    @diasalvatore
    Author

    Thank you, you were very kind. I did the same creating a new loopback application and it works either!
    How strange is that?
    Now I'll put all old files in this projects and hope. Thank you again!

  9. diasalvatore commented on Nov 28, 2014

    @diasalvatore
    Author

    Could you try what happens if you link your User model to a MySQL datasource?
    Because if I do this, it returns null to me

  10. doublemarked commented on Nov 28, 2014

    @doublemarked

    I'm not set up right now with a MySQL datasource, but can try perhaps in a day or two. Sounds like you may have found the difference, though.

  11. diasalvatore commented on Nov 28, 2014

    @diasalvatore
    Author

    Finally, but it costed me one day.
    Here is your example with MySQL configured: https://www.dropbox.com/s/uobkp2x8bg610o6/contextTestBugged.zip?dl=0

    I hope that MySQL is the cause (and if it is that someone will fix it!)

  12. changed the title [-]Problem trying to set current user in context[/-] [+]loopback.getCurrentContext() seems to return null when MySQL is used[/+] on Nov 28, 2014
  13. serkanserttop commented on Nov 28, 2014

    @serkanserttop

    Just a suggestion, I did not test it, but could you try
    app.use(loopback.context());
    app.use(loopback.token());
    rather than
    app.use(loopback.token());
    app.use(loopback.context());

  14. doublemarked commented on Nov 29, 2014

    @doublemarked

    @diasalvatore Your test project w/ a MySQL datastore indeed does fail for me also.

  15. bajtos commented on Dec 1, 2014

    @bajtos
    Member

    This is most likely a duplicate of #809. There is a pending pull request #885 to fix the problem.

  16. 94 remaining items

  17. stringbeans commented on Jan 29, 2016

    @stringbeans

    Could this issue affect loopback's implementation of checking whether a user in authenticated via the ACL? ie. with principalId: "$authenticated"

  18. Nivl commented on Feb 4, 2016

    @Nivl

    Just got the issue again. Updating a model in a RemoteMethod was causing the getCurrentContext in the model's access to be null.

    I fixed the issue by… removing newrelic (see #1984 )

  19. stringbeans commented on Feb 26, 2016

    @stringbeans

    Should everyone be avoiding using node above v0.12.* for right now with loopback?

  20. tomcooksey commented on Apr 29, 2016

    @tomcooksey

    I have got this working on newer versions of Node, including the latest 5.9.1 - but only on certain machines - for instance my dev machine it works fine, on my colleague's it has this same problem. However, reverting to 0.12.13 version of Node it seems to work reliably across machines and servers. Obviously this is annoying as this is quite an old version of Node. Is there any update on this?

  21. stringbeans commented on May 10, 2016

    @stringbeans

    Just ran into this again with 5.10.1... the issue is very intermittent

  22. rwngallego commented on Jun 12, 2016

    @rwngallego

    If this is currently an intermittent issue why don't we change the documentation to warn this is currently not working. I have to spend some hours before I noticed it was a problem in the framework not in my own code. Also as it's intermittent it could led people to release their software with a piece of code that will be affecting in a bad manner their production software. This is unacceptable.

    We should add a warning right here: https://docs.strongloop.com/display/public/LB/Using+current+context

  23. thanickel commented on Jun 29, 2016

    @thanickel

    I am seeing this issue when using promises. Every call that is made to getCurrentContext from a promise completion is causing it to be null. Not just before save, access is also returning null. Possibly others as well. I have switched to callback and is working fine. Tried with node v4.4.5 and v4.4.7 LTS versions

  24. CarlosCuevas commented on Jul 5, 2016

    @CarlosCuevas

    Never had this issue. Changed nothing but my version of node from 0.10 to 4.4.7 and it started. Using callbacks with async lib, not promises.

    I added require('continuation-local-storage'); to the top of server.js and the issue seems to have gone away, though the fact that it happens intermittently makes me question the results. This issue, however, boosts my confidence in it as a fix: othiym23/node-continuation-local-storage#55

  25. jeff3yan commented on Jul 6, 2016

    @jeff3yan

    Have had this issue intermittently and can't seem to reproduce it consistently on any environment, but it's enough to discourage usage of getCurrentContext.

    I'm only really using the loopback context to propagate user authentication details to a couple of dynamic role resolvers. I can consistently get around this issue by directly accessing the remotingContext in the role resolvers, although this isn't ideal as pointed out by #1495.

    This means that the implementation won't be transport agnostic, but for now at least the issue seems to have disappeared completely.

  26. peeter-tomberg commented on Jul 13, 2016

    @peeter-tomberg

    Having the same issue while using promises with Transactions. Switched to callbacks and it worked. Same issue appeared in an after save hook where I used callbacks though. Turns out the issue was cause I used a promise in a asyncValidator and that messed up the after save (even though I didn't use any promises in there).

  27. bajtos commented on Jan 9, 2017

    @bajtos
    Member

    Hello. The original getCurrentContext implementation was based on continuation-local-storage that's know to loose the context in many situations. We decided to deprecate this API in favour of an explicit propagation of context via the "options" argument, see #1495 and the related pull requests.

    In the meantime, a new version looopback-context@3.0.0 offers a different implementation of getCurrentContext, this one is based on cls-hooked that should work better on Node 4 and newer. Feel free to give it a try. If you run into any issues with loopback-context, then please report them in loopback-context's repository on GitHub.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions