How to use the loopback.getCurrentContext function in loopback

To help you get started, we’ve selected a few loopback examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github EdgeVerve / loopback-connector-nodes-for-Node-RED / loopback-ds-switcher / ds-switcher.js View on Github external
Model.beforeRemote('**', function(ctx, unused, next) {

        if (ctx.methodString.includes("find") || ctx.methodString == 'exists' || ctx.methodString == "count") {
          // Change context here.
       //   if (altds.length == 0) {
            var callContext = loopback.getCurrentContext().get('callContext');
            callContext.ctx.remote = "ex";
       //   }
          //node.callContext.ctx.remote = "ex";
        } else {
          //console.log('ds-switcher Skipping Method called ', ctx.methodString);
        }

        next();
      });
    } else {
github craigcabrey / ratemycoop / common / models / review.js View on Github external
Review.observe('before save', function(ctx, next) {
    var loopback = require('loopback');
    var newctx = loopback.getCurrentContext();
    // Force userId to be that of the logged in user
    if(newctx !== null){
      var currentUser = newctx && newctx.get('currentUser');
      if(currentUser !== undefined){
        ctx.instance.userId = currentUser.id;

        // Check that user has not submitted a review the the past 3 months
        ONE_MONTH = 30 * 24 * 60 * 60 * 1000;  // Month in milliseconds
        Review.findOne(
          {
            where: {
              userId: currentUser.id,
              companyId: ctx.instance.companyId,
              created: {
                gt: Date.now() - (ONE_MONTH * 3)
              }
github ShoppinPal / StockUp / common / mixins / utils.js View on Github external
Model.getCurrentUserModel = function(cb) {
    var ctx = loopback.getCurrentContext();
    var currentUser = ctx && ctx.get('currentUser');
    if (currentUser) {
      //log.trace('inside ' + Model.definition.name + '.getCurrentUserModel() - currentUser: ', currentUser.username);
      logger.trace({log: {message: `inside ${Model.definition.name}.getCurrentUserModel() - currentUser: ${currentUser.username}` }});
      //return currentUser;
      return Promise.promisifyAll(
        currentUser,
        {
          filter: function(name, func, target){
            return !( name == 'validate');
          }
        }
      );
    }
    else {
      // TODO: when used with core invocations, the call stack can end up here
github topcoderinc / TopBlogger-Loopback / common / models / blog.js View on Github external
Blog.upvote = function(id, cb) {
    // get the current context
    var ctx = loopback.getCurrentContext();
    Blog.findById(id, function(err, record){
      // get the calling user who 'upvoted' it from the context
      record.upvotes.push(ctx.active.accessToken.userId);
      record.updateAttributes({numOfUpVotes: record.upvotes.length, upvotes: record.upvotes}, function(err, instance) {
        if (err) cb(err);
        if (!err) cb(null, instance);
      })
    })
  };
  // UPVOTE
github ShoppinPal / StockUp / common / lib / debug-extension.js View on Github external
var logger;
    if (scope) {
      logger = require('debug')(scope);
      if (_.isObject(params[0])) {
        params[0].scope = scope; // TODO: when can this ever happen?
      } else {
        // convert to array
        params = Array.prototype.slice.call(arguments);

        var prefix = '';
        if (level) {
          prefix += level.toUpperCase();
        }

        var loopbackContext = loopback.getCurrentContext();
        if (loopbackContext) {
          // prep the all important identifier for wading through logs
          var identifier = loopbackContext.get('ip');
          if (loopbackContext.get('username')){
            identifier += '-' + loopbackContext.get('username');
          }
          else {
            identifier += '-X';
          }
          if (loopbackContext.get('accessToken')){
            // don't want prefixes to be too long, want logs to be human-readable
            identifier += '-' + loopbackContext.get('accessToken').slice(-6);
          }
          else {
            identifier += '-X';
          }
github topcoderinc / TopBlogger-Loopback / common / models / comment.js View on Github external
Comment.dislike = function(id, cb) {
    // get the current context
    var ctx = loopback.getCurrentContext();
    Comment.findById(id, function(err, record){
      // get the calling user who 'disliked' it from the context
      record.dislikes.push(ctx.active.accessToken.userId);
      record.updateAttributes({numOfDislikes: record.dislikes.length, likes: record.dislikes}, function(err, instance) {
        if (err) cb(err);
        if (!err) cb(null, instance);
      })
    })
  };
  // DISLIKE
github EdgeVerve / oe-cloud / server / middleware / context-populator-filter.js View on Github external
return function populateContext(req, res, next) {
    if (req.callContext) {
      var loopbackContext = loopback.getCurrentContext();
      if (loopbackContext) {
        loopbackContext.set('callContext', req.callContext);
        log.debug(req.callContext, 'context set = ', req.callContext);
      } else {
        throw (new Error('call context is null'));
      }
    }
    next();
  };
};
github aquid / Loopback-Messaging-App / server / server.js View on Github external
app.models.Messenger.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.'));
    }
    var loopbackContext = loopback.getCurrentContext();
    var loopbackServerUrl = 'http://message-app.mybluemix.net';
    if (loopbackContext) {
      loopbackContext.set('currentUser', user);
    }
    if(loopbackServerUrl) {
      loopbackContext.set('loopbackServerUrl', loopbackServerUrl);
    }
    next();
  });
});
github aquid / Loopback-Messaging-App / common / models / message.js View on Github external
Message.sendMessage = function(arg,callback){
			/*
				Return a error if reciver , sender or text is not found;
			*/
			if(!arg.text || !arg.senderId || !arg.recieverId){
				return callback('Params not present');
			}
			/*
				Get the current context and add loopbackAccessToken , loopbackServerUrl
				to the arguments sent to iron worker.
			*/
			var ctx = loopback.getCurrentContext();
			arg.loopbackAccessToken = ctx.get('accessToken');
			arg.loopbackServerUrl = ctx.get('loopbackServerUrl');
			/*
				Queue a task to worker usign the iron worker client library.
			*/
			worker.tasksCreate('aquid/translate', arg, {}, function(error) {
				if(error){
					callback(error);
				}
				/*
					Send a processing notification to the user.
				*/
				callback(null,'Message sent for processing....');
			});
		};
github craigcabrey / ratemycoop / server / middleware / userVerified.js View on Github external
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();
    });
  }