Passport's authenticate middleware for Koa.

@param {String|Array} name
@param {Object} options
@param {GeneratorFunction} callback
@return {GeneratorFunction}
@api private
767727
function authenticate(passport, name, options, callback) {
  // normalize arguments
  if (typeof options === 'function') {
    callback = options
    options  = {}
  }
  options = options || {}

  if (callback) {
    // When the callback is set, neither `next`, `res.redirect` or `res.end`
    // are called. That is, a workaround to catch the `callback` is required.
    // The `passportAuthenticate()` method below will therefore set
    // `callback.resolve` and `callback.reject`. Then, once the authentication
    // finishes, the modified callback calls the original one and afterwards
    // triggers either `callback.resolve` or `callback.reject` to inform
    // `passportAuthenticate()` that we are ready.
    const _callback = callback
    callback = function(err, user, info, status) {
      try {
        Promise.resolve(_callback(err, user, info, status))
               .then(() => callback.resolve(false))
               .catch(err => callback.reject(err))
      } catch (err) {
        callback.reject(err)
      }
    }
  }

  const middleware = promisify(_authenticate(passport, name, options, callback))

  return function passportAuthenticate(ctx, next) {
    // this functions wraps the connect middleware
    // to catch `next`, `res.redirect` and `res.end` calls
    const p = new Promise((resolve, reject) => {
      // mock the `req` object
      const req = createReqMock(ctx, options.assignProperty || passport._userProperty || 'user')

      function setBodyAndResolve(content) {
        if (content) ctx.body = content
        resolve(false)
      }

      // mock the `res` object
      const res = {
        redirect: function(url) {
          ctx.redirect(url)
          resolve(false)
        },
        set: ctx.set.bind(ctx),
        setHeader: ctx.set.bind(ctx),
        end: setBodyAndResolve,
        send: setBodyAndResolve,
        set statusCode(status) {
          ctx.status = status
        },
        get statusCode() {
          return ctx.status
        }
      }

      req.res = res

      // update the custom callback above
      if (callback) {
        callback.resolve = resolve
        callback.reject  = reject
      }

      // call the connect middleware
      middleware(req, res).then(resolve, reject)
    })

    return p.then(cont => {
      // cont equals `false` when `res.redirect` or `res.end` got called
      // in this case, call next to continue through Koa's middleware stack
      if (cont !== false) {
        return next()
      }
    })
  }
}
59047
function Connection(options) {
	
	if (!(this instanceof Connection)){
		return new Connection(options);
	}
	
	
	this.prefixCounter = 0;
	this.serverMessages = {};
	this._options = {
		username: options.username || options.user || '',
		password: options.password || '',
		host: options.host || 'localhost',
		port: options.port || 143,
		secure: options.secure === true ? { // secure = true means default behavior
			rejectUnauthorized: false // Force pre-node-0.9.2 behavior
		} : (options.secure || false),
		timeout: options.timeout || 10000, // connection timeout in msecs
		xoauth: options.xoauth,
		xoauth2: options.xoauth2
	};
	
	this._messages = {};
	this._messages = {};
	
	if (options.debug===true){
		this.debug = function(msg){
			console.log(msg);
		}
	}
	
		
	if (options.chainDebug===true){
		this.chainDebug = function(msg){
			console.log(msg);
		}
	}
	
	this.socket = null;
	
	this._messages_prefix_key={};
	this._messages_key_prefix={};
	this._messages={};
	
	
	this._msg_buffer = '';
	this._resetChainCommands();
}
830170
function middleware(schema, options = optionsDefault) {
    return (req, res, next) => {
        // Test if schema exists
        /* istanbul ignore if */
        if (!schema) {
            next();
        }

        // Test if Joi is provided
        const Joi = options.joi || require('joi');

        // Object to validate
        const objectToValidate = {};
        ['params', 'body', 'query', 'headers'].forEach((key) => {
            if (schema[key]) {
                objectToValidate[key] = req[key];
            }
        });

        // Get joi options
        const joiOptions = options.joiOptions || {};

        // Get callback
        const callback = options.validationCallback || validationCallback;

        return Joi.validate(objectToValidate, schema, joiOptions, callback(req, res, next, options));
    };
}
1164396
function setting(options) {
  var conf = {};

  if (options === null || typeof options !== 'object') {
    options = {};
  }

  for (var key in defaultSetting) {
    conf[key] = options[key] === undefined ? defaultSetting[key] : options[key];
  }

  conf.format = defaultFormat(['json', 'xml'].indexOf(conf.format.toLowerCase()));

  var prefix = conf.prefix;
  if ((typeof prefix === 'string' || util.isRegExp(prefix)) && !options.prefixPattern) {
    conf.prefixPattern = util.isRegExp(prefix) ? prefix : new RegExp(prefix);
  }

  if (conf.authenticate) {
    conf.deny = options.deny;
    conf.authenticatePattern = options.authenticatePattern || conf.prefixPattern;

    if (conf.authenticate.constructor.name !== 'GeneratorFunction') {
      console.error('authenticate should be a GeneratorFunction');
      conf.authenticate = false;
    }
    if (conf.deny.constructor.name !== 'GeneratorFunction') {
      console.error('deny should be a GeneratorFunction');
    }
  }

  return conf;
}
974164
function (req, res, passport, cb) {
        let authentication = req.soajs.inputmaskData.strategy;

        passportLib.getDriver(req, false, function (err, passportDriver) {
            passportDriver.preAuthenticate(req, function () {
                passport.authenticate(authentication, {session: false}, function (err, user) {
                    if (err) {
                        req.soajs.log.error(err);
                        return cb({"code": 499, "msg": err.toString()});
                    }
                    if (!user) {
                        cb({"code": 403, "msg": req.soajs.config.errors[403]});
                    }

                    req.soajs.inputmaskData.user = user;
                    initBLModel(req.soajs, function (err) {
                        if (err) {
                            return cb(err);
                        }
                        let mode = req.soajs.inputmaskData.strategy;
                        utilities.saveUser(req.soajs, driver.model, mode, user, function (error, data) {
                            cb(error, data);
                        });
                    });
                })(req, res);

            });
        });

    }
1215480
function(name,options) {
    var cls = new Class(name,options);
    var custom = new Class("CustomError",{
      inherits: Error,
      constructor: function(message) {
        this.name = name;
        this.message = message;
      },
    })
    cls.inherit(custom);
    return cls.toFunction();
  }
1115215
function Session(identity, connection, options) {
  if (!(this instanceof Session)) {
    return new Session(identity, connection, options);
  }

  assert(identity instanceof Identity, 'Invalid identity supplied');

  if (!(connection instanceof Connection)) {
    options = connection || {};
    options.passive = true;
  }

  this.options = merge(Object.create(Session.DEFAULTS), options);
  this.client = new Client(identity);
  this._identity = identity;

  if (!this.options.passive) {
    this._connection = connection;
    this._connection.open(this._onConnect.bind(this));
  } else {
    this._onConnect();
  }

  if (this.options.subscribe) {
    this.client.on('message', this._onMessage.bind(this)).subscribe();
  }
}
1358099
function OriginDB(name, options) {
  let objects = {};
  let checksums = {};

  if (!_.isString(name)) {
    throw new Error('Invalid name');
  }

  if (_.isObject(options)) {
    options = Object.assign({}, defaultOptions, options);
  } else {
    options = defaultOptions;
  }

  if (_.isString(options.adapter) && !_.has(adapters, options.adapter)) {
    throw new Error('Unknown adapter');
  }

  const save = _.isFunction(options.adapter) ?
    options.adapter(name, objects, checksums, options) :
    adapters[options.adapter](name, objects, checksums, options);

  /**
   * The database instance.
   *
   * @param {string} objectName
   * @param {Object} methods
   */
  function db(objectName) {
    if (_.isBoolean(save.hasLoaded)) deasync.loopWhile(() => !save.hasLoaded);
    if (!_.has(objects, objectName)) objects[objectName] = {};
    return createMethods(objects[objectName], save.bind(null, objectName));
  }

  // backwards compatability with < v2.4.1
  db.save = () => {
    if (_.isBoolean(save.hasLoaded)) deasync.loopWhile(() => !save.hasLoaded);
    _.forIn(objects, function(value, file) {
      save(file);
    });
  };

  return db;
}
793385
function Strategy(options, verify) {
  if (typeof options == 'function') {
    verify = options;
    options = {};
  }
  if (!verify) throw new Error('OAuth 2.0 client password strategy requires a verify function');

  passport.Strategy.call(this);
  this.name = 'oauth2-client-password';
  this._verify = verify;
  this._passReqToCallback = options.passReqToCallback;
}
213866
function initialize(passport) {
  const middleware = promisify(_initialize(passport))
  return function passportInitialize(ctx, next) {
    // koa <-> connect compatibility:
    const userProperty = passport._userProperty || 'user'
    // check ctx.req has the userProperty
    if (!ctx.req.hasOwnProperty(userProperty)) {
      Object.defineProperty(ctx.req, userProperty, {
        enumerable: true,
        get: function() {
          return ctx.state[userProperty]
        },
        set: function(val) {
          ctx.state[userProperty] = val
        }
      })
    }

    // create mock object for express' req object
    const req = createReqMock(ctx, userProperty)


    // add Promise-based login method
    const login  = req.login
    ctx.login = ctx.logIn = function(user, options) {
      return new Promise((resolve, reject) => {
        login.call(req, user, options, err => {
          if (err) reject(err)
          else resolve()
        })
      })
    }

    // add aliases for passport's request extensions to Koa's context
    ctx.logout = ctx.logOut = req.logout.bind(req)
    ctx.isAuthenticated     = req.isAuthenticated.bind(req)
    ctx.isUnauthenticated   = req.isUnauthenticated.bind(req)

    return middleware(req, ctx).then(function() {
      return next()
    })
  }
}
244336
function(name, callback) {
    if (name in whichCache) {
      return callback(null, whichCache[name]);
    }

    which(name, function(err, result){
      if (err) {
        // Treat errors as not found
        return callback(null, whichCache[name] = '');
      }
      callback(null, whichCache[name] = result);
    });
  }
1009733
function authorizationRequest (req, options) {
  var provider = this.provider
  var endpoints = this.endpoints
  var config = this.client
  var url = URL.parse(endpoints.authorize.url)
  var responseType = 'code'
  var clientId = config.client_id
  var redirectUri = provider.redirect_uri
  var state = options.state

  // required authorization parameters
  url.query = {
    response_type: responseType,
    client_id: clientId,
    redirect_uri: redirectUri
  }

  // merge default and configured scopes
  if (provider.scope || config.scope) {
    var s1 = provider.scope || []
    var s2 = config.scope || []
    var sp = provider.separator || ' '

    url.query.scope = s1.concat(s2).join(sp)
  }

  if (state) {
    url.query.state = state
  }

  // Redirect to the provider. This method is
  // added at runtime by passport and not explicitly
  // defined here.
  this.redirect(URL.format(url))
}
593827
function (options) {
  // Unknown keys allowed, because a onCreateUserHook can take arbitrary
  // options.
  check(options, Match.ObjectIncluding({
    username: Match.Optional(String),
    email: Match.Optional(String),
    password: Match.Optional(String),
    srp: Match.Optional(SRP.matchVerifier)
  }));

  var username = options.username;
  var email = options.email;
  if (!username && !email)
    throw new Meteor.Error(400, "Need to set a username or email");

  // Raw password. The meteor client doesn't send this, but a DDP
  // client that didn't implement SRP could send this. This should
  // only be done over SSL.
  if (options.password) {
    if (options.srp)
      throw new Meteor.Error(400, "Don't pass both password and srp in options");
    options.srp = SRP.generateVerifier(options.password);
  }

  var user = {services: {}};
  if (options.srp)
    user.services.password = {srp: options.srp}; // XXX validate verifier
  if (username)
    user.username = username;
  if (email)
    user.emails = [{address: email, verified: false}];

  return Accounts.insertUserDoc(options, user);
}
840522
function oauth2callback(options) {
  return function(req, res, next) {
    const { service_name, } = options;
    const entitytype = req.session.passport.user.entitytype || 'user';
    const redirectURL = (entitytype === 'account') ? passportExtSettings.redirect.account.logged_in_homepage : passportExtSettings.redirect.user.logged_in_homepage;
    const loginEntityURL = (entitytype === 'account') ? passportLocals.paths.account_auth_login : passportLocals.paths.user_auth_login;
    const loginUrl = (req.session.return_url) ?
      req.session.return_url :
      redirectURL;
    const loginFailureUrl = (req.session.return_url) ?
      req.session.return_url :
      loginEntityURL + '?return_url=' + req.session.return_url;
    // console.log({ loginUrl, loginFailureUrl, redirectURL, loginEntityURL, });
    // console.log({ entitytype, redirectURL, loginEntityURL, loginUrl, loginFailureUrl }, 'req.session', req.session, 'req.user', req.user,'req.headers', req.headers,{service_name});
    passport.authenticate(`oauth2client-${service_name}`, {
      successRedirect: loginUrl,
      failureRedirect: loginFailureUrl,
      failureFlash: `Invalid ${service_name} authentication credentials username or password.`,
    })(req, res, next);
  };
}
1106970
function auth (username, password, callback) {
    return relax({
      method: 'POST',
      db: '_session',
      form: {
        name: username,
        password: password
      }
    }, callback)
  }
149341
function(options) {
      var storedUser = ((!this.isOAuth2Mode() && this.Storage.retrieve(this.loggedInUserKey)) || this.Storage.retrieve('oauth2.user'));
      //The logged in user's ID is saved in local storage until removed, so we need to check to make sure that the user has valid login credentials before returning the login ID.
      if ( options && options['success'] ){
        this.hasValidOAuth(options);
      } else {
        return (this.isLoggedIn(options) && storedUser) ? storedUser : null;
      }
    }
636539
def create_with_role(name, options = {})
      headers = extract_headers!(options)
      json = client.post("/v1/auth/token/create/#{encode_path(name)}", JSON.fast_generate(options), headers)
      return Secret.decode(json)
    end