Added because the Dropbox OAuth2 flow doesn't
        work when scope is passed in, which is empty.
483801
def _strip_empty_keys(self, params):
        
        keys = [k for k, v in params.items() if v == '']
        for key in keys:
            del params[key]
628910
function addScopedHandler (event, handler, scope) {
    if (handlers[event] === undefined) {
        handlers[event] = [];
    }

    let scopedHandler = scope ? handler.bind(scope) : handler;

    handlers[event].push({
        original: handler,
        scoped: scopedHandler
    });

    return scopedHandler;
}
459799
function handleLogin(onCloudLoginSuccess) {
  const link = authLink();
  const authWindow = window.open(link, '_blank', 'width=1024,height=716');
  const handleToken = e => {
    // TODO: add security step to validate which domain the message is coming from
    authWindow.close();
    window.removeEventListener('message', handleToken);
    dropbox.setAccessToken(e.data.token);
    if (window.localStorage) {
      window.localStorage.setItem('dropbox', JSON.stringify({
        // dropbox token doesn't expire unless revoked by the user
        token: e.data.token,
        timetamp: new Date()
      }));
    }
    onCloudLoginSuccess();
  };
  window.addEventListener('message', handleToken);
}
258148
function getAuthenticationUrl(scopes, clientId, clientSecret, redirectUri = 'urn:ietf:wg:oauth:2.0:oob') {
	const oauth2Client = new OAuth2(
		clientId,
		clientSecret,
		redirectUri
	);
	const url = oauth2Client.generateAuthUrl({
		access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
		scope: scopes // If you only need one scope you can pass it as string
	});
	return url;
}
405924
function getToken (client) {
  debug("getToken");
  console.log("No token found to access Github API. I will now ask for your username and password to generate one.");
  console.log("Those information ARE NOT STORED, only the generated token will be stored in your global git configuration.");
  console.log("If you don't want to let this process go you'll have to generate a token yourself and then save it with 'github-todos config github.token <your token>'.");

  return ask([
    {"type": "input",     "message": "Github username", "name": "user"},
    {"type": "password",  "message": "Github password", "name": "password"}
  ]).then(function (answers) {

    client.authenticate({
      "type":     "basic",
      "username": answers.user,
      "password": answers.password
    });

    var payload = {
      "note":     "Github-Todos (" + (new Date()) + ")",
      "note_url": "https://github.com/naholyr/github-todos",
      "scopes":   ["user", "repo"]
    };

    return Promise.promisify(client.authorization.create, client.authorization)(payload)
      .then(null, function (err) {
        if (err && err.code === 401 && err.message && err.message.indexOf("OTP") !== -1) {
          // Two-factor authentication
          console.log("You are using two-factor authentication, please enter your code to finish:");
          return twoFactorAuth(client, payload);
        } else {
          throw err;
        }
      })
      .then(saveToken(client));
  });
}
1222760
def do_local_server_auth_flow(session_params=None, force_new_client=False):
    
    session_params = session_params or {}

    # start local server and create matching redirect_uri
    with start_local_server(listen=("127.0.0.1", 0)) as server:
        _, port = server.socket.getsockname()
        redirect_uri = "http://localhost:{}".format(port)

        # get the ConfidentialApp client object and start a flow
        auth_client = internal_auth_client(
            requires_instance=True, force_new_client=force_new_client
        )
        auth_client.oauth2_start_flow(
            refresh_tokens=True, redirect_uri=redirect_uri, requested_scopes=SCOPES
        )
        additional_params = {"prompt": "login"}
        additional_params.update(session_params)
        url = auth_client.oauth2_get_authorize_url(additional_params=additional_params)

        # open web-browser for user to log in, get auth code
        webbrowser.open(url, new=1)
        auth_code = server.wait_for_code()

    if isinstance(auth_code, LocalServerError):
        safeprint("Authorization failed: {}".format(auth_code), write_to_stderr=True)
        click.get_current_context().exit(1)
    elif isinstance(auth_code, Exception):
        safeprint(
            "Authorization failed with unexpected error:\n{}".format(auth_code),
            write_to_stderr=True,
        )
        click.get_current_context().exit(1)

    # finish auth flow and return true
    exchange_code_and_store_config(auth_client, auth_code)
    return True
1260568
function (auth) {
        var host = window.location;
        var pathname = location.pathname.substring(0, location.pathname.lastIndexOf('/'));
        var defaultRedirectUrl = host.protocol + '//' + host.host + pathname + '/o2c.html';
        var redirectUrl = window.oAuthRedirectUrl || defaultRedirectUrl;
        var url = null;
        var scopes = _.map(auth.get('scopes'), function (scope) {
            if(scope.checked) {
                return scope.scope;
            }
        });
        var container = window.swaggerUiAuth || (window.swaggerUiAuth = {});
        var state, dets, ep;
        container.OAuthSchemeKey = auth.get('title');

        window.enabledScopes = scopes;
        var flow = auth.get('flow');

        /**
         * Returns the name of the access token parameter returned by the server.
         *
         * @param dets
         *     The authorisation scheme configuration.
         * @return the name of the access token parameter
         */
        function getTokenName(dets) {
            return dets.vendorExtensions['x-tokenName'] || dets.tokenName;
        }

        if(auth.get('type') === 'oauth2' && flow && (flow === 'implicit' || flow === 'accessCode')) {
            dets = auth.attributes;
            url = dets.authorizationUrl + '?response_type=' + (flow === 'implicit' ? 'token' : 'code');
            container.tokenName = getTokenName(dets) || 'access_token';
            container.tokenUrl = (flow === 'accessCode' ? dets.tokenUrl : null);
            state = container.OAuthSchemeKey;
        }
        else if(auth.get('type') === 'oauth2' && flow && (flow === 'application')) {
            dets = auth.attributes;
            container.tokenName = getTokenName(dets) || 'access_token';
            this.clientCredentialsFlow(scopes, dets, container.OAuthSchemeKey);
            return;
        }
        else if(auth.get('type') === 'oauth2' && flow && (flow === 'password')) {
            dets = auth.attributes;
            container.tokenName = getTokenName(dets) || 'access_token';
            this.passwordFlow(scopes, dets, container.OAuthSchemeKey);
            return;
        }
        else if(auth.get('grantTypes')) {
            // 1.2 support
            var o = auth.get('grantTypes');
            for(var t in o) {
                if(o.hasOwnProperty(t) && t === 'implicit') {
                    dets = o[t];
                    ep = dets.loginEndpoint.url;
                    url = dets.loginEndpoint.url + '?response_type=token';
                    container.tokenName = getTokenName(dets);
                }
                else if (o.hasOwnProperty(t) && t === 'accessCode') {
                    dets = o[t];
                    ep = dets.tokenRequestEndpoint.url;
                    url = dets.tokenRequestEndpoint.url + '?response_type=code';
                    container.tokenName = getTokenName(dets);
                }
            }
        }

        redirect_uri = redirectUrl;

        url += '&redirect_uri=' + encodeURIComponent(redirectUrl);
        url += '&realm=' + encodeURIComponent(realm);
        url += '&client_id=' + encodeURIComponent(clientId);
        url += '&scope=' + encodeURIComponent(scopes.join(scopeSeparator));
        url += '&state=' + encodeURIComponent(state);
        for (var key in additionalQueryStringParams) {
            url += '&' + key + '=' + encodeURIComponent(additionalQueryStringParams[key]);
        }

        window.open(url);
    }
1248957
function(scopes) {
                console.log('iamInterface.group.addScopes', scopes);
                corbel.validate.value('id', this.id);
                return this.request({
                    url: this._buildUriWithDomain(this.uri, this.id) + '/scope',
                    method: corbel.request.method.PUT,
                    data: scopes,
                    withAuth: true
                });
            }
201637
public void setScopes(Set<ApiAppOauthScopeType> scopes) {
        if (oauth == null) {
            oauth = new ApiAppOauth();
        }
        oauth.setScopes(scopes);
    }
604185
public static function generateToken($client_id, $redirect_uri, $scope = 'public_content')
  {
    $params = array(
      'client_id'     => $client_id,
      'redirect_uri'  => $redirect_uri,
      'response_type' => 'token',
      'scope'         => $scope
    );
    header('location:https://www.instagram.com/oauth/authorize/?' . http_build_query($params));
    die;
  }
1292317
function useNonce($server_url, $timestamp, $salt)
    {
        global $Auth_OpenID_SKEW;

        if (!$this->active) {
            trigger_error("FileStore no longer active", E_USER_ERROR);
            return null;
        }

        if ( abs($timestamp - time()) > $Auth_OpenID_SKEW ) {
            return false;
        }

        if ($server_url) {
            list($proto, $rest) = explode('://', $server_url, 2);
        } else {
            $proto = '';
            $rest = '';
        }

        $parts = explode('/', $rest, 2);
        $domain = $this->_filenameEscape($parts[0]);
        $url_hash = $this->_safe64($server_url);
        $salt_hash = $this->_safe64($salt);

        $filename = sprintf('%08x-%s-%s-%s-%s', $timestamp, $proto,
                            $domain, $url_hash, $salt_hash);
        $filename = $this->nonce_dir . DIRECTORY_SEPARATOR . $filename;

        $result = @fopen($filename, 'x');

        if ($result === false) {
            return false;
        } else {
            fclose($result);
            return true;
        }
    }
954447
void processScope(Scope scope) {
    boolean shouldAddToBlockStack = !scope.isHoistScope();
    this.narrowScope = scope;
    if (shouldAddToBlockStack) {
      blockStack.add(new BasicBlock(null, scope.getRootNode()));
    }
    (new NodeTraversal(compiler, this, scopeCreator)).traverseAtScope(scope);
    if (shouldAddToBlockStack) {
      pop(blockStack);
    }
    this.narrowScope = null;
  }
701229
function getAccessTokenFromLocation(location) {
  if (!(location && location.hash.length)) {
    return null;
  }
  // dropbox token usually start with # therefore we want to remore the '#'
  const query = window.location.hash.substring(1);

  return parseQueryString(query).access_token;
}
1324583
public function passValidateCredentialsAndCreateAccessTokenResponse(
        string $userName,
        string $password,
        ClientInterface $client = null,
        bool $isScopeModified = false,
        array $scope = null,
        array $extraParameters = []
    ): ResponseInterface {
        assert($client !== null);

        if (($userIdentifier = $this->getIntegration()->validateUserId($userName, $password)) === null) {
            $this->logDebug('User not found with provided username and password.', ['username' => $userName]);
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_INVALID_GRANT);
        }
        assert(is_int($userIdentifier) === true);
        $this->logInfo('User authenticated with provided username and password.', ['username' => $userName]);

        $changedScopeOrNull = $this->getIntegration()->verifyAllowedUserScope($userIdentifier, $scope);
        if ($changedScopeOrNull !== null) {
            assert(is_array($changedScopeOrNull));
            $isScopeModified = true;
            $scope           = $changedScopeOrNull;
        }

        $unsavedToken = $this->getIntegration()->createTokenInstance();
        $unsavedToken
            ->setClientIdentifier($client->getIdentifier())
            ->setScopeIdentifiers($scope)
            ->setUserIdentifier($userIdentifier);
        $isScopeModified === true ? $unsavedToken->setScopeModified() : $unsavedToken->setScopeUnmodified();

        $tokenExpiresIn = $this->setUpTokenValues($unsavedToken);
        $savedToken     = $this->getIntegration()->getTokenRepository()->createToken($unsavedToken);

        $response = $this->createBodyTokenResponse($savedToken, $tokenExpiresIn);

        return $response;
    }
602892
function error() {

                        this.httpRequest.upload.onerror = function onError() {

                            $scope.$apply(function apply() {

                                $scope.finishedUploading();
                                $scope.isError = true;

                                var response = $scope.options.parserFn(this.httpRequest.responseText);
                                $rootScope.$broadcast('$dropletError', response);
                                $scope.onError({ response: response });
                                this.deferred.reject(response);

                            }.bind(this));

                        }.bind(this);

                    }
1313190
function getAccessToken() {
  let token = dropbox.getAccessToken();
  if (!token && window.localStorage) {
    const jsonString = window.localStorage.getItem('dropbox');
    token = jsonString && JSON.parse(jsonString).token;
    if (token) {
      dropbox.setAccessToken(token);
    }
  }

  return (token || '') !== '' ? token : null;
}
1366129
function (type) {
        if (!(RequestAuth.isValidType(type) && VariableList.isVariableList(this[type]))) {
            return;
        }

        // clear the variable list
        this[type].clear();

        // if it is not a currently selected auth type, do not delete the variable list, but simply delete it
        if (type !== this.type) {
            delete this[type];
        }
    }