Forked from hernandev/RedirectIfWrongUrlOrProtocol.php
Created
September 10, 2016 04:14
-
-
Save marcellorg/2833bd2582dfcc8da17f028ce87270ef to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Codecasts\Core\Http\Middleware; | |
use Closure; | |
use Illuminate\Http\Request; | |
class RedirectIfWrongUrlOrProtocol | |
{ | |
/** @var Request */ | |
protected $request; | |
public function handle($request, Closure $next) | |
{ | |
if (!app()->runningInConsole()) { | |
$this->request = $request; | |
$this->trustProxies(); | |
if (!$this->isTheRightDomain() || !$this->isTheRightProtocol()) { | |
return $this->redirect(); | |
} | |
} | |
return $next($request); | |
} | |
protected function trustProxies() | |
{ | |
// trust proxies before anything | |
$this->request->setTrustedProxies($this->request->getClientIps()); | |
} | |
protected function getDomain() | |
{ | |
$root = $this->request->root(); | |
if (str_contains($root, 'http://')) { | |
return str_replace('http://', '', $root); | |
} elseif (str_contains($root, 'https://')) { | |
return str_replace('https://', '', $root); | |
} | |
return $root; | |
} | |
protected function redirect() | |
{ | |
$protocol = config('app.secure') ? 'https://' : 'http://'; | |
$domain = config('app.domain'); | |
$path = $this->request->path() == '/' ? '' : '/'.$this->request->path(); | |
return redirect()->to($protocol.$domain.$path); | |
} | |
protected function isTheRightDomain() | |
{ | |
$defaultDomain = config('app.domain'); | |
$currentDomain = $this->getDomain(); | |
return $defaultDomain == $currentDomain; | |
} | |
protected function isTheRightProtocol() | |
{ | |
$shouldBeSecure = config('app.secure'); | |
$isSecure = $this->request->isSecure(); | |
return $shouldBeSecure == $isSecure; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment