Created
September 10, 2016 03:32
-
-
Save hernandev/e199029666e93f8c653bb07318d469e7 to your computer and use it in GitHub Desktop.
This file contains 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