1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of graze/gigya-client |
4
|
|
|
* |
5
|
|
|
* Copyright (c) 2016 Nature Delivered Ltd. <https://www.graze.com> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
* |
10
|
|
|
* @license https://github.com/graze/gigya-client/blob/master/LICENSE.md |
11
|
|
|
* @link https://github.com/graze/gigya-client |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Graze\Gigya\Auth\OAuth2; |
15
|
|
|
|
16
|
|
|
use GuzzleHttp\Event\BeforeEvent; |
17
|
|
|
use GuzzleHttp\Event\ErrorEvent; |
18
|
|
|
use GuzzleHttp\Event\RequestEvents; |
19
|
|
|
use GuzzleHttp\Event\SubscriberInterface; |
20
|
|
|
|
21
|
|
|
class Subscriber implements SubscriberInterface |
22
|
|
|
{ |
23
|
|
|
const AUTH_NAME = 'gigya-oauth2'; |
24
|
|
|
|
25
|
|
|
/** @var GrantInterface */ |
26
|
|
|
private $grant; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param GrantInterface $grant |
30
|
|
|
*/ |
31
|
8 |
|
public function __construct(GrantInterface $grant) |
32
|
|
|
{ |
33
|
8 |
|
$this->grant = $grant; |
34
|
8 |
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Returns an array of event names this subscriber wants to listen to. |
38
|
|
|
* |
39
|
|
|
* @return array |
40
|
|
|
*/ |
41
|
1 |
|
public function getEvents() |
42
|
|
|
{ |
43
|
|
|
return [ |
44
|
1 |
|
'before' => ['sign', RequestEvents::SIGN_REQUEST], |
45
|
1 |
|
'error' => ['error', RequestEvents::EARLY], |
46
|
1 |
|
]; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Add the authentication params to the request. |
51
|
|
|
* |
52
|
|
|
* @param BeforeEvent $event |
53
|
|
|
*/ |
54
|
1 |
|
public function sign(BeforeEvent $event) |
55
|
|
|
{ |
56
|
1 |
|
$request = $event->getRequest(); |
57
|
1 |
|
if ($request->getScheme() == 'https' |
58
|
1 |
|
&& $request->getConfig()->get('auth') == static::AUTH_NAME |
59
|
1 |
|
) { |
60
|
1 |
|
$token = $this->grant->getToken(); |
61
|
|
|
|
62
|
1 |
|
if (!is_null($token)) { |
63
|
1 |
|
$request->addHeader('Authorization', sprintf('OAuth %s', $token->getToken())); |
64
|
1 |
|
} |
65
|
1 |
|
} |
66
|
1 |
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param ErrorEvent $event |
70
|
|
|
*/ |
71
|
4 |
|
public function error(ErrorEvent $event) |
72
|
|
|
{ |
73
|
4 |
|
$response = $event->getResponse(); |
74
|
4 |
|
if ($response && $response->getStatusCode() == 401) { |
75
|
3 |
|
$request = $event->getRequest(); |
76
|
3 |
|
if ($request->getScheme() == 'https' |
77
|
3 |
|
&& $request->getConfig()->get('auth') == static::AUTH_NAME |
78
|
3 |
|
&& !$request->getConfig()->get('retried') |
79
|
3 |
|
) { |
80
|
2 |
|
$token = $this->grant->getToken(); |
81
|
2 |
|
if (!is_null($token)) { |
82
|
1 |
|
$request->getConfig()->set('retried', true); |
83
|
1 |
|
$event->intercept($event->getClient()->send($request)); |
84
|
1 |
|
} |
85
|
2 |
|
} |
86
|
3 |
|
} |
87
|
4 |
|
} |
88
|
|
|
} |
89
|
|
|
|