From 64f4ea89be89e9c86c2a2b95d49c458a6c45d8e2 2023-05-15 12:13:54 From: Lance Edgar Date: 2023-05-15 12:13:54 Subject: [PATCH] Add basic HTTP client for Tailbone API with inspiration from https://packagist.org/packages/avency/gitea --- diff --git a/.gitignore b/.gitignore index 57872d0f1e5f46731396e93c4e22b149809798f8..c55784dd284d1872a3371bdbc169522f59baf6c2 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ +composer.lock /vendor/ diff --git a/composer.json b/composer.json index 6db6bee3ef718b6c3d9e93e49f5c26c9e419d58c..da5ccb09bb770b2b5f2563ecbbbfe8bcc0be29be 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,7 @@ { "name": "rattail/posterior", "description": "Tailbone API Client", + "type": "library", "homepage": "https://rattailproject.org", "license": "GPL-3.0-or-later", "autoload": { @@ -14,5 +15,7 @@ "email": "lance@edbob.org" } ], - "require": {} + "require": { + "guzzlehttp/guzzle": "^7.0" + } } diff --git a/src/Client.php b/src/Client.php new file mode 100644 index 0000000000000000000000000000000000000000..85377f87db8e539ec71e37e6148b009619266ae6 --- /dev/null +++ b/src/Client.php @@ -0,0 +1,75 @@ +baseURI = $baseURI; + $parts = parse_url($baseURI); + + $options = [ + 'base_uri' => $baseURI, + 'cookies' => true, + 'headers' => [ + 'Authorization' => "Bearer {$token}", + // TODO: is this a good idea, or hacky security + // risk..? without it, can get error response: 400 + // Client Error: Bad CSRF Origin for url + 'Origin' => "{$parts['scheme']}://{$parts['host']}", + ], + 'verify' => $verifySSL, + ]; + + $this->httpClient = new \GuzzleHttp\Client($options); + $this->inited = false; + } + + private function init() + { + if ($this->inited) { + return; + } + + // fetch 'session' endpoint, to get current xsrf token + $response = $this->get('/session'); + + // look for xsrf token cookie + $jar = $this->httpClient->getConfig('cookies'); + foreach ($jar->toArray() as $cookie) { + + // and save it when found + if ($cookie['Name'] == 'XSRF-TOKEN') { + $this->xsrfToken = $cookie['Value']; + $this->inited = true; + break; + } + } + } + + public function get(string $uri = '', array $options = []): ResponseInterface + { + $uri = $this->baseURI . $uri; + return $this->httpClient->request('GET', $uri, $options); + } + + public function post(string $uri = '', array $data = []): ResponseInterface + { + $this->init(); + $uri = $this->baseURI . $uri; + $options = [ + 'headers' => ['X-XSRF-TOKEN' => $this->xsrfToken], + 'json' => $data, + ]; + return $this->httpClient->request('POST', $uri, $options); + } +}