Check if a redirect for SSL is necessary

@param HTTPRequest $request
@return bool
192197
protected function requiresSSL(HTTPRequest $request)
    {
        // Check if force SSL is enabled
        if (!$this->getForceSSL()) {
            return false;
        }

        // Already on SSL
        if ($request->getScheme() === 'https') {
            return false;
        }

        // Veto if any existing patterns fail
        $patterns = $this->getForceSSLPatterns();
        if (!$patterns) {
            return true;
        }

        // Filter redirect based on url
        $relativeURL = $request->getURL(true);
        foreach ($patterns as $pattern) {
            if (preg_match($pattern, $relativeURL)) {
                return true;
            }
        }

        // No patterns match
        return false;
    }
758331
public function isAuthorised( Request $request )
    {
        $header = $request->headers->get( 'Authorization' );
        $context = new Context( EncryptionFactory::create( $this->algorithm ) );

        if ( $header ) {
            try{
                $this->token = $this->jwt->deserialize( $this->extractJwtFromHeader($header) );
            } catch ( \Exception $e ){
                return false;
            }
        }

        if ( $this->algorithm instanceof None ) {
            return false;
        }

        if( $this->isExpired() || !$this->hasUserId() || !$this->isAllowedAppId() ) {
            return false;
        }

        try {
            return $this->jwt->verify( $this->token, $context );
        } catch ( VerificationException $e ) {
            return false;
        }
    }
1358883
private function verifyUpgradeRequest(HttpRequest $request)
    {
        $this->logger->debug("Attempting to switch protocols (checking preconditions per RFC)");

        //That "ifology" is ugly, but I don't have better idea to perform checks

        //Check request to conform with RFC 6455 [see page 16]
        if ($request->getMethod() !== "GET") {
            throw new HttpException("Cannot upgrade to WebSocket - invalid method", HttpCode::METHOD_NOT_ALLOWED);
        }

        if ($request->getProtocolVersion() != 1.1) {
            throw new HttpException("Cannot upgrade to WebSockets - http version not supported",
                HttpCode::VERSION_NOT_SUPPORTED);
        }

        //Intentionally skipped host & origin validation here

        if (strtolower($request->getHeader("upgrade")) !== "websocket") {
            throw new HttpException("Cannot upgrade to WebSockets - invalid upgrade header", HttpCode::BAD_REQUEST);
        }

        if (strpos(strtolower($request->getHeader("connection")), "upgrade") === false) {
            throw new HttpException("Cannot upgrade to WebSockets - invalid connection header", HttpCode::BAD_REQUEST);
        }

        $wsNoonce = base64_decode($request->getHeader("sec-websocket-key"));
        if (strlen($wsNoonce) !== 16) {
            throw new HttpException("Cannot upgrade to WebSockets - invalid key", HttpCode::BAD_REQUEST);
        }

        if (strtolower($request->getHeader("sec-websocket-version")) != self::SUPPORTED_WEBSOCKET_VERSION) {
            throw new HttpException("Cannot upgrade to WebSockets - version not supported", HttpCode::UPGRADE_REQUIRED,
                array("Sec-WebSocket-Version" => self::SUPPORTED_WEBSOCKET_VERSION));
        }

        $this->logger->debug("RFC check OK");
    }
1103696
protected function checkForAlternateVerbs($request)
	{
		$methods = array_diff(Router::$verbs, array($request->getMethod()));

		// Here we will spin through all verbs except for the current request verb and
		// check to see if any routes respond to them. If they do, we will return a
		// proper error response with the correct headers on the response string.
		$others = array();

		foreach ($methods as $method)
		{
			if ( ! is_null($this->check($this->get($method), $request, false)))
			{
				$others[] = $method;
			}
		}

		return $others;
	}
1164381
public function authenticate($request) {
		if(!$this->configured)
			return;
		
		$this->checkValidity();
		
		if($this->via == self::HTTP_HEADER)
			$request->addHeader($this->description->http_header, $this->token);
	}
1333234
public function handleRead(SS_HTTPRequest $request)
    {
        if (!$this->file->canView()) {
            return $this->httpError(403);
        }

        return $this->jsonResponse($this->buildJSON());
    }
628257
public function redirectMatching(Request $request)
    {
        $redirects = $this->storage->getRedirects()->getRedirects();
        $relativeUri = '/' . $request::$relativeUri;

        foreach ($redirects as $redirect) {
            if (preg_match_all($redirect->fromUrl, $relativeUri, $matches)) {
                $toUrl = preg_replace($redirect->fromUrl, $redirect->toUrl, $relativeUri);
                if (substr($toUrl, 0, 1) == '/') {
                    $toUrl = substr($toUrl, 1);
                }
                if ($redirect->type == '301') {
                    header('HTTP/1.1 301 Moved Permanently');
                    header('Location: ' . $request::$subfolders . $toUrl);
                    exit;
                } elseif ($redirect->type == '302') {
                    header('Location: ' . $request::$subfolders . $toUrl, true, 302);
                    exit;
                } else {
                    throw new \Exception('Invalid redirect type.');
                }
            }
        }
    }
305720
public static function is_https($trust_proxy_headers = false)
    {
        // Check standard HTTPS header
        if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
           return isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off';
        }

        // Check proxy headers if allowed
        return $trust_proxy_headers && isset($_SERVER['X-FORWARDED-PROTO']) && $_SERVER['X-FORWARDED-PROTO'] == 'https';

        // Default to not SSL
        return false;
    }
622401
protected function mustReplace($request) : bool
  {
    try {
      foreach ($this->checks as $key => $value) {
        if (starts_with($value, ':')) {
          $this->checks[$key] = config('auth.provider.' . $this->provider . '.' . substr($key, 1));
        }

        if (starts_with($key, ':')) {
          $this->checks = array_replace_key($this->checks, $key, config('auth.provider.' . $this->provider . '.' . substr($key, 1)));
        }
      }

      return true;
    }
    catch (\Exception $e) {
      return false;
    }
  }
867830
public function getRedirectFor(Request $request)
    {
        $redirects = $this->redirector->getRedirectsFor($request);

        collect($redirects)->each(function ($redirects, $missingUrl) {
            $this->router->get($missingUrl, function () use ($redirects, $missingUrl) {
                $redirectUrl = $this->determineRedirectUrl($redirects);
                $statusCode = $this->determineRedirectStatusCode($redirects);

                event(new RouteWasHit($redirectUrl, $missingUrl, $statusCode));

                return redirect()->to(
                    $redirectUrl,
                    $statusCode
                );
            });
        });

        try {
            return $this->router->dispatch($request);
        } catch (Exception $e) {
            event(new RedirectNotFound($request));

            return;
        }
    }
354189
public function confirm(HTTPRequest $request)
    {
        if ($this->EmailType !== 'Confirmation' &&
            $this->EmailType !== 'Validation') {
            return $this->httpError(400, 'No confirmation required.');
        }

        $currentMember = Member::currentUser();
        $id = (int)$request->param('ID');
        $key = $request->getVar('key');

        if ($currentMember) {
            if ($currentMember->ID == $id) {
                return Security::permissionFailure($this, _t(
                    'MemberProfiles.ALREADYCONFIRMED',
                    'Your account is already confirmed.'
                ));
            }
            return Security::permissionFailure($this, _t(
                'MemberProfiles.CANNOTCONFIRMLOGGEDIN',
                'You cannot confirm account while you are logged in.'
            ));
        }

        if (!$id ||
            !$key) {
            return $this->httpError(404);
        }

        $confirmationTitle = $this->data()->dbObject('ConfirmationTitle');

        /**
         * @var Member|null $member
         */
        $member = DataObject::get_by_id(Member::class, $id);
        if (!$member) {
            return $this->invalidRequest('Member #'.$id.' does not exist.');
        }
        if (!$member->NeedsValidation) {
            // NOTE(Jake): 2018-05-03
            //
            // You might be hitting this if you set your MemberProfilePage to use
            // Email Setting 'Confirmation' rather than 'Validation' and you didn't
            // edit the original Email template to not include the copy about confirmation.
            //
            return $this->invalidRequest('Member #'.$id.' does not need validation.');
        }
        if (!$member->ValidationKey) {
            return $this->invalidRequest('Member #'.$id.' does not have a validation key.');
        }
        if ($member->ValidationKey !== $key) {
            return $this->invalidRequest('Validation key does not match.');
        }

        // Allow member to login
        $member->NeedsValidation = false;
        $member->ValidationKey = null;

        $validationResult = $member->validateCanLogin();
        if (!$validationResult->isValid()) {
            $this->getResponse()->setStatusCode(500);
            $validationMessages = $validationResult->getMessages();
            return [
                'Title'   => $confirmationTitle,
                'Content' => $validationMessages ? $validationMessages[0]['message'] : _t('MemberProfiles.ERRORCONFIRMATION', 'An unexpected error occurred.'),
            ];
        }
        $member->write();

        $this->extend('onConfirm', $member);

        if ($member->canLogin()) {
            Injector::inst()->get(IdentityStore::class)->logIn($member);
        } else {
            throw new Exception('Permission issue occurred. Was the "$member->validateCanLogin" check above this code block removed?');
        }

        return [
            'Title'   => $this->data()->dbObject('ConfirmationTitle'),
            'Content' => $this->data()->dbObject('ConfirmationContent')
        ];
    }
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);
	}
1128450
public function getHttpRedirectBindingResponse(AuthnRequest $request = null)
    {
        if (is_null($request)) {
            $request = $this->buildAuthnRequest();
        }

        $context = new MessageContext();
        $context->setMessage($request);

        $binding = (new BindingFactory())->create(SamlConstants::BINDING_SAML2_HTTP_REDIRECT);

        return new RedirectResponse($binding->send($context)->getTargetUrl());
    }
1041159
public function execute($request)
    {
        RequestNotSupportedException::assertSupports($this, $request);

        $model = ArrayObject::ensureArrayObject($request->getModel());

        $model['signature'] = Signer::sign(
            $model->toUnsafeArray(),
            $this->api['secretKey']
        );

        throw new HttpPostRedirect($this->api['endpoint'], $model->toUnsafeArray());
    }
838655
public function allow(Request $request)
    {
        foreach ($this->patterns as $regex)
            if (preg_match(sprintf("#^%s$#i", $regex), $request->getUri()->getPath()))
                return false;

        return true;
    }
191281
protected function getRedirect(HTTPRequest $request)
    {
        // Check global disable
        if (!$this->isEnabled()) {
            return null;
        }

        // Get properties of current request
        $host = $request->getHost();
        $scheme = $request->getScheme();

        // Check https
        if ($this->requiresSSL($request)) {
            $scheme = 'https';

            // Promote ssl domain if configured
            $host = $this->getForceSSLDomain() ?: $host;
        }

        // Check www.
        if ($this->getForceWWW() && strpos($host, 'www.') !== 0) {
            $host = "www.{$host}";
        }

        // No-op if no changes
        if ($request->getScheme() === $scheme && $request->getHost() === $host) {
            return null;
        }

        return $this->redirectToScheme($request, $scheme, $host);
    }
592279
protected static function checkHttpXForwardedProto(Request $request): bool
    {
        return $request->server->has('HTTP_X_FORWARDED_PROTO') && 'https' === $request->server->get('HTTP_X_FORWARDED_PROTO');
    }