Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcellorg/2833bd2582dfcc8da17f028ce87270ef to your computer and use it in GitHub Desktop.
Save marcellorg/2833bd2582dfcc8da17f028ce87270ef to your computer and use it in GitHub Desktop.
<?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