1 | <?php |
||
20 | class OAuth2Middleware |
||
21 | { |
||
22 | const AUTH_NAME = 'gigya-oauth2'; |
||
23 | |||
24 | /** @var GrantInterface */ |
||
25 | private $grant; |
||
26 | /** @var string|null */ |
||
27 | private $name; |
||
28 | /** |
||
29 | * @var callable |
||
30 | */ |
||
31 | private $nextHandler; |
||
32 | |||
33 | /** |
||
34 | * @param callable $nextHandler |
||
35 | * @param GrantInterface $grant |
||
36 | * @param string|null $name |
||
37 | */ |
||
38 | 6 | public function __construct(callable $nextHandler, GrantInterface $grant, $name = null) |
|
44 | |||
45 | /** |
||
46 | * @param RequestInterface $request |
||
47 | * @param array $options |
||
48 | * |
||
49 | * @return mixed |
||
50 | */ |
||
51 | 6 | public function __invoke(RequestInterface $request, array $options) |
|
52 | { |
||
53 | 6 | if ($request->getUri()->getScheme() == 'https' && $options['auth'] == $this->name) { |
|
54 | 5 | $token = $this->grant->getToken(); |
|
55 | |||
56 | 5 | if (!is_null($token)) { |
|
57 | 4 | $request = $request->withHeader('Authorization', sprintf('OAuth %s', $token->getToken())); |
|
58 | 4 | } |
|
59 | 5 | } |
|
60 | |||
61 | 6 | $fn = $this->nextHandler; |
|
62 | |||
63 | 6 | return $fn($request, $options) |
|
64 | 6 | ->then($this->refreshToken($request, $options)); |
|
65 | } |
||
66 | |||
67 | /** |
||
68 | * @param RequestInterface $request |
||
69 | * @param array $options |
||
70 | * |
||
71 | * @return Closure A function taking a response and returning a new response|future |
||
72 | */ |
||
73 | 6 | private function refreshToken(RequestInterface $request, array $options) |
|
74 | { |
||
75 | /** |
||
76 | * Take a response and if is required authentication, retry the request. Otherwise passthrough |
||
77 | * |
||
78 | * @param GuzzleResponseInterface $response |
||
79 | * |
||
80 | * @return GuzzleResponseInterface |
||
81 | */ |
||
82 | return function (GuzzleResponseInterface $response) use ($request, $options) { |
||
83 | 4 | if ($response && $response->getStatusCode() == 401) { |
|
84 | 4 | if ($request->getUri()->getScheme() == 'https' |
|
85 | 4 | && $options['auth'] == $this->name |
|
86 | 4 | && (!isset($options['retries']) || $options['retries'] === 0) |
|
87 | 4 | ) { |
|
88 | 2 | $token = $this->grant->getToken(); |
|
89 | 2 | if (!is_null($token)) { |
|
90 | 1 | $options['retries'] = (isset($options['retries'])) ? $options['retries'] + 1 : 1; |
|
91 | 1 | return $this($request, $options); |
|
92 | } |
||
93 | 1 | } |
|
94 | 3 | } |
|
95 | 4 | return $response; |
|
96 | 6 | }; |
|
97 | } |
||
98 | |||
99 | /** |
||
100 | * Return a middleware handler function for OAuth2 Authentication |
||
101 | * |
||
102 | * @param GrantInterface $grant |
||
103 | * @param string|null $name |
||
104 | * |
||
105 | * @return Closure |
||
106 | */ |
||
107 | public static function middleware(GrantInterface $grant, $name = null) |
||
113 | } |
||
114 |