Create a preauth value

@param {CreatePreauthOptions} options options for createPreauth
@param {callback} callback run with optional error (see throws) and
preauth key
@throws {InvalidOptionError}
@throws {SystemError}
181636
function (options, callback) {

        LOG.debug('preauth#createPreauth called');
        LOG.debug('Validating options');

        try {

            options = new preauthOptions.CreatePreauth().validate(options);

        } catch (err) {

            if (err.name === 'InvalidOption') {

                LOG.error('Invalid options specified: %s', err.message);

                callback(
                    commonErrors.InvalidOption(
                        undefined,
                        {
                            message: err.message
                        }
                    )
                );

            } else {

                LOG.error('System error: %s', err.message);

                callback(
                    commonErrors.SystemError(
                        undefined,
                        {
                            message: err.message
                        }
                    )
                );

            }

            return;

        }

        var timestamp = options.timestamp;

        if (!timestamp) {

            timestamp = new Date().getTime();

        }

        LOG.debug('Generating preauth key');

        var pakCreator = crypto.createHmac('sha1', options.key)
            .setEncoding('hex');

        pakCreator.write(
            util.format(
                '%s|%s|%s|%s',
                options.byValue,
                options.by,
                options.expires,
                timestamp
            )
        );
        pakCreator.end();
        var pak = pakCreator.read();

        LOG.debug('Returning preauth key %s', pak);

        callback(null, pak);

    }
612695
function fireCallback(callbackName) {
      var data = [], len = arguments.length - 1;
      while ( len-- > 0 ) data[ len ] = arguments[ len + 1 ];

      /*
        Callbacks:
        beforeCreate (options),
        beforeOpen (xhr, options),
        beforeSend (xhr, options),
        error (xhr, status),
        complete (xhr, stautus),
        success (response, status, xhr),
        statusCode ()
      */
      var globalCallbackValue;
      var optionCallbackValue;
      if (globals[callbackName]) {
        globalCallbackValue = globals[callbackName].apply(globals, data);
      }
      if (options[callbackName]) {
        optionCallbackValue = options[callbackName].apply(options, data);
      }
      if (typeof globalCallbackValue !== 'boolean') { globalCallbackValue = true; }
      if (typeof optionCallbackValue !== 'boolean') { optionCallbackValue = true; }
      return (globalCallbackValue && optionCallbackValue);
    }
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()
      }
    })
  }
}
751231
function init(ctx) {
        var server = ctx.server;

        if (!privateKey) {
            throw new Error('Please set config.security.token.privateKey');
        }

        server.ext('onPreAuth', validateToken);

        return new Q(ctx);
    }
155080
function createAuthKey(callback, channel) {

    flow.retryUntilIsDone(callback, null,
        function (callback) {
            flow.runSeries([
                require('./request-pq'),
                require('./request-dh-params'),
                require('./set-client-dh-params')
            ], callback, channel);
        });
}
784205
function(args) {
    var baseUrl = this.baseUrl + this.basePath;
    var authToken = this.authToken;
    var qs = this._buildQueryString(args.params);

    return new Promise(function(resolve, reject) {
      var req = new XMLHttpRequest();

      req.onreadystatechange = function() {
        if (req.readyState === 4) {
          try {
            var response = JSON.parse(req.responseText);
            var status = req.status;

            if (status >= 200 && status < 400) {
              return resolve(
                addShadowProperty({
                  target: response,
                  property: 'httpRequest',
                  value: req
                })
              );
            }

            return reject(
              createApiError(
                merge(response, {
                  status: status,
                  httpRequest: req
                })
              )
            );
          } catch (err) {
            reject(err);
          }
        }
      };

      req.open(args.method, baseUrl + args.path + qs, true);
      req.setRequestHeader('Authorization', 'Bearer ' + authToken);
      req.setRequestHeader('Accept', 'application/json');
      req.setRequestHeader('Content-type', 'application/json; charset=utf-8');
      req.send(args.payload ? JSON.stringify(args.payload) : null);
    });
  }
1244867
function createHandler(options) {
  /**
   * Client request handler
   * Data from the incoming request (plus options) is forwarded to the AWS module
   */
  return async (ctx) => {
    const { credentials, endpoint, region } = options
    const { rawBody: body, header: headers, method, url: path } = ctx.request

    console.log(chalk.cyan(method, path))

    const params = { body, credentials, endpoint, headers, method, path, region }
    const req = createSignedAWSRequest(params)
    const res = await sendAWSRequest(req)

    ctx.status = 200
    ctx.type = 'application/json'
    ctx.response.header = stripProxyResHeaders(res)
    ctx.body = res.body
  }
}
1292025
function(provider, options) {
      var authType;
      if (_.isString(provider)) {
        authType = provider;
        provider = Parse.User._authProviders[provider];
      } else {
        authType = provider.getAuthType();
      }
      if (_.has(options, 'authData')) {
        var authData = this.get('authData') || {};
        authData[authType] = options.authData;
        this.set('authData', authData);

        // Overridden so that the user can be made the current user.
        var newOptions = _.clone(options) || {};
        newOptions.success = function(model) {
          model._handleSaveResult(true);
          if (options.success) {
            options.success.apply(this, arguments);
          }
        };
        return this.save({'authData': authData}, newOptions);
      } else {
        var self = this;
        var promise = new Parse.Promise();
        provider.authenticate({
          success: function(provider, result) {
            self._linkWith(provider, {
              authData: result,
              success: options.success,
              error: options.error
            }).then(function() {
              promise.resolve(self);
            });
          },
          error: function(provider, error) {
            if (options.error) {
              options.error(self, error);
            }
            promise.reject(error);
          }
        });
        return promise;
      }
    }
983227
function TokenRequest(authenticate, options) {

	var self = this;
	this.status = 'expired';
	this.pendingCallbacks = [];

	// execute accumulated callbacks during the 'pending' state
	function fireCallbacks(err, token) {
		self.pendingCallbacks.forEach(function (callback) {
			callback(err, token);
		});
		self.pendingCallbacks = [];
	}

	TokenRequest.prototype.get = function (callback) {

		if (this.status == 'expired') {

			this.status = 'pending';
			this.pendingCallbacks.push(callback);

			authenticate(options, function (err, token) {
				if (err) {
					self.status = 'expired';
					return fireCallbacks(err, null);
				}
				self.issued = Date.now();
				self.duration = options.expiration || 60 * 60 * 1000;
				self.token = token;
				self.status = 'completed';
				return fireCallbacks(null, token);
			});

		} else if (this.status == 'pending') {
			// wait for the pending request instead of issuing a new one
			this.pendingCallbacks.push(callback);
		} else if (this.status == 'completed') {

			if (this.issued + this.duration < Date.now()) {
				this.status = 'expired';
				debug('token is expired, a new token will be requested');
				this.get(callback);
			} else {
				callback(null, this.token);
			}

		}
	};
}
1172922
function login(options) {
  if (!gui.isActive()) {
    throw new Error('Cannot login without a GUI.');
  }

  if (!options.scope) {
    throw new Error('Must specify list of requested scopes');
  }
  var params = {
    response_type: 'token',
    client_id: core.clientId,
    redirect_uri: 'https://api.twitch.tv/kraken/',
    scope: options.scope.join(' '),
  };

  if(options.force_verify) {
    params.force_verify = true;
  }

  if (!params.client_id) {
    throw new Error('You must call init() before login()');
  }

  gui.popupLogin(params);
}
12033
function createOptions(options) {
    var object = optionsCache[options] = {};(options.match(rnotwhite) || []).forEach(function (flag) {
        object[flag] = true;
    });
    return object;
}
390817
function init (prefs, callback) {
	options = _.extend(defaults, prefs);
	app = options.app || express();
	app.use(cors());

	ramlMocker.generate(options, process(function(requestsToMock){
		requestsToMock.forEach(function(reqToMock){
			addRoute(reqToMock);
		});
		log(new Array(30).join('='));
		log('%s[%s]%s API routes generated', colors.qyan, requestsToMock.length, colors.default);

		if(typeof callback === 'function'){
			callback(app);
		}
	}));

	var watcher = watch();
	var server = launchServer(app);

	function close () {
		if (watcher) { watcher.close(); }
		if (server) { server.close(); }
	}

	return {
		close: close,
		server: server,
		watcher: watcher
	};
}
1094293
function init(options) {
    if (options === void 0) { options = {}; }
    if ('debug' in options) {
        diag.debug.enabled = options.debug;
        Q.longStackSupport = options.debug;
    }
    if ('serverUrl' in options) {
        var myURL = url.parse(options.serverUrl);
        if (!myURL.protocol && !myURL.host) {
            return Q.reject(new Error(options.serverUrl + " is not an accepted Url, please add a Host and a Protocol."));
        }
    }
    _.assignWith(exports.initOptions, cloneServerInitOptions(options), function (left, right) { return _.isUndefined(right) ? left : right; });
    if ('push' in options) {
        exports.initOptions.push = _.cloneDeep(options.push);
    }
    return device.ready;
}
718645
function createAuth(type, token) {

  if (!type) {
    throw new Error('<type> required');
  }

  if (!token) {
    throw new Error('<token> required');
  }

  /**
   * Actual middleware that appends a `Authorization: "${type} ${token}"`
   * header to the request options.
   */
  return function(worker) {

    const workerOptions = worker.options;
    const requestOptions = workerOptions.requestOptions || {};
    const headers = requestOptions.headers || {};

    worker.options = {
      ...workerOptions,
      requestOptions: {
        ...requestOptions,
        headers: {
          ...headers,
          Authorization: `${type} ${token}`
        }
      }
    };
  };
}
956665
function init(options) {

    var fs = require('fs');
    var path = require('path');
    var rootdir = path.dirname(require.main);
    var options = options || {
        config: require(path.join(rootdir, 'config.json')),
        root: rootdir,
        callback: function (noop) {}
    };
    var def = {};
    function ModulePaths (moduledir) {
        this.moduledir = moduledir;
    }

    ModulePaths.prototype.then = function (accept, reject) {
      var moduledir = this.moduledir;
      fs.readdir(moduledir, function (err, files) {
        if (err) reject(err);
        files.forEach(function (file) {
            var name = path.basename(file, '.js');
            def[name] = path.join(moduledir, name);
        });
        accept();
      });
    };
    var pubpath = new ModulePaths(path.join(path.dirname(module.filename), '..', 'public', 'js'));
    var prvpath = new ModulePaths(path.join(path.dirname(module.filename), '..', 'private', 'js'));

    Promise.all([pubpath, prvpath])
        .then(function () {
            var requirejs = require('requirejs');
            requirejs.config({
                baseUrl: path.join(rootdir),
                paths: def
            });

            requirejs(['loader_factory'], function (LoaderFactory) {
                var fs = require('fs');
                var config = options.config;
                config.paths.push(path.dirname(pubpath.moduledir));
                var loader = 'loader_express';
                var db = 'db_mongo';
                if (config.loader) loader = config.loader;
                if (config.db) db = config.db;

                new LoaderFactory().create(loader, db, function (loader) {
                    loader.init(config, options.callback);
                });
            });
        })
    .catch(function (err) {
        console.error('err:', err);
    });
}
1275628
function(callback) {
        var self = this;

        var auth_post_data = querystring.stringify({
            'grant_type': 'client_credentials'
        });

        return new Promise(function(resolve, reject){
            self.client.methods.authentication_oauth(_.extend({}, self.requestOptions, {
                data: auth_post_data,
                headers: _.extend({}, self.requestOptions.headers, {
                    'Authorization': _getBasicAuthHash(self.config.clientId, self.config.clientApiKey),
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Content-Length': Buffer.byteLength(auth_post_data)
                })
            }), function(data) {
                // Authorization succeeded
                if (data.token_type && data.access_token) {
                    _.extend(self.requestOptions.headers, {
                        'Authorization': data.token_type + ' ' + data.access_token
                    });
                    // Multiplying expires_in (seconds) by 1000 since JS getTime() is expressed in ms
                    self.authorizationExpireTime = new Date().getTime() + ( data.expires_in * 1000 );
                    resolve(data);
                    if (_.isFunction(callback)) {
                        callback(data);
                    }
                } else {
                    reject(data);
                }
            }).on('error', function (err) { reject(err.message) });
        });
    }
404315
function AuthenticationOAuth(options) {
    AuthenticationAbstract.call(this, options);
    options = options || {};
    this._token = {
        access: options.accessToken || null
    };
}