Include an accessToken in a given HttpRequest.
@param HttpRequest $request
@return HttpRequest
@throws Exception
553692
public function sign(HttpRequest $request) {
    // add the developer key to the request before signing it
    if ($this->developerKey) {
      $requestUrl = $request->getUrl();
      $requestUrl .= (strpos($request->getUrl(), '?') === false) ? '?' : '&';
      $requestUrl .=  'key=' . urlencode($this->developerKey);
      $request->setUrl($requestUrl);
    }

    // Cannot sign the request without an OAuth access token.
    if (null == $this->accessToken && null == $this->assertionCredentials) {
      return $request;
    }

    // If the token is set to expire in the next 30 seconds (or has already
    // expired), refresh it and set the new token.
    $expired = (null == $this->accessToken) ||
        ($this->accessToken['created'] + ($this->accessToken['expires_in'] - 30)) < time();

    if ($expired) {
      if ($this->assertionCredentials) {
        $this->refreshTokenWithAssertion();
      } else {
        if (! array_key_exists('refresh_token', $this->accessToken)) {
            throw new Exception("The OAuth 2.0 access token has expired, "
                . "and a refresh token is not available. Refresh tokens are not "
                . "returned for responses that were auto-approved.");
        }
        $this->refreshToken($this->accessToken['refresh_token']);
      }
    }

    // Add the OAuth2 header to the request
    $request->setRequestHeaders(
        array('Authorization' => 'Bearer ' . $this->accessToken['access_token'])
    );

    return $request;
  }
1097732
public function authenticate(Request $request)
    {
        $this->checkForToken($request);

        try {
            if (! $this->auth->parseToken()->authenticate()) {
                throw new UnauthorizedHttpException('jwTauth', 'User not found');
            }
        } catch (JwTException $e) {
            throw new UnauthorizedHttpException('jwTauth', $e->getMessage(), $e, $e->getCode());
        }
    }
878910
public function fetchAccessToken(&$request)
    {
        $this->getVersion($request);
        
        $consumer = $this->getConsumer($request);
        
        // requires authorized request token
        $token = $this->getToken($request, $consumer, "request");
        
        $this->checkSignature($request, $consumer, $token);
        
        // Rev A change
        $verifier = $request->getParameter('oauth_verifier');
        $new_token = $this->data_store->newAccessToken($token, $consumer, $verifier);
        
        return $new_token;
    }
922455
function getOAuthToken($request)
    {
        $token = OAuth\Util::parse_parameters($request);
        if (isset($token['oauth_token'], $token['oauth_token_secret'])) {
            $this->token = new OAuth\Consumer($token['oauth_token'], $token['oauth_token_secret']);
        }

        return $token;
    }
1176583
public function callback(HTTPRequest $request)
    {
        $session = $request->getSession();

        if (!$this->validateState($request)) {
            $session->clear('oauth2');
            $this->httpError(400, 'Invalid session state.');
            return null;
        }

        $providerName = $session->get('oauth2.provider');
        /** @var ProviderFactory $providerFactory */
        $providerFactory = Injector::inst()->get(ProviderFactory::class);
        $provider = $providerFactory->getProvider($providerName);
        $returnUrl = $this->getReturnUrl();

        try {
            $accessToken = $provider->getAccessToken('authorization_code', [
                'code' => $request->getVar('code')
            ]);

            $handlers = $this->getHandlersForContext($session->get('oauth2.context'));

            // Run handlers to process the token
            $results = [];
            foreach ($handlers as $handlerConfig) {
                $handler = Injector::inst()->create($handlerConfig['class']);
                $results[] = $handler->handleToken($accessToken, $provider);
            }

            // Handlers may return response objects
            foreach ($results as $result) {
                if ($result instanceof HTTPResponse) {
                    $session->clear('oauth2');

                    // If the response is redirecting to the login page (e.g. on Security::permissionFailure()),
                    // update the BackURL so it doesn't point to /oauth/callback/
                    if ($result->isRedirect()) {
                        $location = $result->getHeader('location');
                        $relativeLocation = Director::makeRelative($location);

                        // If the URL begins Security/login and a BackURL parameter is set...
                        if (
                            strpos($relativeLocation, Security::config()->uninherited('login_url')) === 0
                            && strpos($relativeLocation, 'BackURL') !== -1
                        ) {
                            $session->set('BackURL', $returnUrl);
                            $location = HTTP::setGetVar('BackURL', $returnUrl, $location);
                            $result->addHeader('location', $location);
                        }
                    }
                    
                    return $result;
                }
            }
        } catch (IdentityProviderException $e) {
            /** @var LoggerInterface $logger */
            $logger = Injector::inst()->get(LoggerInterface::class . '.oauth');
            $logger->error('OAuth IdentityProviderException: ' . $e->getMessage());
            $this->httpError(400, 'Invalid access token.');
            return null;
        } catch (Exception $e) {
            /** @var LoggerInterface $logger */
            $logger = Injector::inst()->get(LoggerInterface::class . '.oauth');
            $logger->error('OAuth Exception: ' . $e->getMessage());
            $this->httpError(400, $e->getMessage());
            return null;
        } finally {
            $session->clear('oauth2');
        }

        return $this->redirect($returnUrl);
    }
341817
public function tokenAction(Request $request)
    {
        /** @var PropertyAccess $config */
        $config = $this->app['conf'];

        if ( ! $request->isSecure() && $config->get(['main', 'api_require_ssl'], true) == true) {
            throw new HttpException(400, 'This route requires the use of the https scheme: ' . $config->get(['main', 'api_require_ssl']), null, ['content-type' => 'application/json']);
        }

        $this->oAuth2Adapter->grantAccessToken();
        ob_flush();
        flush();

        // As OAuth2 library already outputs response content, we need to send an empty
        // response to avoid breaking silex controller
        return '';
    }
632570
public function run(HTTPRequest $request) {
		$options = $request->getRoute()->getOptions();
		if( !empty($options['url_config']) ) {
			$url = AppConfig::instance()->get($options['url_config']);
			if( !$url ) {
				throw new Exception('The RedirectController requires a valid url_config option, please check your configuration.');
			}
		} else
		if( empty($options['redirect']) ) {
			throw new Exception('The RedirectController requires a redirect option, add it to your route configuration.');
		} else {
			$url = u($options['redirect']);
		}
		return new RedirectHTTPResponse($url);
	}
1182267
public function getOwner(HTTPRequest $request)
    {
        $owner = null;

        //get the token
        $token = $request->getHeader($this->tokenConfig['header']);
        if (!$token) {
            $token = $request->requestVar($this->tokenConfig['queryVar']);
        }

        if ($token) {
            $SQLToken = Convert::raw2sql($token);

            $owner = DataObject::get_one(
                $this->tokenConfig['owner'],
                "\"" . $this->tokenConfig['DBColumn'] . "\"='" . $SQLToken . "'",
                false
            );

            if (!$owner) {
                $owner = null;
            }
        }

        return $owner;
    }
612920
public function sendRequest(Http\Request $request)
    {
        if (!extension_loaded('curl')) {
            throw new Http\Exception('CurlEngine requires the PHP CURL extension to be installed and loaded.', 1346319808);
        }

        $requestUri = $request->getUri();
        $curlHandle = curl_init((string)$requestUri);

        curl_setopt_array($curlHandle, $this->options);

        // Send an empty Expect header in order to avoid chunked data transfer (which we can't handle yet).
        // If we don't set this, cURL will set "Expect: 100-continue" for requests larger than 1024 bytes.
        curl_setopt($curlHandle, CURLOPT_HTTPHEADER, ['Expect:']);

        // If the content is a stream resource, use cURL's INFILE feature to stream it
        $content = $request->getContent();
        if (is_resource($content)) {
            curl_setopt_array($curlHandle,
                [
                    CURLOPT_INFILE => $content,
                    CURLOPT_INFILESIZE => $request->getHeader('Content-Length'),
                ]
            );
        }

        switch ($request->getMethod()) {
            case 'GET':
                if ($request->getContent()) {
                    // workaround because else the request would implicitly fall into POST:
                    curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, 'GET');
                    if (!is_resource($content)) {
                        curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $content);
                    }
                }
            break;
            case 'POST':
                curl_setopt($curlHandle, CURLOPT_POST, true);
                if (!is_resource($content)) {
                    $body = $content !== '' ? $content : http_build_query($request->getArguments());
                    curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $body);
                }
            break;
            case 'PUT':
                curl_setopt($curlHandle, CURLOPT_PUT, true);
                if (!is_resource($content) && $content !== '') {
                    $inFileHandler = fopen('php://temp', 'r+');
                    fwrite($inFileHandler, $request->getContent());
                    rewind($inFileHandler);
                    curl_setopt_array($curlHandle, [
                        CURLOPT_INFILE => $inFileHandler,
                        CURLOPT_INFILESIZE => strlen($request->getContent()),
                    ]);
                }
            break;
            case 'HEAD':
                if (!is_resource($content)) {
                    $body = $content !== '' ? $content : http_build_query($request->getArguments());
                    curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $body);
                }
                curl_setopt($curlHandle, CURLOPT_NOBODY, true);
            break;
            default:
                if (!is_resource($content)) {
                    $body = $content !== '' ? $content : http_build_query($request->getArguments());
                    curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $body);
                }
                curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, $request->getMethod());
        }

        $preparedHeaders = [];
        foreach ($request->getHeaders()->getAll() as $fieldName => $values) {
            foreach ($values as $value) {
                $preparedHeaders[] = $fieldName . ': ' . $value;
            }
        }
        curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $preparedHeaders);

        // curl_setopt($curlHandle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP && CURLPROTO_HTTPS);
        // CURLOPT_UPLOAD

        if ($requestUri->getPort() !== null) {
            curl_setopt($curlHandle, CURLOPT_PORT, $requestUri->getPort());
        }

        if (count($request->getCookies()) > 0) {
            $cookies = [];
            foreach ($request->getCookies() as $cookie) {
                $cookies[] = $cookie->getName() . '=' . $cookie->getValue();
            }
            curl_setopt($curlHandle, CURLOPT_COOKIE, implode('; ', $cookies));
        }

        $curlResult = curl_exec($curlHandle);
        if ($curlResult === false) {
            throw new CurlEngineException(sprintf('cURL reported error code %s with message "%s". Last requested URL was "%s" (%s).', curl_errno($curlHandle), curl_error($curlHandle), curl_getinfo($curlHandle, CURLINFO_EFFECTIVE_URL), $request->getMethod()), 1338906040);
        } elseif (strlen($curlResult) === 0) {
            return false;
        }
        curl_close($curlHandle);

        $response = Http\Helper\ResponseInformationHelper::createFromRaw($curlResult);
        try {
            while (substr($response->getContent(), 0, 5) === 'HTTP/' || $response->getStatusCode() === 100) {
                $response = Http\Response::createFromRaw($response->getContent(), $response);
            }
        } catch (\InvalidArgumentException $e) {
        }

        return $response;
    }
842243
public function activate(Request $request): JsonResponse
    {
        $this->connection->beginTransaction();

        try {
            $user = $this->activationService->activateUser(
                $request->input('token')
            );

            $token = $user->createToken('Personal Access Token');

            $this->connection->commit();
        } catch (\Throwable $exception) {
            $this->connection->rollback();

            report($exception);

            return $this->response->error($exception->getMessage());
        }

        return $this->response->success('OK', (new HCAuthorizeDTO($user, $token))->toArray());
    }
294268
public function add($request)
    {
        if (!$this->AllowAdding || !Injector::inst()->get(Member::class)->canCreate()) {
            return Security::permissionFailure($this, _t(
                'MemberProfiles.CANNOTADDMEMBERS',
                'You cannot add members via this page.'
            ));
        }

        $data = array(
            'Type'    => 'Add',
            'Title'   => _t('MemberProfiles.ADDMEMBER', 'Add Member'),
            'Content' => '',
            'Form'    => $this->AddForm()
        );

        return $this->customise($data);
    }
249152
public function do_request($request)
    {
        $http = [];

        $http['method'] = $request->method;

        $headers = [];
        foreach ($request->headers as $k => $v) {
            $headers[] = is_string($k) ? "$k: $v" : $v;
        }

        if (isset($request->options['proxy'])) {
            $parts = parse_url($request->options['proxy']);
            if ($parts['scheme'] !== 'http') {
                throw new NotSupportedException(['only support http type proxy: `:proxy`', 'proxy' => $request->options['proxy']]);
            }

            if (isset($parts['pass'])) {
                $headers[] = 'Proxy-Authorization: Basic ' . base64_encode($parts['user'] . ':' . $parts['pass']);
            }
            $http['proxy'] = 'tcp://' . $parts['host'] . ':' . (isset($parts['port']) ? $parts['port'] : '80');
        }

        $http['header'] = $headers;

        if (is_string($request->body)) {
            $http['content'] = $request->body;
        } elseif (is_array($request->body)) {
            if (isset($options['Content-Type']) && strpos($request->headers['Content-Type'], 'json') !== false) {
                $http['content'] = json_encode($request->body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            } else {
                $http['content'] = http_build_query($request->body);
            }
        }

        $http['timeout'] = $request->options['timeout'];
        $http['ignore_errors'] = true;

        $ssl = [];
        $ssl['verify_peer'] = $request->options['verify_peer'];
        if (isset($request->options['allow_self_signed'])) {
            $ssl['allow_self_signed'] = $request->options['allow_self_signed'];
        } else {
            $ssl['allow_self_signed'] = !$request->options['verify_peer'];
        }

        if (isset($request->options['cafile'])) {
            $ssl['cafile'] = $this->alias->resolve($request->options['cafile']);
        }

        $start_time = microtime(true);

        if (!$stream = @fopen($request->url, 'rb', false, stream_context_create(['http' => $http, 'ssl' => $ssl]))) {
            throw new ConnectionException(['`:url`: `:last_error_message`', 'url' => $request->url]);
        }
        $meta = stream_get_meta_data($stream);
        $body = stream_get_contents($stream);
        fclose($stream);

        $process_time = round(microtime(true) - $start_time, 3);

        $headers = $meta['wrapper_data'];

        for ($i = count($headers) - 1; $i >= 0; $i--) {
            $header = $headers[$i];
            /** @noinspection NotOptimalIfConditionsInspection */
            if (strpos($header, ':') === false && $headers !== '') {
                break;
            }
        }

        if ($i !== 0) {
            $headers = array_slice($headers, $i);
        }

        $content_type = null;
        foreach ($headers as $header) {
            if (strpos($header, 'Content-Type:') === 0) {
                $content_type = trim(substr($header, 13));
                break;
            }
        }

        $http_code = null;
        if ($headers && preg_match('#\d{3}#', $headers[0], $match)) {
            $http_code = (int)$match[0];
        }

        $response = new Response();
        $response->url = $request->url;
        $response->remote_ip = null;
        $response->http_code = $http_code;
        $response->headers = $headers;
        $response->process_time = 0;
        $response->content_type = $content_type;
        $response->body = $body;
        $response->process_time = $process_time;

        return $response;
    }
862264
public function createPreflightCorsResponse(HttpRequest $request)
    {
        $response = new HttpResponse();
        $response->setStatusCode(200);

        $headers = $response->getHeaders();

        $headers->addHeaderLine('Access-Control-Allow-Origin', $this->getAllowedOriginValue($request));
        $headers->addHeaderLine('Access-Control-Allow-Methods', implode(', ', $this->options->getAllowedMethods()));
        $headers->addHeaderLine('Access-Control-Allow-Headers', implode(', ', $this->options->getAllowedHeaders()));
        $headers->addHeaderLine('Access-Control-Max-Age', $this->options->getMaxAge());
        $headers->addHeaderLine('Content-Length', 0);

        if ($this->options->getAllowedCredentials()) {
            $headers->addHeaderLine('Access-Control-Allow-Credentials', 'true');
        }

        return $response;
    }
197819
public function createToken(Request $request, $providerKey)
    {
        $apiKey = $request->headers->get($this->header);

        if (!$apiKey) {
            throw new BadCredentialsException('No ApiKey found in request!');
        }

        return new PreAuthenticatedToken(
            'unauthorized',
            $apiKey,
            $providerKey
        );
    }
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);
    }
1199642
public function execute($request)
    {
        RequestNotSupportedException::assertSupports($this, $request);
        $details = ArrayObject::ensureArrayObject($request->getModel());

        $httpRequest = new GetHttpRequest();
        $this->gateway->execute($httpRequest);

        if (isset($httpRequest->request['RtnCode']) === true) {
            if ($this->api->verifyHash($httpRequest->request) === false) {
                $httpRequest->request['RtnCode'] = '10400002';
            }
            $details->replace($httpRequest->request);

            return;
        }

        $token = $request->getToken();
        $targetUrl = $token->getTargetUrl();

        if (empty($details['OrderResultURL']) === true) {
            $details['OrderResultURL'] = $targetUrl;
        }

        if (empty($details['ReturnURL']) === true) {
            $notifyToken = $this->tokenFactory->createNotifyToken(
                $token->getGatewayName(), $token->getDetails()
            );
            $details['ReturnURL'] = $notifyToken->getTargetUrl();
        }
        $this->gateway->execute(new CreateTransaction($details));
    }
382269
public function getCredentials(Request $request)
    {
        $tokenExtractor = $this->getTokenExtractor();

        if (!$tokenExtractor instanceof TokenExtractorInterface) {
            throw new \RuntimeException(sprintf('Method "%s::getTokenExtractor()" must return an instance of "%s".', __CLASS__, TokenExtractorInterface::class));
        }

        if (false === ($jsonWebToken = $tokenExtractor->extract($request))) {
            return;
        }

        $preAuthToken = new PreAuthenticationJWTUserToken($jsonWebToken);

        try {
            if (!$payload = $this->jwtManager->decode($preAuthToken)) {
                throw new InvalidTokenException('Invalid JWT Token');
            }

            $preAuthToken->setPayload($payload);
        } catch (JWTDecodeFailureException $e) {
            if (JWTDecodeFailureException::EXPIRED_TOKEN === $e->getReason()) {
                throw new ExpiredTokenException();
            }

            throw new InvalidTokenException('Invalid JWT Token', 0, $e);
        }

        return $preAuthToken;
    }