1: <?php
2:
3: namespace Crowdsdom;
4:
5: use Crowdsdom\Client\Exceptions\AuthException;
6: use GuzzleHttp\Client as GuzzleClient;
7: use Psr\Http\Message\RequestInterface;
8:
9: 10: 11: 12:
13: class Auth
14: {
15:
16: const ENDPOINT = '/oauth/token';
17: const GRANT_TYPE = 'client_credentials';
18:
19: 20: 21:
22: protected $host;
23:
24: 25: 26: 27:
28: protected $accessToken;
29:
30: 31: 32:
33: protected $clientId;
34:
35: 36: 37:
38: protected $clientSecret;
39:
40: 41: 42: 43: 44: 45:
46: public function __construct($host, $clientId, $clientSecret)
47: {
48: $this->host = $host;
49: $this->clientId = $clientId;
50: $this->clientSecret = $clientSecret;
51: }
52:
53:
54: public function getAccessToken()
55: {
56:
57: if (!isset($this->accessToken)) {
58: $guzzle = new GuzzleClient([
59: 'verify' => !getenv('CROWDSDOM_TESTING')
60: ]);
61: $response = $guzzle->request('POST', $this->host . self::ENDPOINT, [
62: 'json' => [
63: 'grant_type' => self::GRANT_TYPE,
64: 'client_id' => $this->clientId,
65: 'client_secret' => $this->clientSecret,
66: ]
67: ]);
68:
69: if ($response->getStatusCode() !== 200) {
70: throw AuthException::make($response);
71: }
72:
73: $this->accessToken = json_decode($response->getBody()->getContents(), true);
74: }
75:
76: return $this->accessToken;
77: }
78:
79: public function authMiddleware()
80: {
81: $accessToken = $this->getAccessToken();
82: return function (callable $handler) use ($accessToken) {
83: return function (RequestInterface $request, array $options) use ($handler, $accessToken) {
84: $request = $request->withHeader('Authorization', $accessToken['access_token']['id']);
85: return $handler($request, $options);
86: };
87: };
88: }
89: }
90: