Skip to content

Commit d703962

Browse files
committedFeb 27, 2020
Refactor scheme checking
1 parent 8a83ca4 commit d703962

File tree

2 files changed

+17
-21
lines changed

2 files changed

+17
-21
lines changed
 

‎src/Authenticator.php

+15-17
Original file line numberDiff line numberDiff line change
@@ -6,31 +6,29 @@
66

77
class Authenticator {
88
private Cipher $cipher;
9-
private string $httpsScheme = "https";
10-
private string $httpHost;
9+
private UriInterface $baseUri;
1110

12-
public function __construct(Token $token, string $hostname) {
11+
public function __construct(Token $token, string $baseUri) {
1312
$this->cipher = $token->generateCipher();
14-
$this->httpHost = $hostname;
13+
$this->baseUri = $this->normaliseBaseUri($baseUri);
1514
}
1615

17-
public function useLocalhostHttps(bool $useHttps = true) {
18-
if(!$useHttps) {
19-
if($this->httpHost !== "localhost") {
20-
throw new InsecureProtocolException();
21-
}
22-
23-
$this->httpsScheme = "http";
24-
}
16+
public function getAuthUri():UriInterface {
17+
return $this->baseUri;
2518
}
2619

27-
public function getAuthUri():UriInterface {
20+
private function normaliseBaseUri(string $baseUri):Uri {
21+
$scheme = parse_url($baseUri, PHP_URL_SCHEME) ?? "https";
22+
$host = parse_url($baseUri, PHP_URL_HOST) ??
23+
parse_url($baseUri, PHP_URL_PATH);
24+
2825
$uri = (new Uri())
29-
->withScheme("https")
30-
->withHost($this->httpHost);
26+
->withScheme($scheme)
27+
->withHost($host);
3128

32-
if($this->httpHost === "localhost") {
33-
$uri = $uri->withScheme($this->httpsScheme);
29+
if($uri->getHost() !== "localhost"
30+
&& $uri->getScheme() !== "https") {
31+
throw new InsecureProtocolException($uri->getScheme());
3432
}
3533

3634
return $uri;

‎test/phpunit/AuthenticatorTest.php

+2-4
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,7 @@ public function testGetAuthUriHostnameLocalhostHttpAllowed() {
4646
$token->method("generateCipher")
4747
->willReturn($cipher);
4848

49-
$sut = new Authenticator($token, "localhost");
50-
$sut->useLocalhostHttps(false);
49+
$sut = new Authenticator($token, "http://localhost");
5150
$authUri = $sut->getAuthUri();
5251
self::assertStringStartsWith(
5352
"http://localhost",
@@ -62,8 +61,7 @@ public function testGetAuthUriHostnameNotLocalhostHttpNotAllowed() {
6261
$token->method("generateCipher")
6362
->willReturn($cipher);
6463

65-
$sut = new Authenticator($token, "localhost.com");
6664
self::expectException(InsecureProtocolException::class);
67-
$sut->useLocalhostHttps(false);
65+
new Authenticator($token, "http://localhost.com");
6866
}
6967
}

0 commit comments

Comments
 (0)
Please sign in to comment.