1
|
|
|
<?php declare (strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace OpenStack\Common\Auth; |
4
|
|
|
|
5
|
|
|
use function GuzzleHttp\Psr7\modify_request; |
6
|
|
|
use Psr\Http\Message\RequestInterface; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* This class is responsible for three tasks: |
10
|
|
|
* |
11
|
|
|
* 1. performing the initial authentication for OpenStack services |
12
|
|
|
* 2. populating the ``X-Auth-Token`` header for every HTTP request |
13
|
|
|
* 3. checking the token expiry before each request, and re-authenticating if necessary |
14
|
|
|
*/ |
15
|
|
|
class AuthHandler |
16
|
|
|
{ |
17
|
|
|
/** @var callable */ |
18
|
|
|
private $nextHandler; |
19
|
|
|
|
20
|
|
|
/** @var callable */ |
21
|
|
|
private $tokenGenerator; |
22
|
|
|
|
23
|
|
|
/** @var Token */ |
24
|
|
|
private $token; |
25
|
|
|
|
26
|
|
|
/** |
27
|
3 |
|
* @param callable $nextHandler |
28
|
|
|
* @param callable $tokenGenerator |
29
|
3 |
|
*/ |
30
|
3 |
|
public function __construct(callable $nextHandler, callable $tokenGenerator, Token $token = null) |
31
|
3 |
|
{ |
32
|
3 |
|
$this->nextHandler = $nextHandler; |
33
|
|
|
$this->tokenGenerator = $tokenGenerator; |
34
|
|
|
$this->token = $token; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* This method is invoked before every HTTP request is sent to the API. When this happens, it |
39
|
|
|
* checks to see whether a token is set and valid, and then sets the ``X-Auth-Token`` header |
40
|
|
|
* for the HTTP request before letting it continue on its merry way. |
41
|
|
|
* |
42
|
|
|
* @param RequestInterface $request |
43
|
|
|
* @param array $options |
44
|
2 |
|
* |
45
|
|
|
* @return mixed|void |
46
|
2 |
|
*/ |
47
|
|
|
public function __invoke(RequestInterface $request, array $options) |
48
|
2 |
|
{ |
49
|
1 |
|
$fn = $this->nextHandler; |
50
|
|
|
|
51
|
|
|
if ($this->shouldIgnore($request)) { |
52
|
1 |
|
return $fn($request, $options); |
53
|
1 |
|
} |
54
|
1 |
|
|
55
|
|
|
if (!$this->token || $this->token->hasExpired()) { |
56
|
1 |
|
$this->token = call_user_func($this->tokenGenerator); |
57
|
|
|
} |
58
|
1 |
|
|
59
|
|
|
$modify = ['set_headers' => ['X-Auth-Token' => $this->token->getId()]]; |
60
|
|
|
|
61
|
|
|
return $fn(modify_request($request, $modify), $options); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* Internal method which prevents infinite recursion. For certain requests, like the initial |
66
|
|
|
* auth call itself, we do NOT want to send a token. |
67
|
|
|
* |
68
|
|
|
* @param RequestInterface $request |
69
|
2 |
|
* |
70
|
|
|
* @return bool |
71
|
2 |
|
*/ |
72
|
|
|
private function shouldIgnore(RequestInterface $request): bool |
73
|
|
|
{ |
74
|
|
|
return strpos((string) $request->getUri(), 'tokens') !== false && $request->getMethod() == 'POST'; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|