Method used to get a request token.

@return  void

@since   1.1.2
@throws  \DomainException
432731
private function generateRequestToken()
	{
		// Set the callback URL.
		if ($this->getOption('callback'))
		{
			$parameters = array(
				'oauth_callback' => $this->getOption('callback'),
			);
		}
		else
		{
			$parameters = array();
		}

		// Make an OAuth request for the Request Token.
		$response = $this->oauthRequest($this->getOption('requestTokenURL'), 'POST', $parameters);

		parse_str($response->body, $params);

		if (strcmp($this->version, '1.0a') === 0 && strcmp($params['oauth_callback_confirmed'], 'true') !== 0)
		{
			throw new \DomainException('Bad request token!');
		}

		// Save the request token.
		$this->token = array('key' => $params['oauth_token'], 'secret' => $params['oauth_token_secret']);

		// Save the request token in session
		$session = $this->application->getSession();
		$session->set('oauth_token.key', $this->token['key']);
		$session->set('oauth_token.secret', $this->token['secret']);
	}
650869
protected function fetchExecutionToken()
    {
        try {
            $response = $this->client->get(static::LOGIN_URL, [
                'headers' => [
                    'User-Agent' => 'niantic'
                ]
            ]);
        } catch(ServerException $e) {
            sleep(1);
            return $this->fetchExecutionToken();
        }

        if ($response->getStatusCode() !== 200) {
            throw new AuthenticationException("Could not retrieve execution token. Got status code " . $response->getStatusCode());
        }

        $jsonData = json_decode($response->getBody()->getContents());

        if (!$jsonData || !isset($jsonData->execution)) {
            throw new AuthenticationException("Could not retrieve execution token. Invalid JSON. TrainersClub could be offline or unstable.");
        }

        return $jsonData;
    }
676798
public function getTokenFromServer()
    {
        $params = [
            'component_appid' => $this->appId,
            'component_appsecret' => $this->secret,
            'component_verify_ticket' => $this->ticket->getTicket(),
        ];

        $http = $this->getHttp();

        $token = $http->parseJSON($http->json(self::API_TOKEN_GET, $params));

        if (empty($token['component_access_token'])) {
            throw new HttpException('Request AccessToken fail. response: '.json_encode($token, JSON_UNESCAPED_UNICODE));
        }

        $token['access_token'] = $token['component_access_token'];

        return $token;
    }
95891
public function getBearerToken() {

	    $headers = null;
	    $token   = null;

	    if (isset($_SERVER['Authorization'])) {
	        $headers = \trim($_SERVER['Authorization']);
	    } elseif (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
	        $headers = \trim($_SERVER['HTTP_AUTHORIZATION']);
	    } elseif (\function_exists('apache_request_headers')) {
	        $requestHeaders = \apache_request_headers();
	        // Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
	        $requestHeaders = \array_combine(\array_map('ucwords', \array_keys($requestHeaders)), \array_values($requestHeaders));
	        if (isset($requestHeaders['Authorization'])) {
	            $headers = \trim($requestHeaders['Authorization']);
	        }
	    }

	    // HEADER: Get the access token from the header
	    if ($headers) {
	        if (\preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
	            $token = $matches[1];
	        }
	    }

	    return $token;
	}
1175967
protected function extractToken()
    {
        if ($this->request->input('token') === false) {
            if (!$this->request->getHeader('X-JS-CLIENTS-TOKEN')) {
                return 'token';
            }

            return $this->request->getHeader('X-JS-CLIENTS-TOKEN');
        }

        return $this->request->input('token');
    }
57503
protected function getToken()
    {
        $temp = $this->request->getSession()->get('oauth.temp');

        return $this->server->getTokenCredentials(
            $temp, $this->request->get('oauth_token'), $this->request->get('oauth_verifier')
        );
    }
1248913
public function index()
    {
        //  Validates the request token and generates a new one for the next request
        $this->validateToken();

        // --------------------------------------------------------------------------

        $oInput     = Factory::service('Input');
        $oAuthModel = Factory::model('Auth', 'nails/module-auth');

        if ($oInput->post('answer')) {

            /**
             * Validate the answer, if correct then log user in and forward, if
             * not then generate a new token and show errors
             */

            $this->data['question'] = $oAuthModel->mfaQuestionGet($this->mfaUser->id);
            $bIsValid               = $oAuthModel->mfaQuestionValidate(
                $this->data['question']->id,
                $this->mfaUser->id,
                $oInput->post('answer')
            );

            if ($bIsValid) {
                $this->loginUser();
            } else {
                $this->data['error'] = lang('auth_twofactor_answer_incorrect');
                $this->askQuestion();
            }

        } else {

            //  Determine whether the user has any security questions set
            $this->data['question'] = $oAuthModel->mfaQuestionGet($this->mfaUser->id);

            if ($this->data['question']) {

                //  Ask away cap'n!
                $this->askQuestion();

            } else {

                //  Fetch the security questions
                $this->data['questions'] = $this->authMfaConfig['questions'];

                /**
                 * Determine how many questions a user must have, if the number of questions
                 * is smaller than the number of questions available, use the smaller.
                 */
                if (count($this->data['questions']) < $this->authMfaConfig['numQuestions']) {
                    $this->data['num_questions'] = count($this->data['questions']);
                } else {
                    $this->data['num_questions'] = $this->authMfaConfig['numQuestions'];
                }

                //  The number of user generated questions a user must have
                $this->data['num_custom_questions'] = $this->authMfaConfig['numUserQuestions'];

                if ($this->data['num_questions'] + $this->data['num_custom_questions'] <= 0) {
                    throw new NailsException('Two-factor auth is enabled, but no questions available');
                }

                if ($oInput->post()) {

                    $oFormValidation = Factory::service('FormValidation');

                    for ($i = 0; $i < $this->data['num_questions']; $i++) {

                        $oFormValidation->set_rules(
                            'question[' . $i . '][question]',
                            '',
                            'required|is_natural_no_zero'
                        );

                        $oFormValidation->set_rules(
                            'question[' . $i . '][answer]',
                            '',
                            'trim|required'
                        );
                    }

                    for ($i = 0; $i < $this->data['num_custom_questions']; $i++) {

                        $oFormValidation->set_rules(
                            'custom_question[' . $i . '][question]',
                            '',
                            'trim|required'
                        );

                        $oFormValidation->set_rules(
                            'custom_question[' . $i . '][answer]',
                            '',
                            'trim|required'
                        );
                    }

                    $oFormValidation->set_message('required', lang('fv_required'));
                    $oFormValidation->set_message('is_natural_no_zero', lang('fv_required'));

                    if ($oFormValidation->run()) {

                        //  Make sure that we have different questions
                        $aQuestionIndex = [];
                        $aQuestion      = (array) $oInput->post('question', true);
                        $bError         = false;

                        foreach ($aQuestion as $q) {
                            if (array_search($q['question'], $aQuestionIndex) === false) {
                                $aQuestionIndex[] = $q['question'];
                            } else {
                                $bError = true;
                                break;
                            }
                        }

                        $aQuestionIndex = [];
                        $aQuestion      = (array) $oInput->post('custom_question', true);

                        foreach ($aQuestion as $q) {
                            if (array_search($q['question'], $aQuestionIndex) === false) {
                                $aQuestionIndex[] = $q['question'];
                            } else {
                                $bError = true;
                                break;
                            }
                        }

                        if (!$bError) {

                            //  Good arrows. Save questions
                            $aData = [];

                            if ($oInput->post('question', true)) {

                                foreach ($oInput->post('question', true) as $q) {

                                    $oTemp = new stdClass();

                                    if (isset($this->data['questions'][$q['question'] - 1])) {
                                        $oTemp->question = $this->data['questions'][$q['question'] - 1];
                                    } else {
                                        $oTemp->question = null;
                                    }
                                    $oTemp->answer = $q['answer'];

                                    $aData[] = $oTemp;
                                }
                            }

                            if ($oInput->post('custom_question', true)) {
                                foreach ((array) $oInput->post('custom_question', true) as $aQuestion) {
                                    $aData[] = (object) [
                                        'question' => trim($aQuestion['question']),
                                        'answer'   => $aQuestion['answer'],
                                    ];
                                }
                            }

                            if ($oAuthModel->mfaQuestionSet($this->mfaUser->id, $aData)) {

                                $sStatus  = 'success';
                                $sMessage = '<strong>Multi Factor Authentication Enabled!</strong><br />You ';
                                $sMessage .= 'successfully set your security questions. You will be asked to answer ';
                                $sMessage .= 'one of them every time you log in.';

                                $oSession = Factory::service('Session', 'nails/module-auth');
                                $oSession->setFlashData($sStatus, $sMessage);

                                $this->loginUser();

                            } else {

                                $oUserModel          = Factory::model('User', 'nails/module-auth');
                                $this->data['error'] = lang('auth_twofactor_question_set_fail');
                                $this->data['error'] .= ' ' . $oUserModel->lastError();
                            }

                        } else {
                            $this->data['error'] = lang('auth_twofactor_question_unique');
                        }

                    } else {
                        $this->data['error'] = lang('fv_there_were_errors');
                    }
                }

                //  No questions, request they set them
                $this->data['page']->title = lang('auth_twofactor_question_set_title');
                $this->loadStyles(NAILS_APP_PATH . 'application/modules/auth/views/mfa/question/set.php');
                Factory::service('View')
                    ->load([
                        'structure/header/blank',
                        'auth/mfa/question/set',
                        'structure/footer/blank',
                    ]);
            }
        }
    }
993180
protected function getAuthToken()
    {
        $token = $this->request->getHeader('X_AUTHORIZATION');
        if (!$token) {
            $request = $this->getDI()->get('request');
            $token = $request->getQuery('token') ?: $request->getPost('token');
        }

        $token = trim(str_ireplace('Token:', '', $token));
        if (strlen($token) < 30) {
            throw new HTTPException('Unauthorized access blocked', 401, [
                'dev' => 'Supplied Token: ' . $token,
                'code' => '98914681681864674'
            ]);
        }
        return $token;
    }
1090491
protected function getTokenFromServer()
    {
        $http = new Http();
        $params = array(
            'corpid'      => $this->appId,
            'corpsecret'     => $this->appSecret,
        );

        $token = $http->get(self::API_TOKEN_GET, $params);

        return $token;
    }
1295265
protected function _getAuthenticateChallengeHeader()
    {
        $wwwauth = 'Digest realm="' . $this->getRealm() . '", '
            /*
             * Domain directive is not meaningful in Proxy-Authenticate headers,
             * for which the protection space is always the entire proxy; if present
             * it should be ignored.
             */
            . ( ($this->getDomains()) ? 'domain="' . $this->domains . '", ' : '' )
            . 'nonce="' . $this->_generateNonce() . '", '
            /*
             * This can be treated as a session id. If this changes the browser
             * will deauthenticate the user.
             */
            . ( ($this->isUseOpaque()) ? 'opaque="' . $this->_generateOpaque() . '", ' : '' )
            /*
             * indicating that the previous request from the client was
             * rejected because the nonce value was stale. If stale is TRUE
             * (case-insensitive), the client may wish to simply retry the request
             * with a new encrypted response, without reprompting the user for a
             * new username and password. The server should only set stale to TRUE
             * if it receives a request for which the nonce is invalid but with a
             * valid digest for that nonce (indicating that the client knows the
             * correct username/password). If stale is FALSE, or anything other
             * than TRUE, or the stale directive is not present, the username
             * and/or password are invalid, and new values must be obtained.
             */
            . ( (isset($this->stale)) ? 'stale="true"' : '' )
            . 'algorithm="' . $this->defaultAlgorithm . '", '
            . 'qop="' . implode(',', $this->supportedQops) . '"';

        return $wwwauth;
    }
1278289
public function getToken($request = null)
    {
        $request = $request ?: $this->makeRequest();

        list($token) = sscanf($request->header($this->getAuthHeaderKey()), 'Bearer %s');
        if( ! $token) {
            $name = $this->getInputName();
            $token = $request->input($name);
        }

        return $token;
    }
52334
public function authenticate()
	{
		// Already got some credentials stored?
		if ($this->token)
		{
			$response = $this->verifyCredentials();

			if ($response)
			{
				return $this->token;
			}

			$this->token = null;
		}

		// Check for callback.
		if (strcmp($this->version, '1.0a') === 0)
		{
			$verifier = $this->input->get('oauth_verifier');
		}
		else
		{
			$verifier = $this->input->get('oauth_token');
		}

		if (empty($verifier))
		{
			// Generate a request token.
			$this->generateRequestToken();

			// Authenticate the user and authorise the app.
			$this->authorise();
		}

		// Callback
		else
		{
			$session = $this->application->getSession();

			// Get token form session.
			$this->token = array('key' => $session->get('oauth_token.key', null), 'secret' => $session->get('oauth_token.secret', null));

			// Verify the returned request token.
			if (strcmp($this->token['key'], $this->input->get('oauth_token')) !== 0)
			{
				throw new \DomainException('Bad session!');
			}

			// Set token verifier for 1.0a.
			if (strcmp($this->version, '1.0a') === 0)
			{
				$this->token['verifier'] = $this->input->get('oauth_verifier');
			}

			// Generate access token.
			$this->generateAccessToken();

			// Return the access token.
			return $this->token;
		}
	}
583120
public function get()
    {
        if (isset($this->settings['instanceURL']) && !empty($this->settings['instanceURL'])) {
            return $this->settings['instanceURL'];
        } else {
            return $this->tokenRepo->get()['instance_url'];
        }
    }
1362802
public function getBlockEndToken(): array
    {
        if (!$this->hasDocBlock()) {
            throw new DomainException(
                sprintf('Missing doc block for position %s of file %s.', $this->stackPos, $this->file->getFilename())
            );
        }

        return $this->tokens[$this->getBlockEndPosition()];
    }
766344
private function getAuthToken()
    {
        // Generate a new token if current is expired or empty
        if (!$this->token || new \DateTime() > $this->tokenExpireTime) {
            $this->requestToken();
        }

        return $this->token;
    }
227143
public function getTokenResponse()
    {
        $query = [
            'grant_type' => 'client_credential',
            'appid' => $this['appid'],
            'secret' => $this['appsecret'],
        ];

        $response = Http::request('GET', static::ACCESS_TOKEN)
            ->withQuery($query)
            ->send();

        if ($response->containsKey('errcode')) {
            throw new \Exception($response['errmsg'], $response['errcode']);
        }

        return $response;
    }
1276654
protected function getRequestToken($request)
    {
        $name = $this->getName();
        $header = 'X-' . ucwords(strtolower($name));
        if ($token = $request->getHeader($header)) {
            return $token;
        }

        // Get from request var
        return $request->requestVar($name);
    }