Example #1
0
Storage.prototype.defaults = function (defaults) {
  assert(_.isObject(defaults), 'Storage `defaults` method only accept objects');
  var val = _.defaults(this.getAll(), defaults);
  this.set(val);
  return val;
};
Example #2
0
 if (Array.isArray(criteria) && _.all(criteria, function(crit) {return _.isObject(crit);})) {
Example #3
0
 .map(function(value, key) {
     if (value === null || value === undefined) return null;
     return [key, _.isObject(value)? JSON.stringify(value) : value.toString()]
 })
Example #4
0
keystone.Email.prototype.send = function (options, callback) {

	// create transport once
	if (!transport) {
		transport = nodemailer.createTransport(keystone.get('email nodemailer'));
	}

	var locals = options;

	var prepareOptions = [locals];

	if (arguments.length === 3 ) {
		// we expect locals, options, callback
		if (_.isObject(arguments[1])) {
			prepareOptions.push(arguments[1]);
		}
		callback = arguments[2];

	} else if (arguments.length === 2 && !_.isFunction(callback)) {
		// no callback so we expect locals, options
		if (_.isObject(arguments[1])) {
			prepareOptions.push(arguments[1]);
		}
		callback = function(err, info) {// eslint-disable-line no-unused-vars
			if (err) console.log(err);
		};

	} else if (arguments.length === 1) {
		// we expect options here and it is pushed already
		callback = function(err, info){// eslint-disable-line no-unused-vars
			if (err) console.log(err);
		};
	}

	prepareOptions.push(function(err, toSend) {

		if (err) {
			return callback(err, null);
		}

		return process.nextTick(function() {
			var message = toSend.message;

			var attachments = [];
			async.each(message.attachments,(el, callback)=>{
				console.log(el);
				attachments.push({
					cid: attachment.cid,
					filename: attachment.name,
					content: attachment.content,
					contentType: attachment.type,
					encoding: 'base64'
				});
				callback();
			}, ()=> {
				console.log(attachments);
				var mail = {
					from: buildAddress(message.from_email, message.from_name),
					to: message.to.map(function (to) {
						return buildAddress(to.email, to.name)
					}).join(', '),
					subject: message.subject,
					html: message.html,
					attachments: attachments
				};

				if (options.sendPlainText) {
					if (typeof options.sendPlainText === 'object') {
						mail.text = htmlToText.fromString(message.html, options.sendPlainText);
					} else {
						mail.text = htmlToText.fromString(message.html);
					}
				}

				transport.sendMail(mail, function(error, info) {
					if (error) {
						callback({
							from: 'Email.send',
							key: 'send error',
							message: 'Nodemailer encountered an error and did not send the emails.',
							info: info
						});
					} else {
						callback(null, info);
					}
				});
			});


		});

	}.bind(this));

	this.prepare.apply(this, prepareOptions);

};
Example #5
0
  process.nextTick(function() {

    //Allow overloaded params, and hide accessToken.
    if (_.isObject(accessToken)) {
      //Leave accessToken property out of the core
      _.extend(core, _.omit(accessToken, 'accessToken'));
      accessToken = accessToken.accessToken;
    } else {
      core.id = deviceId;
    }

    var coreOptions = {
      accessToken: accessToken,
      path: '/' + core.id
    };

    //Https request for spark information.
    makeReq(coreOptions, function(err, data) {
      if(err) {
        return emitter.emit('error', err);
      }

      //Add information from API to core.
      _.extend(core, data);

      //Dynamically add variables as a function on the core class.
      _.each(data.variables, function(type, variable) {

        var _updateInterval = 0;
        var cancelUpdate;

        var emitterForVariable = new events.EventEmitter();

        //Add each core variable.
        core[variable] = function(callback) {

          //Request options.
          var opts = {
            accessToken: accessToken,
            path: '/' + core.id + '/' + variable
          };


          makeReq(opts, function(err, data) {
            if(err) {
              return callback(err);
            }

            core.last_app = data.coreInfo.last_app;
            core.last_heard = new Date(data.coreInfo.last_heard);
            core.connected = data.coreInfo.connected;

            //Try to handle temporary spark buffer bug. 
            //https://community.sparkdevices.com/t/example-response-for-spark-variable/827
            if(_.isArray(data.result)) {
              data.result = new Buffer(data.result).toString();
            }

            if(callback) {
              if(data.result) {
                core[variable].value = data.result;
                callback(null, data.result);
              } else {
                //Handle undefined responses nicely.
                callback('No data returned by the API.');
              }
            }

            if(_updateInterval) {
              scheduleUpdate();
            }
          });
        };

        //Set event handler.
        core[variable].on = function(event, handler) {
          emitterForVariable.on(event, handler);
        };



        //Schedule an update
        function scheduleUpdate() {
          if(!_updateInterval) {
            throw 'Update interval was unset.';
          }

          if(cancelUpdate) {
            clearTimeout(cancelUpdate);
          }

          cancelUpdate = setTimeout(function() {
            core[variable]( function(err, value) {
              if(err) {
                emitterForVariable.emit('error', err);
                return emitter.emit('error', err);
              }

              emitterForVariable.emit('update', err, value);
              core.variables[variable] = value;
            });
          }, _updateInterval);
        }

        Object.defineProperty(core[variable], 'autoupdate', {
          get: function() {
            return _updateInterval;
          },
          set: function(newVal) {
            if(_.isNumber(newVal)) {
              _updateInterval = Number(newVal);
              scheduleUpdate();
            } else if (newVal === true) {
              //Default update interval
              _updateInterval = 1000 * 5;
              scheduleUpdate();
            } else if (newVal === false) {
              _updateInterval = false;
              clearTimeout(cancelUpdate);
            } else {
              throw 'variable.autoupdate must be a number or true or false.';
            }

            return _updateInterval;
          }
        });

        cache.add(core);
        cache.write();
      });

      //Dynamically add functions as, uh, functions... on the core class.
      _.each(data.functions, function(func) {
        core[func] = function(param, callback) {
          param = param || '';

          var opts = {
            accessToken: accessToken,
            path: '/' + core.id + '/' + func,
            method: 'POST',
            data: {
              args: param
            }
          };

          makeReq(opts, function(err, data) {
            if(err) {
              return emitter.emit('error', err);
            }

            if(callback) {
              //Handle undefined responses nicely.
              if(data) {
                callback(null, data.return_value);
              } else {
                callback('Undefined was returned. Is you core powered on?');
              }
            }
          });
        };
      });

      //Let everything know you're done loading.
      emitter.emit('connect', core);
    });
  });
Example #6
0
 vis.handler.charts.forEach(function (chart) {
   expect(_.isObject(chart.addPath(width, height, svg, slices))).to.be(true);
 });
	criteria: function normalizeCriteria(origCriteria) {
		var criteria = _.clone(origCriteria);

		if(!criteria) return {
			where: null
		};

		// Empty undefined values from criteria object
		_.each(criteria, function(val, key) {
			if(_.isUndefined(val)) delete criteria[key];
		});

		// Convert non-objects (ids) into a criteria
		// TODO: use customizable primary key attribute
		if(!_.isObject(criteria)) {
			criteria = {
				id: +criteria || criteria
			};
		}

		// Return string to indicate an error
		if(!_.isObject(criteria)) throw new Error('Invalid options/criteria :: ' + criteria);

		// If criteria doesn't seem to contain operational keys, assume all the keys are criteria
		if(!criteria.where && !criteria.limit && !criteria.skip && !criteria.sort) {

			// Delete any residuals and then use the remaining keys as attributes in a criteria query
			delete criteria.where;
			delete criteria.limit;
			delete criteria.skip;
			delete criteria.skip;
			criteria = {
				where: criteria
			};
		}
		// If where is null, turn it into an object
		else if(_.isNull(criteria.where)) criteria.where = {};

		// If WHERE is {}, always change it back to null
		if(criteria.where && _.keys(criteria.where).length === 0) {
			criteria.where = null;
		}

		// If a LIKE was specified, normalize it
		if(criteria.where && criteria.where.like) {
			_.each(criteria.where.like, function(criterion, attrName) {
				criteria.where.like[attrName] = normalizePercentSigns(criterion);
			});
		}

		// Normalize sort criteria
		if(criteria.sort) {
			// Split string into attr and sortDirection parts (default to 'asc')
			if(_.isString(criteria.sort)) {
				var parts = _.str.words(criteria.sort);
				parts[1] = parts[1] ? parts[1].toLowerCase() : 'asc';
				if(parts.length !== 2 || (parts[1] !== 'asc' && parts[1] !== 'desc')) {
					throw new Error('Invalid sort criteria :: ' + criteria.sort);
				}
				criteria.sort = {};
				criteria.sort[parts[0]] = (parts[1] === 'asc') ? 1 : -1;
			}

			// Verify that user either specified a proper object
			// or provided explicit comparator function
			if(!_.isObject(criteria.sort) && !_.isFunction(criteria.sort)) {
				throw new Error('Invalid sort criteria for ' + attrName + ' :: ' + direction);
			}
		}

		return criteria;
	},
Example #8
0
File: model.js Project: jinusask/tc
function _getCache(id) {
  if (_.isObject(id)) {
    id = id._id;
  }
  return CACHE_STORE[id];
}
Example #9
0
Interceptor.prototype.match = function match(options, body, hostNameOnly) {
    if (debug.enabled) {
        debug('match %s, body = %s', stringify(options), stringify(body));
    }

    if (hostNameOnly) {
        return options.hostname === this.scope.urlParts.hostname;
    }

    var method = (options.method || 'GET').toUpperCase()
        , path = options.path
        , matches
        , matchKey
        , proto = options.proto;

    if (this.scope.transformPathFunction) {
        path = this.scope.transformPathFunction(path);
    }
    if (typeof(body) !== 'string') {
        body = body.toString();
    }
    if (this.scope.transformRequestBodyFunction) {
        body = this.scope.transformRequestBodyFunction(body, this._requestBody);
    }

    var checkHeaders = function(header) {
        if (_.isFunction(header.value)) {
            return header.value(options.getHeader(header.name));
        }
        return common.matchStringOrRegexp(options.getHeader(header.name), header.value);
    };

    if (!this.scope.matchHeaders.every(checkHeaders) ||
        !this.interceptorMatchHeaders.every(checkHeaders)) {
        this.scope.logger('headers don\'t match');
        return false;
    }

    var reqHeadersMatch =
        ! this.reqheaders ||
        Object.keys(this.reqheaders).every(this.reqheaderMatches.bind(this, options));

    if (!reqHeadersMatch) {
        return false;
    }

    function reqheaderContains(header) {
        return _.has(options.headers, header);
    }

    var reqContainsBadHeaders =
        this.badheaders &&
        _.some(this.badheaders, reqheaderContains);

    if (reqContainsBadHeaders) {
        return false;
    }

    //  If we have a filtered scope then we use it instead reconstructing
    //  the scope from the request options (proto, host and port) as these
    //  two won't necessarily match and we have to remove the scope that was
    //  matched (vs. that was defined).
    if (this.__nock_filteredScope) {
        matchKey = this.__nock_filteredScope;
    } else {
        matchKey = proto + '://' + options.host;
        if (
            options.port && options.host.indexOf(':') < 0 &&
            (options.port !== 80 || options.proto !== 'http') &&
            (options.port !== 443 || options.proto !== 'https')
        ) {
            matchKey += ":" + options.port;
        }
    }

    // Match query strings when using query()
    var matchQueries = true;
    var queryIndex = -1;
    var queryString;
    var queries;

    if (this.queries && (queryIndex = path.indexOf('?')) !== -1) {
        queryString = path.slice(queryIndex + 1);
        queries = qs.parse(queryString);

        // Only check for query string matches if this.queries is an object
        if (_.isObject(this.queries)) {

            if(_.isFunction(this.queries)){
                matchQueries = this.queries(queries);
            }else {
                // Make sure that you have an equal number of keys. We are
                // looping through the passed query params and not the expected values
                // if the user passes fewer query params than expected but all values
                // match this will throw a false positive. Testing that the length of the
                // passed query params is equal to the length of expected keys will prevent
                // us from doing any value checking BEFORE we know if they have all the proper
                // params
                debug('this.queries: %j', this.queries);
                debug('queries: %j', queries);
                if (_.size(this.queries) !== _.size(queries)) {
                    matchQueries = false;
                } else {
                    var self = this;
                    _.forOwn(queries, function matchOneKeyVal(val, key) {
                        var expVal = self.queries[key];
                        var isMatch = true;
                        if (val === undefined || expVal === undefined) {
                        isMatch = false;
                    } else if (expVal instanceof RegExp) {
                      isMatch = common.matchStringOrRegexp(val, expVal);
                    } else if (_.isArray(expVal) || _.isObject(expVal)) {
                      isMatch = _.isEqual(val, expVal);
                    } else {
                      isMatch = common.matchStringOrRegexp(val, expVal);
                    }
                matchQueries = matchQueries && !!isMatch;
                });
                }
                debug('matchQueries: %j', matchQueries);
            }
        }

        // Remove the query string from the path
        path = path.substr(0, queryIndex);
    }

    if (typeof this.uri === 'function') {
        matches = matchQueries &&
        method.toUpperCase() + ' ' + proto + '://' + options.host === this.baseUri &&
        this.uri.call(this, path);
    } else {
        matches = method === this.method &&
        common.matchStringOrRegexp(matchKey, this.basePath) &&
        common.matchStringOrRegexp(path, this.path) &&
        matchQueries;
    }

    // special logger for query()
    if (queryIndex !== -1) {
        this.scope.logger('matching ' + matchKey + '?' + queryString + ' to ' + this._key +
        ' with query(' + stringify(this.queries) + '): ' + matches);
    } else {
        this.scope.logger('matching ' + matchKey + ' to ' + this._key + ': ' + matches);
    }

    if (matches) {
        matches = (matchBody.call(options, this._requestBody, body));
        if (!matches) {
            this.scope.logger('bodies don\'t match: \n', this._requestBody, '\n', body);
        }
    }

    return matches;
};
  findOrCreateEach: function(attributesToCheck, valuesList, cb, metaContainer) {
    var self = this;
    var connName;
    var adapter;

    // Normalize Arguments
    cb = normalize.callback(cb);

    var isObjectArray = false;

    if (_.isObject(attributesToCheck[0])) {
      if (attributesToCheck.length > 1 &&
        attributesToCheck.length !== valuesList.length) {
        return cb(new Error('findOrCreateEach: The two passed arrays have to be of the same length.'));
      }
      isObjectArray = true;
    }

    // Clone sensitive data
    attributesToCheck = _.clone(attributesToCheck);
    valuesList = _.clone(valuesList);

    var query = this._query || {};
    var connName = this.connection;
    // check default connection
    if (connName === 'default' && query.defaultConnection) {
      connName = query.defaultConnection;
    }
    var connection = this.query.offshore.connections[connName];
    // check connection
    if (!connection) {
      return cb(new Error('No valid connection specified'));
    }
    var adapter = connection._adapter;
    // check transaction
    if (query.transaction && query.transaction[connName]) {
      connName = query.transaction[connName];
    }

    // Custom user adapter behavior
    if (hasOwnProperty(adapter, 'findOrCreateEach')) {
      return adapter.findOrCreateEach(connName, this.collection, valuesList, cb, metaContainer);
    }

    // Build a list of models
    var models = [];
    var i = 0;

    async.eachSeries(valuesList, function(values, cb) {
      if (!_.isObject(values)) return cb(new Error('findOrCreateEach: Unexpected value in valuesList.'));
      // Check that each of the criteria keys match:
      // build a criteria query
      var criteria = {};

      if (isObjectArray) {
        if (_.isObject(attributesToCheck[i])) {
          Object.keys(attributesToCheck[i]).forEach(function(attrName) {
            criteria[attrName] = values[attrName];
          });
          if (attributesToCheck.length > 1) {
            i++;
          }
        } else {
          return cb(new Error('findOrCreateEach: Element ' + i + ' in attributesToCheck is not an object.'));
        }
      } else {
        attributesToCheck.forEach(function(attrName) {
          criteria[attrName] = values[attrName];
        });
      }

      return self.findOrCreate.call(self, criteria, values, function(err, model) {
        if (err) return cb(err);

        // Add model to list
        if (model) models.push(model);

        cb(null, model);
      }, metaContainer);
    }, function(err) {
      if (err) return cb(err);
      cb(null, models);
    });
  }
Example #11
0
    render: function() {

        var baseClassName = 'ltt_c-log',
            classCode = getLogClassCode(this.props.classes),
            signs = this.props.signs;
        var className = baseClassName;
        if (classCode) {
            className += ' ' + inheritClassName(baseClassName, classCode);
        }
        if (signs.indexOf('wake') >=0 ) {
            className += ' ' + inheritClassName(baseClassName, 'wake');
        }
        if (signs.indexOf('sleep') >= 0) {
            className += ' ' + inheritClassName(baseClassName, 'sleep');
        }
        var tags = this.props.tags;
        if (!_.isEmpty(tags)) {
            tags = tags.map(function (tag) {
                return (<Tag>{tag}</Tag>);
            });
        }
        var project = this.props.project;
        if (_.isObject(project)) {
            if (_.isObject(project.version)) {
                var version = (<span className="ltt_c-log-project-version">{project.version}</span>);
            } else {
                version = null;
            }
            project = (
                <span className="ltt_c-log-project">
                    <a href="#">
                        <i className="fa fa-rocket"></i>
                        <span className="ltt_c-log-project-name">{project.name}</span>
                        {version}
                    </a>
                </span>
            );
        } else {
            project = null;
        }
        var task = this.props.task;
        if (_.isObject(task)) {
            task = (
                <span className="ltt_c-log-task"><i className="fa fa-tasks"></i>{task.name}</span>
            );
        } else {
            task = null;
        }
        var progress = this.props.progress;

        if (progress) {
            progress = <Progress max={100} value={progress.subTask || progress.task}/>
        }

        var detail = <div class="ltt_c-log-detail">
            <LogClass value={this.props.classes}/>
            {project}
            {task}
            {tags}
        </div>
        return (
            <div className={className}  style={getLogInlineStyle(this.props)}>
                <span className="ltt_c-log-detailToggler" onClick={this.toggleDetail}>
                    <i className={cx({
                        fa: true,
                        'fa-angle-down': this.state.showDetail,
                        'fa-angle-up': !this.state.showDetail
                    })}></i>
                </span>
                {this.props.showDate ? <Time value={this.props.start} type='date'/> : null}
                {this.props.showTime ? <Time value={this.props.start} type='time'/> : null }
                {this.props.showTime ? <Time value={this.props.end} type='time'/> : null }
                <i className="ltt_c-log-gotoEditor fa fa-external-link" onClick={this.gotoEditor}></i>
                {this.props.showProgress ? progress : null}
                <span className="ltt_c-log-len">{getTimeLength(this.props.len)}</span>
                {this.state.showDetail ? detail : null}
                <Origin value={this.props.content}/>
            </div>
        );

        function inheritClassName (base, prop) {
            return base + '__' + prop;
        }

        function getLogClassCode(classes) {
            if (!_.isEmpty(classes)) {
                return classes[0];
            } else {
                return '';
            }
        }
        function getTimeLength(val) {
            if (val < 60) {
                return val + ' minutes';
            } else {
                return (val / 60).toFixed(1) + ' hours';
            }
        }
    },
Example #12
0
  where: function(column, operator, value) {

    // Support "where true || where false"
    if (column === false || column === true) {
      return this.where(1, '=', column ? 1 : 0)
    }

    // Check if the column is a function, in which case it's
    // a where statement wrapped in parens.
    if (typeof column === 'function') {
      return this.whereWrapped(column);
    }

    // Allow a raw statement to be passed along to the query.
    if (column instanceof Raw && arguments.length === 1) return this.whereRaw(column);

    // Allows `where({id: 2})` syntax.
    if (_.isObject(column) && !(column instanceof Raw)) return this._objectWhere(column);

    // Enable the where('key', value) syntax, only when there
    // are explicitly two arguments passed, so it's not possible to
    // do where('key', '!=') and have that turn into where key != null
    if (arguments.length === 2) {
      value    = operator;
      operator = '=';

      // If the value is null, and it's a two argument query,
      // we assume we're going for a `whereNull`.
      if (value === null) {
        return this.whereNull(column);
      }
    }

    // lower case the operator for comparison purposes
    var checkOperator = ('' + operator).toLowerCase().trim();

    // If there are 3 arguments, check whether 'in' is one of them.
    if (arguments.length === 3) {
      if (checkOperator === 'in' || checkOperator === 'not in') {
        return this._not(checkOperator === 'not in').whereIn(arguments[0], arguments[2]);
      }
      if (checkOperator === 'between' || checkOperator === 'not between') {
        return this._not(checkOperator === 'not between').whereBetween(arguments[0], arguments[2]);
      }
    }

    // If the value is still null, check whether they're meaning
    // where value is null
    if (value === null) {

      // Check for .where(key, 'is', null) or .where(key, 'is not', 'null');
      if (checkOperator === 'is' || checkOperator === 'is not') {
        return this._not(checkOperator === 'is not').whereNull(column);
      }
    }

    // Push onto the where statement stack.
    this._statements.push({
      grouping: 'where',
      type: 'whereBasic',
      column: column,
      operator: operator,
      value: value,
      not: this._not(),
      bool: this._bool()
    });
    return this;
  },
Example #13
0
	var isObject 	= function(val) { return (_.isObject(val) && !_.isArray(val) && !_.isFunction(val)); };
Example #14
0
    value: function _normalizeService(service) {
      var key = this._appName;
      var defaultService = {
        config: {},
        options: {},
        preRoutes: {},
        routes: [],
        directory: { service: 'lib', controllers: '', resolvers: '', views: '', static: '' }
      };

      // -----------------------------------------------
      if (_.isString(service)) {
        key = service;
        service = defaultService;
        //
        service.name = key;
        service.directory.service = key;
      } else if (_.isObject(service)) {
        if (service.hasOwnProperty('name')) {
          key = service.name;
          defaultService.directory.service = service.name;
        } else {
          service.name = key;
        }

        if (service.hasOwnProperty('directory') && _.isString(service.directory)) {
          defaultService.directory.service = service.directory;
          service.directory = defaultService.directory;
        }

        service = _.merge(defaultService, service);
      } else {
        logger.warn('Invalid service type:', service);
      }
      // -----------------------------------------------

      // check if service.directories exists
      // find dir for each type
      _.forEach(service.directory, function (dir, d) {
        // logger.info("d:", d, ", key:", key, ", directory:", service.directory[d], ", directory.service:", service.directory.service);
        service.directory[d] = this._findDir(d, service.directory[d], key, service.directory.service);
        // logger.info("found directory:", service.directory[d]);

        if (!service.directory[d]) {
          logger.info('Could not find ' + d + ' dir in App dir (' + process.cwd() + ')');
          // service.directory[d] = service.name;
          // if not, set to current working dir
          service.directory[d] = process.cwd();
        }
      }.bind(this));

      // ----------------------------------------
      // TODO: load controllers first
      // ----------------------------------------

      // if config does not contain routes
      // try to load a routes file using app name
      if (!service.hasOwnProperty('routes') || !(_.isArray(service.routes) && service.routes.length)) {
        try {
          // use directory as root to look for routes file
          var fileSearchPath = path.resolve(process.cwd(), service.directory.service) + path.sep + '**' + path.sep + service.name + '.routes.js';
          // logger.log("fileSearchPath:", fileSearchPath);
          var globs = glob.sync(fileSearchPath);
          // logger.log("globs list:", globs);

          // remove all node_modules
          globs = util.filterNodeModules(globs);
          // logger.log("globs after filter:", globs);

          if (globs.length === 0) {
            logger.info('Could not find a routes files and service defined (%s)', fileSearchPath);
          }
          // TODO: also check the controllers didn't have routes defined
          else if (globs.length > 1) {
              logger.warn('More than one route file found', globs);
            }

          if (globs.length === 1) {
            var file = path.resolve(globs[0]);
            service.routes = require(file);
          }
        } catch (err) {
          logger.warn('Could not load routes files.', err);
          return;
        }
      }

      // -----------------------------------------------
      if (this._config.services.hasOwnProperty(key)) {
        logger.warn('Service already in services:', key);
      }

      // logger.log("normalize service:", JSON.stringify(service, null, 2));
      this._config.services[key] = service;
    }
Mailer.send = function (options, cb) {
  var dataSource = this.dataSource,
    settings = dataSource && dataSource.settings,
    connector = dataSource.connector,
    deferred = Q.defer(),
    mandrilMessage = {
      message: {}
    };

  if (options.__data) {
    options = _.clone(options.__data);
  }
  else {
    options = _.clone(options);
  }

  var fn = function (err, result) {
    if (err) {
      deferred.reject(err);
    }
    else {
      deferred.resolve(result);
    }
    cb && cb(err, result);
  };

  assert(connector, 'Cannot send mail without a connector!');

  if (connector.mandrill) {

    if (_.isString(options.from)) {
      mandrilMessage.message.from_email = options.from
    }
    else if (_.isObject(options.from)) {
      mandrilMessage.message.from_name = options.from.name;
      mandrilMessage.message.from_email = options.from.email;
    }
    else {
      if (options.from_name) {
        mandrilMessage.message.from_name = options.from_name || undefined;
      }
      if (options.from_email) {
        mandrilMessage.message.from_email = options.from_email || undefined;
      }
    }
    delete options.from;


    if (_.isString(options.to)) {
      mandrilMessage.message.to = options.to.split(',');

      mandrilMessage.message.to.forEach(function (email, index) {
        mandrilMessage.message.to[index] = {email: email};
      });

    }
    else if (_.isObject(options.to)) {
      mandrilMessage.message.to = [options.to];
    }
    else {
      mandrilMessage.message.to = options.to;
    }
    delete options.to;

    if (options.template) {
      assert(options.template.name, 'template name should be defined');

      mandrilMessage.template_name = options.template.name;
      mandrilMessage.template_content = options.template.content || [];
      delete options.template;

      _.extend(mandrilMessage.message, _.extend(options, settings.defaults))
      _.extend(mandrilMessage, {
        async: settings.async || false
      });

      connector.mandrill.messages.sendTemplate(mandrilMessage, function (result) {
        fn(null, result);
      }, function (err) {
        fn(err, null);
      });
    }
    else {
      _.extend(mandrilMessage.message, _.extend(options, settings.defaults))
      _.extend(mandrilMessage, {
        async: settings.async || false
      });

      connector.mandrill.messages.send(mandrilMessage, function (result) {
        fn(null, result);
      }, function (err) {
        fn(err, null);
      });
    }
  } else {
    console.warn('Warning: no connectiom with Mandrill');
    process.nextTick(function () {
      fn(null, options);
    });
  }
  return deferred.promise;
};
Example #16
0
 let drinks = _.flatMap(types, (value, key) => {
   if (_.isObject(value)) {
     return _.valuesIn(value, (value2, key2) => { return value2 })
   }
   return value;
 });
  method = _.findWhere(wlconfig.authMethod, {name: 'waterlock-local-auth'});
}else{
  method = wlconfig.authMethod;
}

/**
 * the entire config
 */
exports.config = wlconfig;

/**
 * the config for this method
 */
exports.authConfig = method;

if(_.isObject(method) &&
  !_.isUndefined(method.passwordReset) &&
  method.passwordReset.tokens){
  var nodemailer = require('nodemailer');
  var mail = method.passwordReset.mail;
  var transport = nodemailer.createTransport(mail.protocol, mail.options);
  exports.transport = transport;
}

/**
 * [actions description]
 * @type {[type]}
 */
exports.actions = require('./controllers');

/**
Example #18
0
            _.each(sails.middleware.controllers, function eachController(controller, controllerId) {
                if (!_.isObject(controller) || _.isArray(controller)) return;

                // Get globalId for use in errors/warnings
                var globalId = sails.controllers[controllerId].globalId;

                // Determine blueprint configuration for this controller
                var config = _.merge({},
                    sails.config.blueprints,
                    controller._config || {});

                // Validate blueprint config for this controller
                if (config.prefix) {
                    if (!_(config.prefix).isString()) {
                        sails.after('lifted', function() {
                            sails.log.blank();
                            sails.log.warn(util.format('Ignoring invalid blueprint prefix configured for controller `%s`.', globalId));
                            sails.log.warn('`prefix` should be a string, e.g. "/api/v1".');
                            STRINGFILE.logMoreInfoLink(STRINGFILE.get('links.docs.config.blueprints'), sails.log.warn);
                        });
                        return;
                    }
                    if (!config.prefix.match(/^\//)) {
                        var originalPrefix = config.prefix;
                        sails.after('lifted', function() {
                            sails.log.blank();
                            sails.log.warn(util.format('Invalid blueprint prefix ("%s") configured for controller `%s` (should start with a `/`).', originalPrefix, globalId));
                            sails.log.warn(util.format('For now, assuming you meant:  "%s".', config.prefix));
                            STRINGFILE.logMoreInfoLink(STRINGFILE.get('links.docs.config.blueprints'), sails.log.warn);
                        });

                        config.prefix = '/' + config.prefix;
                    }
                }

                // Determine the names of the controller's user-defined actions
                // IMPORTANT: Use `sails.controllers` instead of `sails.middleware.controllers`
                // (since `sails.middleware.controllers` will have blueprints already mixed-in,
                // and we want the explicit actions defined in the app)
                var actions = Object.keys(sails.controllers[controllerId]);



        // Determine base route
        var baseRoute = config.prefix + '/' + controllerId;
        if (config.pluralize) {
          baseRoute = pluralize(baseRoute);
        }

        var baseActionRoute = config.actionPrefix + '/' + controllerId;
        if(config.pluralize){
          baseActionRoute = pluralize(baseActionRoute);
        }

        // Build route options for blueprint
        var routeOpts = config;

                // Bind "actions" and "index" shadow routes for each action
                _.each(actions, function eachActionID(actionId) {

                    var opts = _.merge({
                        action: actionId,
                        controller: controllerId
                    }, routeOpts);

          // Bind a route based on the action name, if `actions` shadows enabled
          if (config.actions) {
            var actionRoute = baseActionRoute + '/' + actionId.toLowerCase() + '/:id?';
            sails.log.silly('Binding action ('+actionId.toLowerCase()+') blueprint/shadow route for controller:',controllerId);
            sails.router.bind(actionRoute, controller[actionId.toLowerCase()], null, opts);
          }

          // Bind base route to index action, if `index` shadows are not disabled
          if (config.index !== false && actionId.match(/^index$/i)) {
            sails.log.silly('Binding index blueprint/shadow route for controller:',controllerId);
            sails.router.bind(baseActionRoute, controller.index, null, opts);
          }
        });

                // Determine the model connected to this controller either by:
                // -> explicit configuration
                // -> on the controller
                // -> on the routes config
                // -> or implicitly by globalId
                // -> or implicitly by controller id
                var routeConfig = sails.router.explicitRoutes[controllerId] || {};
                var modelFromGlobalId = sails.util.findWhere(sails.models, {
                    globalId: globalId
                });
                var modelId = config.model || routeConfig.model || (modelFromGlobalId && modelFromGlobalId.identity) || controllerId;

                // If the orm hook is enabled, it has already been loaded by this time,
                // so just double-check to see if the attached model exists in `sails.models`
                // before trying to attach any CRUD blueprint actions to the controller.
                if (sails.hooks.orm && sails.models && sails.models[modelId]) {

                    // If a model with matching identity exists,
                    // extend route options with the id of the model.
                    routeOpts.model = modelId;

                    var Model = sails.models[modelId];

                    // Bind convenience functions for readability below:

                    // Given an action id like "find" or "create", returns the appropriate
                    // blueprint action (or explicit controller action if the controller
                    // overrode the blueprint CRUD action.)
                    var _getAction = _.partial(_getMiddlewareForShadowRoute, controllerId);

                    // Returns a customized version of the route template as a string.
                    var _getRoute = _.partialRight(util.format, baseRoute);


                    // Mix in the known associations for this model to the route options.
                    routeOpts = _.merge({
                        associations: _.cloneDeep(Model.associations)
                    }, routeOpts);

                    // Binds a route to the specifed action using _getAction, and sets the action and controller
                    // options for req.options
                    var _bindRoute = function(path, action, options) {
                        options = options || routeOpts;
                        options = _.extend({}, options, {
                            action: action,
                            controller: controllerId
                        });
                        sails.router.bind(path, _getAction(action), null, options);

                    };

                    // Bind URL-bar "shortcuts"
                    // (NOTE: in a future release, these may be superceded by embedding actions in generated controllers
                    //  and relying on action blueprints instead.)
                    if (config.shortcuts) {
                        sails.log.silly('Binding shortcut blueprint/shadow routes for model ', modelId, ' on controller:', controllerId);

                        _bindRoute(_getRoute('%s/find'), 'find');
                        _bindRoute(_getRoute('%s/find/:id'), 'findOne');
                        _bindRoute(_getRoute('%s/create'), 'create');
                        _bindRoute(_getRoute('%s/update/:id'), 'update');
                        _bindRoute(_getRoute('%s/destroy/:id?'), 'destroy');

            // Bind add/remove "shortcuts" for each `collection` associations
            if(config.restCollections){
              _(Model.associations).where({type: 'collection'}).forEach(function (association) {
                var alias = association.alias;
                var _getAssocRoute = _.partialRight(util.format, baseRoute, alias);
                var opts = _.merge({ alias: alias }, routeOpts);

                sails.log.silly('Binding "shortcuts" to association blueprint `'+alias+'` for',controllerId);
                _bindRoute( _getAssocRoute('%s/:parentid/%s/add/:id?'),      'add' , opts );
                _bindRoute( _getAssocRoute('%s/:parentid/%s/remove/:id?'),   'remove', opts );
              });
            }
          }

                    // Bind "rest" blueprint/shadow routes
                    if (config.rest) {
                        sails.log.silly('Binding RESTful blueprint/shadow routes for model+controller:', controllerId);
                        _bindRoute(_getRoute('get %s'), 'find');
                        _bindRoute(_getRoute('get %s/:id'), 'findOne');
                        _bindRoute(_getRoute('post %s'), 'create');
                        _bindRoute(_getRoute('put %s/:id'), 'update');
                        _bindRoute(_getRoute('post %s/:id'), 'update');
                        _bindRoute(_getRoute('delete %s/:id?'), 'destroy');

            // Bind "rest" blueprint/shadow routes based on known associations in our model's schema
            // Bind add/remove for each `collection` associations
            if(config.restCollections){
              _(Model.associations).where({type: 'collection'}).forEach(function (association) {
                var alias = association.alias;
                var _getAssocRoute = _.partialRight(util.format, baseRoute, alias);
                var opts = _.merge({ alias: alias }, routeOpts);
                sails.log.silly('Binding RESTful association blueprint `'+alias+'` for',controllerId);

                _bindRoute( _getAssocRoute('post %s/:parentid/%s/:id?'),     'add', opts );
                _bindRoute( _getAssocRoute('delete %s/:parentid/%s/:id?'),   'remove', opts );
              });
            }

            // and populate for both `collection` and `model` associations
            if(config.restPopulate){
              _(Model.associations).forEach(function (association) {
                var alias = association.alias;
                var _getAssocRoute = _.partialRight(util.format, baseRoute, alias);
                var opts = _.merge({ alias: alias }, routeOpts);
                sails.log.silly('Binding RESTful association blueprint `'+alias+'` for',controllerId);

                _bindRoute( _getAssocRoute('get %s/:parentid/%s/:id?'), 'populate', opts );
              });
            }
          }
        }
      });
Example #19
0
 return _.reject(types, function (t) {
     return _.isFunction(t) || _.isObject(t) || _.isArray(t);
 });
Example #20
0
       }
   },

    isPromise(value) {
       return (value && _.isFunction(value.then));
   },

    md5(str) {
       return crypto.createHash('md5').update(str).digest('hex');
   },

    mergeProp(prop, upstream) {
        if (_.isFunction(prop)) {
            return prop;
        }
        if (_.isFunction(upstream)) {
            return upstream;
        }
        if (_.isArray(upstream)) {
            return _.uniq(_.concat(upstream, _.castArray(prop)));
        } else if (_.isObject(upstream)) {
            return _.defaultsDeep(_.clone(prop || {}), _.clone(upstream));
        }
        if (_.isUndefined(prop)) {
            return upstream;
        }
        return prop;
   }

};
Example #21
0
  };
}

registerInternalPlugin(`encryption`, Encryption, {
  payloadTransformer: {
    predicates: [{
      name: `encryptKmsMessage`,
      direction: `outbound`,
      // I don't see any practical way to reduce complexity here.
      // eslint-disable-next-line complexity
      test(ctx, options) {
        if (!has(options, `body.kmsMessage`)) {
          return Promise.resolve(false);
        }

        if (!isObject(options.body.kmsMessage)) {
          return Promise.resolve(false);
        }

        // If this is a template for a kms message, assume another transform
        // will fill it in later. This is a bit of a leaky abstraction, but the
        // alternative is building a complex rules engine for controlling
        // ordering of transforms
        if (options.body.kmsMessage.keyUris && options.body.kmsMessage.keyUris.length === 0) {
          return Promise.resolve(false);
        }
        if (options.body.kmsMessage.resourceUri && (options.body.kmsMessage.resourceUri.includes(`<KRO>`) || options.body.kmsMessage.resourceUri.includes(`<KEYURL>`))) {
          return Promise.resolve(false);
        }
        if (options.body.kmsMessage.uri && (options.body.kmsMessage.uri.includes(`<KRO>`) || options.body.kmsMessage.uri.includes(`<KEYURL>`))) {
          return Promise.resolve(false);
Example #22
0
 it('should return an object', function () {
   let rowIn = new Data(rowsData, {}, persistedState);
   expect(_.isObject(rowIn)).to.be(true);
 });
Example #23
0
export function validRocProject(directory) {
    const packageJson = getPackageJson(directory);

    return !(!isObject(packageJson) ||
        !fileExists('roc.config.js', directory) && !getRocDependencies(packageJson).length);
}
Example #24
0
 it('should return an object', function () {
   expect(_.isObject(vislib)).to.be(true);
 });
Example #25
0
function isValue(v) {
  return !_.isObject(v) || v instanceof ObjectId;
}
	var validateConfig = function(config) {
		assert(lodash.isObject(config.eventEmitter), 'eventEmitter is required');
	};
Example #27
0
 parse : function (body) {
     if (_.isObject(body)) return body;
     try { var parsed = JSON.parse(body); } 
     catch (e) { return console.log('failed to parse:', body);}
     return parsed;
 },
Example #28
0
var BelongsToMany = function(source, target, options) {
  Association.call(this);

  options = options || {};

  if (options.through === undefined || options.through === true || options.through === null) {
    throw new Error('belongsToMany must be given a through option, either a string or a model');
  }

  if (!options.through.model) {
    options.through = {
      model: options.through
    };
  }

  this.associationType = 'BelongsToMany';
  this.source = source;
  this.target = target;
  this.targetAssociation = null;
  this.options = options;
  this.sequelize = source.modelManager.sequelize;
  this.through = _.assign({}, options.through);
  this.scope = options.scope;
  this.isMultiAssociation = true;
  this.isSelfAssociation = this.source === this.target;
  this.doubleLinked = false;
  this.as = this.options.as;

  if (!this.as && this.isSelfAssociation) {
    throw new Error('\'as\' must be defined for many-to-many self-associations');
  }

  if (this.as) {
    this.isAliased = true;

    if (Utils._.isPlainObject(this.as)) {
      this.options.name = this.as;
      this.as = this.as.plural;
    } else {
      this.options.name = {
        plural: this.as,
        singular: Utils.singularize(this.as)
      };
    }
  } else {
    this.as = this.target.options.name.plural;
    this.options.name = this.target.options.name;
  }

  this.combinedTableName = Utils.combineTableNames(
    this.source.tableName,
    this.isSelfAssociation ? (this.as || this.target.tableName) : this.target.tableName
  );

  /*
   * If self association, this is the target association - Unless we find a pairing association
   */
  if (this.isSelfAssociation) {
    this.targetAssociation = this;
  }

  /*
   * Default/generated foreign/other keys
   */
  if (_.isObject(this.options.foreignKey)) {
    this.foreignKeyAttribute = this.options.foreignKey;
    this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
  } else {
    if (!this.options.foreignKey) {
      this.foreignKeyDefault = true;
    }

    this.foreignKeyAttribute = {};
    this.foreignKey = this.options.foreignKey || Utils.camelizeIf(
      [
        Utils.underscoredIf(this.source.options.name.singular, this.source.options.underscored),
        this.source.primaryKeyAttribute
      ].join('_'),
      !this.source.options.underscored
    );
  }

  if (_.isObject(this.options.otherKey)) {
    this.otherKeyAttribute = this.options.otherKey;
    this.otherKey = this.otherKeyAttribute.name || this.otherKeyAttribute.fieldName;
  } else {
    if (!this.options.otherKey) {
      this.otherKeyDefault = true;
    }

    this.otherKeyAttribute = {};
    this.otherKey = this.options.otherKey || Utils.camelizeIf(
      [
        Utils.underscoredIf(
          this.isSelfAssociation ?
            Utils.singularize(this.as) :
            this.target.options.name.singular,
          this.target.options.underscored
        ),
        this.target.primaryKeyAttribute
      ].join('_'),
      !this.target.options.underscored
    );
  }

  /*
   * Find paired association (if exists)
   */
  _.each(this.target.associations, function(association) {
    if (association.associationType !== 'BelongsToMany') return;
    if (association.target !== this.source) return;

    if (this.options.through.model === association.options.through.model) {
      this.paired = association;
      association.paired = this;
    }
  }, this);

  if (typeof this.through.model === 'string') {
    if (!this.sequelize.isDefined(this.through.model)) {
      this.through.model = this.sequelize.define(this.through.model, {}, _.extend(this.options, {
        tableName: this.through.model,
        indexes: {}, //we dont want indexes here (as referenced in #2416)
        paranoid: false  // A paranoid join table does not make sense
      }));
    } else {
      this.through.model = this.sequelize.model(this.through.model);
    }
  }

  if (this.paired) {
    if (this.otherKeyDefault) {
      this.otherKey = this.paired.foreignKey;
    }
    if (this.paired.otherKeyDefault) {
      // If paired otherKey was inferred we should make sure to clean it up before adding a new one that matches the foreignKey
      if (this.paired.otherKey !== this.foreignKey) {
        delete this.through.model.rawAttributes[this.paired.otherKey];
      }
      this.paired.otherKey = this.foreignKey;
      this.paired.foreignIdentifier = this.foreignKey;
      delete this.paired.foreignIdentifierField;
    }
  }

  if (this.through) {
    this.throughModel = this.through.model;
  }

  this.options.tableName = this.combinedName = (this.through.model === Object(this.through.model) ? this.through.model.tableName : this.through.model);

  this.associationAccessor = this.as;

  // Get singular and plural names, trying to uppercase the first letter, unless the model forbids it
  var plural = Utils.uppercaseFirst(this.options.name.plural)
    , singular = Utils.uppercaseFirst(this.options.name.singular);

  this.accessors = {
    /**
     * Get everything currently associated with this, using an optional where clause.
     *
     * @param {Object} [options]
     * @param {Object} [options.where] An optional where clause to limit the associated models
     * @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
     * @param {String} [options.schema] Apply a schema on the related model
     * @return {Promise<Array<Instance>>}
     * @method getAssociations
     */
    get: 'get' + plural,
    /**
     * Set the associated models by passing an array of instances or their primary keys. Everything that it not in the passed array will be un-associated.
     *
     * @param {Array<Instance|String|Number>} [newAssociations] An array of instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations.
     * @param {Object} [options] Options passed to `through.findAll`, `bulkCreate`, `update` and `destroy`. Can also hold additional attributes for the join table
     * @param {Object} [options.validate] Run validation for the join model
     * @return {Promise}
     * @method setAssociations
     */
    set: 'set' + plural,
    /**
     * Associate several instances with this.
     *
     * @param {Array<Instance|String|Number>} [newAssociations] An array of instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations.
     * @param {Object} [options] Options passed to `through.findAll`, `bulkCreate`, and `update` `destroy`. Can also hold additional attributes for the join table
     * @param {Object} [options.validate] Run validation for the join model
     * @return {Promise}
     * @method addAssociations
     */
    addMultiple: 'add' + plural,
    /**
     * Associate several instances with this.
     *
     * @param {Instance|String|Number} [newAssociation] An array of instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations.
     * @param {Object} [options] Options passed to `through.findAll`, `bulkCreate` and `update`. Can also hold additional attributes for the join table
     * @param {Object} [options.validate] Run validation for the join model
     * @return {Promise}
     * @method addAssociation
     */
    add: 'add' + singular,
     /**
     * Create a new instance of the associated model and associate it with this.
     *
     * @param {Object} [values]
     * @param {Object} [options] Options passed to create and add. Can also hold additional attributes for the join table
     * @return {Promise}
     * @method createAssociation
     */
    create: 'create' + singular,
    /**
     * Un-associate the instance.
     *
     * @param {Instace|String|Number} [oldAssociated] Can be an Instance or its primary key
     * @param {Object} [options] Options passed to `through.destroy`
     * @return {Promise}
     * @method removeAssociation
     */
    remove: 'remove' + singular,
    /**
     * Un-associate several instances.
     *
     * @param {Array<Instace|String|Number>} [oldAssociated] Can be an array of instances or their primary keys
     * @param {Object} [options] Options passed to `through.destroy`
     * @return {Promise}
     * @method removeAssociations
     */
    removeMultiple: 'remove' + plural,
    /**
     * Check if an instance is associated with this.
     *
     * @param {Instace|String|Number} [instance] Can be an Instance or its primary key
     * @param {Object} [options] Options passed to getAssociations
     * @return {Promise}
     * @method hasAssociation
     */
    hasSingle: 'has' + singular,
    /**
     * Check if all instances are associated with this.
     *
     * @param {Array<Instace|String|Number>} [instances] Can be an array of instances or their primary keys
     * @param {Object} [options] Options passed to getAssociations
     * @return {Promise}
     * @method hasAssociations
     */
    hasAll: 'has' + plural,
    /**
     * Count everything currently associated with this, using an optional where clause.
     *
     * @param {Object} [options]
     * @param {Object} [options.where] An optional where clause to limit the associated models
     * @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
     * @return {Promise<Int>}
     * @method countAssociations
     */
    count: 'count' + plural
  };

  if (this.options.counterCache) {
    new CounterCache(this, this.options.counterCache !== true ? this.options.counterCache : {});
  }
};
Example #29
0
 it('should return an object with series[0].values', function () {
   expect(_.isObject(sample1)).to.be(true);
   expect(_.isObject(sample1.series[0].values)).to.be(true);
 });
Example #30
0
 _.each(pattern, function (v, k) {
   if (_.isObject(v)) {
     pattern_rules[k] = _.clone(v)
     delete pattern[k]
   }
 })