/*
Initializes a new instance of the @see AuthMethods class.
@param {Object} models A collection of models to be used within the auth framework.
420079
function OauthAuthMethods(models) {
      this.models = models;
      this.exchangeRefreshTokenForAccessToken = bind(this.exchangeRefreshTokenForAccessToken, this);
      this.exchangeAuthorizationCodeForAccessToken = bind(this.exchangeAuthorizationCodeForAccessToken, this);
      this.createTokenForUserId = bind(this.createTokenForUserId, this);
      this.createOrReuseTokenForUserId = bind(this.createOrReuseTokenForUserId, this);
      this.createAccessGrant = bind(this.createAccessGrant, this);
      this.validate = bind(this.validate, this);
      this.appForClientId = bind(this.appForClientId, this);
      this.currentDateAndSeconds = bind(this.currentDateAndSeconds, this);
      Hoek.assert(this.models, i18n.assertModelsRequired);
      Hoek.assert(this.models.OauthApp, i18n.assertOauthAppInModels);
      Hoek.assert(this.models.OauthAccessToken, i18n.assertOauthAccessTokenInModels);
      Hoek.assert(this.models.OauthAccessGrant, i18n.assertOauthAccessGrantInModels);
    }
1058586
function setDefaultMethods(modelObj) {
    /* This will attach the .data(key, _val) method, that works as a virtual getter/setter.*/
    const dataKey = Symbol("data");
    modelObj.method(function data(key, _val) {
      if (typeof this[dataKey] === 'undefined') this[dataKey] = {};
      if (typeof key !== 'string' || !key) return null;
      if (typeof _val === 'undefined') return (typeof this[dataKey][key] === 'undefined' ? null : this[dataKey][key]);
      this[dataKey][key] = _val;
      return this;
    });
  }
1054534
function initModelValidate (args) {
    var controller = this
    var model = this.model
    // if model does not have schema do not add validate controller
    if (!model.schemaData) {
        return
    }
    // get accountId column
    var accountIdColumn = model.columnName('accountId') 
    // set role to authenticated if model requires account id
    var role = args.defaultRole || (accountIdColumn && model.columns[accountIdColumn].null === false ? 'authenticated' : 'all')
    // index inputs
    var input = {
        // validate schema data
        meta: 'query.meta',
    }
    // instance data is in body under model name
    input[model.name] = 'body.'+model.name
    // create path if it does not exist
    if (!this.paths['/validate']) {
        this.paths['/validate'] = {}
    }
    // add POST /validate handler
    this.paths['/validate'].post = [
        {
            before: function (args) {
                // do validation
                return beforeValidate(controller, args)
            },
            input: input,
            method: function (args) {
                // if before didnt have errors data is valid
                return {valid: true}
            },
            role: role,
            methodName: 'validate',
        },
    ]
}
449597
function Schema(model) {
        var _this = this;
        /**
         * List of generated schemas.
         */
        this.schemas = {};
        this.model = model;
        var models = model.database().models();
        Object.keys(models).forEach(function (name) { _this.one(models[name]); });
    }
207710
function refreshModel(o) {
  if (!(o instanceof Model)) {throw new TypeError('Model expected')}
  _.forEach(o.elements(), refreshElement)
}
200294
function (args) {
    Model.call(this, args);
    this.modelType = messageContents.modelType;
    this.attributes = [];
    for (var a in messageContents.attributes) {
      var attrib = new Attribute(messageContents.attributes[a].name, messageContents.attributes[a].type);
      if (attrib.name == 'id') { // TODO only If mongo! or refactor mongo to normalize IDs
        attrib.value = messageContents.attributes[a].value;
      } else {
        attrib.value = messageContents.attributes[a].value;
      }
      this.attributes.push(attrib);
    }
  }
499010
function init(entry) {  // {{{2
/**
 * Class constructor
 *
 * @param entry {Object} Entry instance
 *
 * @method constructor
 */

//  console.log('ENTRY SLAVE CONSTRUCTOR', entry.id);

  this.entry = entry;

  if (entry.slaves) {
    this.slaveId = ++entry.slaveId;
  } else {
    entry.slaves = {};
    this.slaveId = entry.slaveId = 1;
  }

  entry.slaves[this.slaveId] = this;
}
174481
function ModelIndices(model) {
    // For now the only indices we construct are for flowEvents
    this.flowEventsById_ = {};
    model.flowEvents.forEach(function(fe) {
      if (fe.id !== undefined) {
        if (!this.flowEventsById_.hasOwnProperty(fe.id)) {
          this.flowEventsById_[fe.id] = new Array();
        }
        this.flowEventsById_[fe.id].push(fe);
      }
    }, this);
  }
9030
function(model)
  {
    var exists = this.has( model.$key() );
    var matches = this.filter( model );

    if ( exists && !matches )
    {
      this.remove( model );
    }
    if ( !exists && matches )
    {
      this.add( model );
    }
  }
937931
function initModelCreate (args) {
    var controller = this
    var model = this.model
    // get accountId column
    var accountIdColumn = model.columnName('accountId')
    // set role to authenticated if model requires account id
    var role = args.defaultRole || (accountIdColumn && model.columns[accountIdColumn].null === false ? 'authenticated' : 'all')
    // get relations to create from args if any
    var relations = args.create && args.create.relations
    // validate relations
    _.each(relations, (createArgs, relation) => {
        // this will throw error on invalid relation
        model.relation(relation)
    })
    // index inputs
    var input = {
        // whether or not create data includes meta columns
        meta: 'query.meta',
        // url to redirect to on success
        redirect: ['body.redirect', 'query.redirect'],
    }
    // instance data is in body under model name
    input[model.name] = 'body.'+model.name
    // create path if it does not exist
    if (!this.paths['/']) {
        this.paths['/'] = {}
    }
    // controller spec
    var node = {
        input: input,
        method: function (args) {
            return create(controller, args, node, relations)
        },
        methodName: 'create',
        role: role,
        template: 'instance',
    }
    // add handler for POST / to create instance
    this.paths['/'].post = [node]
}
63604
function initModelUpdate (args) {
    var controller = this
    var model = this.model
    // if model does not have id column then cannot use default controller
    if (!model.columnName('id') || !model.columnName('parentId')) {
        return
    }
    // get accountId column
    var accountIdColumn = model.columnName('accountId') 
    // set role to authenticated if model requires account id
    var role = args.defaultRole || (accountIdColumn && model.columns[accountIdColumn].null === false ? 'authenticated' : 'all')
    // index inputs
    var input = {
        // get current revision of instance
        current: 'query.current',
        // get record even if deleted
        deleted: 'query.deleted',
        // ignore conflicts
        force: 'query.force',
        // instance id
        id: 'params.id',
        // merge update data into existing data
        merge: 'query.merge',
        // input data includes meta columns
        meta: 'query.meta',
    }
    // instance data is in body under model name
    input[model.name] = 'body.'+model.name
    // create path for PUT for API requests
    if (!this.paths['/:id']) {
        this.paths['/:id'] = {}
    }
    // create path for POST for form requests
    if (!this.paths['/:id/update']) {
        this.paths['/:id/update'] = {}
    }
    // add handler for PUT /:id and POST /:id/update
    // to update instance
    this.paths['/:id'].put = this.paths['/:id/update'].post = [
        {
            before: function (args) {
                // load model
                return loadRecordForUpdate(controller, args)
            },

            input: input,
            method: function (args) {
                // perform update
                return update(controller, args)
            },
            methodName: 'update',
            role: role,
            template: 'instance',
        },
    ]
}
310035
public <T extends Model>  void addModels(List<T> models){
        for (T model : models) {
            add(model);
        }
    }
1026762
func InitModels() {
	index := mgo.Index{
		Key:    []string{"authorizationcode"},
		Unique: true,
	} //Do not drop duplicates since it would hijack another authorizationrequest, better to error out

	db.EnsureIndex(requestsCollectionName, index)

	//TODO: unique username/clientid combination

	automaticExpiration := mgo.Index{
		Key:         []string{"createdat"},
		ExpireAfter: time.Second * 10,
		Background:  true,
	}
	db.EnsureIndex(requestsCollectionName, automaticExpiration)

	index = mgo.Index{
		Key:    []string{"accesstoken"},
		Unique: true,
	} //Do not drop duplicates since it would hijack another authorizationrequest, better to error out

	db.EnsureIndex(tokensCollectionName, index)

	//TODO: unique username/clientid combination

	automaticExpiration = mgo.Index{
		Key:         []string{"createdat"},
		ExpireAfter: AccessTokenExpiration,
		Background:  true,
	}
	db.EnsureIndex(tokensCollectionName, automaticExpiration)

	index = mgo.Index{
		Key:    []string{"clientid", "label"},
		Unique: true,
	}
	db.EnsureIndex(clientsCollectionName, index)

	index = mgo.Index{
		Key:    []string{"refreshtoken"},
		Unique: true,
	} //Do not drop duplicates since it would hijack another refreshtoken, better to error out

	db.EnsureIndex(refreshTokenCollectionName, index)
	automaticExpiration = mgo.Index{
		Key:         []string{"lastused"},
		ExpireAfter: time.Second * 86400 * 30,
		Background:  true,
	}
	db.EnsureIndex(refreshTokenCollectionName, automaticExpiration)

}
16083
function(model_s, create, options){
      var toAdd = model_s instanceof Array ? model_s : [model_s],
          self = this;

      ko.utils.arrayForEach(toAdd, function(attributes){
        var model;
        if(attributes instanceof Model){
          model = attributes;
          model.collection = self;
        }else{
          model = new self.model(attributes, {collection: self});
        }
        self.models.push(model);
        if(create) model.save(options);
      });
    }
807176
function init(names) {  // {{{2
/**
 * Class constructor
 *
 * @method constructor
 */

  this.count = 0;
  this.deps = {};
  this.groups = {};
  this.cb = null;

  if (! names) return;

  this.add(names[0], function(cb) { cb() });
  for (var i = 1; i < names.length; i++) {
    this.add(names[i], names[i-1], function(cb) { cb() });
  }

  return;
}
970016
function initModels(seqObj, modelFiles, models, tablePrefix) {
    modelFiles.forEach((item) => {
      var modelFn;
      try {
        modelFn = require(item.fullPath);
      } catch (e) {
        console.error('Thorin.sql: could not require model: ' + item.fullPath + '\n', e.stack);
        return;
      }
      if (modelFn == null) return;  // we skip it
      if (typeof modelFn !== 'function') {
        console.error(thorin.error('SQL.INVALID_MODEL', 'SQL Model: ' + item.fullPath + ' must export a function(modelObj){}'));
        return;
      }
      if (modelFn.name === 'extend') {
        if (typeof extendModels[item.code] === 'undefined') extendModels[item.code] = [];
        extendModels[item.code].push(modelFn);
        return;
      }
      let modelObj = loader.buildModel(seqObj, modelFn, item, tablePrefix);
      if (modelObj) {
        if (typeof models[modelObj.code] !== 'undefined') {
          console.error(thorin.error('SQL.ADD_MODEL', 'SQL Store: model ' + modelObj.code + ' was already declared.'));
          return;
        }
        models[modelObj.code] = modelObj;
      }
    });
  }
607682
function(models){
        var currentLen = this.length;

        // Cloning after converting to an Array because it should be dereferenced
        // in order to continue the while loop when erasing from this._models
        models = Array.from(models).slice();

        this.act(function(){
            var l = models.length,
                i = 0;

            while(l--){
                this._remove(models[i++]);
            }
        });

        // Signal change when the collection of models change
        if (!this.isActive() && this._changed) {
             this.signalChange();

             this.resetChange();
        }

        return this;
    }