Skip to content

Commit

Permalink
Support withSubdomain on insecure upgrade routes
Browse files Browse the repository at this point in the history
  • Loading branch information
bajb committed Jan 7, 2022
1 parent 507073d commit 00d9f8d
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 3 deletions.
30 changes: 27 additions & 3 deletions src/Routes/InsecureRequestUpgradeRoute.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,42 @@

class InsecureRequestUpgradeRoute extends Route
{
protected $_subDomain;

public function __construct()
{
$this->add(FuncCondition::i(function (Context $c) { return !$c->request()->isSecure(true); }));
}

/**
* @param string $subDomain
*
* @return InsecureRequestUpgradeRoute
*/
public static function withSubdomain(string $subDomain = 'www'): InsecureRequestUpgradeRoute
{
$i = new static();
$i->_subDomain = trim($subDomain, '.');
return $i;
}

public function getHandler()
{
return new FuncHandler(
function (Context $c) {
return RedirectResponse::create(
str_replace('http:', 'https:', $c->request()->getUri())
);

if($this->_subDomain)
{
$r = $c->request();
if(null !== $qs = $r->getQueryString())
{
$qs = '?' . $qs;
}
$uri = $r->getBaseUrl() . $r->getPathInfo() . $qs;
return RedirectResponse::create("https://" . $this->_subDomain . $r->urlSprintf(".%d.%t%o") . $uri);
}

return RedirectResponse::create(str_replace('http:', 'https:', $c->request()->getUri()));
}
);
}
Expand Down
22 changes: 22 additions & 0 deletions tests/Routes/InsecureRequestUpgradeRouteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,26 @@ public function testHttpsIgnore()
$route = InsecureRequestUpgradeRoute::i();
$this->assertFalse($route->match($ctx));
}

public function testHttpUpgradeWithSubDomainDefault()
{
$ctx = new Context(Request::create('http://google.com/a/b/c/?d=e&f=g'));
$route = InsecureRequestUpgradeRoute::withSubdomain();
$this->assertTrue($route->match($ctx));
/** @var RedirectResponse|null $resp */
$resp = $route->getHandler()->handle($ctx);
$this->assertInstanceOf(RedirectResponse::class, $resp);
$this->assertEquals('https://www.google.com/a/b/c/?d=e&f=g', $resp->getTargetUrl());
}

public function testHttpUpgradeWithSubDomain()
{
$ctx = new Context(Request::create('http://google.com/a/b/c/?d=e&f=g'));
$route = InsecureRequestUpgradeRoute::withSubdomain('secure');
$this->assertTrue($route->match($ctx));
/** @var RedirectResponse|null $resp */
$resp = $route->getHandler()->handle($ctx);
$this->assertInstanceOf(RedirectResponse::class, $resp);
$this->assertEquals('https://secure.google.com/a/b/c/?d=e&f=g', $resp->getTargetUrl());
}
}

0 comments on commit 00d9f8d

Please sign in to comment.