diff --git a/src/Http/Request.php b/src/Http/Request.php index 501887b7..52a18bee 100644 --- a/src/Http/Request.php +++ b/src/Http/Request.php @@ -241,6 +241,22 @@ public function getReferer(): ?UrlImmutable } + /** + * What origin did the user come from? It contains scheme, hostname and port. + */ + public function getOrigin(): ?UrlImmutable + { + $header = $this->headers['origin'] ?? 'null'; + try { + return $header === 'null' + ? null + : new UrlImmutable($header); + } catch (Nette\InvalidArgumentException $e) { + return null; + } + } + + /** * Is the request sent via secure channel (https)? */ diff --git a/tests/Http/Request.getOrigin.phpt b/tests/Http/Request.getOrigin.phpt new file mode 100644 index 00000000..819176e6 --- /dev/null +++ b/tests/Http/Request.getOrigin.phpt @@ -0,0 +1,40 @@ +fromGlobals(); + + Assert::null($request->getOrigin()); +}); + + +test('opaque origin', function () { + $_SERVER = [ + 'HTTP_ORIGIN' => 'null', + ]; + $factory = new Http\RequestFactory; + $request = $factory->fromGlobals(); + + Assert::null($request->getOrigin()); +}); + + +test('normal origin', function () { + $_SERVER = [ + 'HTTP_ORIGIN' => 'https://nette.org', + ]; + $factory = new Http\RequestFactory; + $request = $factory->fromGlobals(); + + Assert::equal(new UrlImmutable('https://nette.org'), $request->getOrigin()); +});