Skip to content
This repository was archived by the owner on May 28, 2023. It is now read-only.

Commit c464a59

Browse files
committed
Added possibility to get access service with token
1 parent 7cbc965 commit c464a59

File tree

10 files changed

+941
-92
lines changed

10 files changed

+941
-92
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,3 @@
11
/vendor/
2+
/.idea
3+
composer.lock

composer.json

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,19 +12,25 @@
1212
"require": {
1313
"php": ">=5.5.0",
1414
"guzzlehttp/guzzle": "~5.3|~6.0|~6.2",
15-
"illuminate/support": "~5.0|~5.1|~5.2"
15+
"illuminate/support": "~5.0|~5.1|~5.2",
16+
"nesbot/carbon": "^1.21"
1617
},
1718
"require-dev": {
1819
"fzaninotto/faker": "~1.4",
1920
"phpunit/phpunit": "~4.0",
20-
"mockery/mockery": "0.9.*"
21+
"mockery/mockery": "0.9.*",
22+
"symfony/var-dumper": "^3.1"
2123
},
2224
"autoload": {
23-
"classmap": [
24-
"tests/TestCase.php"
25-
],
2625
"psr-4": {
2726
"FindBrok\\WatsonBridge\\" : "src/"
2827
}
29-
}
28+
},
29+
"extra": {
30+
"branch-alias": {
31+
"dev-master": "1.0.x-dev"
32+
}
33+
},
34+
"minimum-stability": "dev",
35+
"prefer-stable": true
3036
}

src/Bridge.php

Lines changed: 172 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,28 @@ class Bridge
4141
*/
4242
protected $client;
4343

44+
/**
45+
* The WatsonToken
46+
*
47+
* @var \FindBrok\WatsonBridge\Token
48+
*/
49+
protected $token;
50+
51+
/**
52+
* Decide which method to use when sending request
53+
*
54+
* @var string
55+
*/
56+
protected $authMethod = 'credentials';
57+
58+
/**
59+
* The limit for which we can re request token,
60+
* when performing request
61+
*
62+
* @var int
63+
*/
64+
protected $exceptionThrottle = 0;
65+
4466
/**
4567
* Default headers
4668
*
@@ -58,14 +80,18 @@ class Bridge
5880
* @param string $password
5981
* @param string $endpoint
6082
*/
61-
public function __construct($username = null, $password = null, $endpoint = null)
83+
public function __construct($username, $password, $endpoint)
6284
{
6385
//Set Username, Password and Endpoint
6486
$this->username = $username;
6587
$this->password = $password;
6688
$this->endpoint = $endpoint;
89+
6790
//Set HttpClient
68-
$this->setClient();
91+
$this->setClient($endpoint);
92+
93+
//Set Token
94+
$this->token = new Token($this->username);
6995
}
7096

7197
/**
@@ -107,16 +133,73 @@ public function getHeaders()
107133
return $this->headers;
108134
}
109135

136+
/**
137+
* Fetch token from Watson and Save it locally
138+
*
139+
* @param bool $incrementThrottle
140+
* @return void
141+
*/
142+
public function fetchToken($incrementThrottle = false)
143+
{
144+
//Increment throttle if needed
145+
if($incrementThrottle) {
146+
$this->incrementThrottle();
147+
}
148+
//Reset Client
149+
$this->setClient($this->getAuthorizationEndpoint());
150+
//Get the token response
151+
$response = $this->get('v1/token', [
152+
'url' => $this->endpoint
153+
]);
154+
//Extract
155+
$token = json_decode($response->getBody()->getContents(), true);
156+
//Reset client
157+
$this->setClient($this->endpoint);
158+
//Update token
159+
$this->token->updateToken($token['token']);
160+
}
161+
162+
/**
163+
* Get a token for authorization from Watson or Storage
164+
*
165+
* @return string
166+
*/
167+
public function getToken()
168+
{
169+
//Token is not valid
170+
if (! $this->token->isValid()) {
171+
//Fetch from Watson
172+
$this->fetchToken();
173+
}
174+
175+
//Return token
176+
return $this->token->getToken();
177+
}
178+
179+
/**
180+
* Get the authorization endpoint for getting tokens
181+
*
182+
* @return string
183+
*/
184+
public function getAuthorizationEndpoint()
185+
{
186+
//Parse the endpoint
187+
$parsedEndpoint = collect(parse_url($this->endpoint));
188+
//Return auth url
189+
return $parsedEndpoint->get('scheme').'://'.$parsedEndpoint->get('host').'/authorization/api/';
190+
}
191+
110192
/**
111193
* Creates the http client
112194
*
195+
* @param string $endpoint
113196
* @return void
114197
*/
115-
private function setClient()
198+
public function setClient($endpoint = null)
116199
{
117200
//Create client using API endpoint
118201
$this->client = new Client([
119-
'base_uri' => $this->endpoint,
202+
'base_uri' => ! is_null($endpoint) ? $endpoint : $this->endpoint,
120203
]);
121204
}
122205

@@ -164,7 +247,7 @@ public function failedRequest($response)
164247
}
165248

166249
/**
167-
* Make a Request to Watson
250+
* Make a Request to Watson with credentials Auth
168251
*
169252
* @param string $method
170253
* @param string $uri
@@ -175,8 +258,17 @@ public function request($method = 'GET', $uri = '', $options = [])
175258
{
176259
try {
177260
//Make the request
178-
return $this->getClient()->request($method, $uri, $options);
261+
return $this->getClient()->request($method, $uri, $this->getRequestOptions($options));
179262
} catch (ClientException $e) {
263+
//We are using token auth and probably token expired
264+
if($this->authMethod == 'token' && $e->getCode() == 401 && ! $this->isThrottledReached()) {
265+
//Try refresh token
266+
$this->fetchToken(true);
267+
//Try requesting again
268+
return $this->request($method, $uri, $options);
269+
}
270+
//Clear throttle for this request
271+
$this->clearThrottle();
180272
//Call Failed Request
181273
$this->failedRequest($e->getResponse());
182274
}
@@ -193,12 +285,8 @@ public function request($method = 'GET', $uri = '', $options = [])
193285
*/
194286
private function send($method = 'POST', $uri, $data, $type = 'json')
195287
{
196-
//Make a Post Request
197-
$response = $this->request($method, $uri, $this->cleanOptions([
198-
'headers' => $this->getHeaders(),
199-
'auth' => $this->getAuth(),
200-
$type => $data
201-
]));
288+
//Make the Request to Watson
289+
$response = $this->request($method, $uri, [$type => $data]);
202290
//Request Failed
203291
if ($response->getStatusCode() != 200) {
204292
//Throw Watson Bridge Exception
@@ -208,6 +296,78 @@ private function send($method = 'POST', $uri, $data, $type = 'json')
208296
return $response;
209297
}
210298

299+
/**
300+
* Get Request options to pass along
301+
*
302+
* @param array $initial
303+
* @return array
304+
*/
305+
public function getRequestOptions($initial = [])
306+
{
307+
//Define options
308+
$options = collect($initial);
309+
//Define an auth option
310+
if($this->authMethod == 'credentials') {
311+
$options = $options->merge([
312+
'auth' => $this->getAuth(),
313+
]);
314+
} elseif ($this->authMethod == 'token') {
315+
$this->appendHeaders([
316+
'X-Watson-Authorization-Token' => $this->getToken()
317+
]);
318+
}
319+
//Put Headers in options
320+
$options = $options->merge([
321+
'headers' => $this->getHeaders(),
322+
]);
323+
//Clean and return
324+
return $this->cleanOptions($options->all());
325+
}
326+
327+
/**
328+
* Change the auth method
329+
*
330+
* @param string $method
331+
* @return self
332+
*/
333+
public function useAuthMethodAs($method = 'credentials')
334+
{
335+
//Change auth method
336+
$this->authMethod = $method;
337+
//Return object
338+
return $this;
339+
}
340+
341+
/**
342+
* Checks if throttle is reached
343+
*
344+
* @return bool
345+
*/
346+
public function isThrottledReached()
347+
{
348+
return $this->exceptionThrottle >= 2;
349+
}
350+
351+
/**
352+
* Increment throttle
353+
*
354+
* @return void
355+
*/
356+
public function incrementThrottle()
357+
{
358+
$this->exceptionThrottle++;
359+
}
360+
361+
/**
362+
* Clears throttle counter
363+
*
364+
* @return void
365+
*/
366+
public function clearThrottle()
367+
{
368+
$this->exceptionThrottle = 0;
369+
}
370+
211371
/**
212372
* Make a GET Request to Watson
213373
*

src/Storage/.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
*
2+
!.gitignore

0 commit comments

Comments
 (0)