-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.php
More file actions
578 lines (531 loc) · 16 KB
/
Copy pathClient.php
File metadata and controls
578 lines (531 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
<?php
namespace Cymatic;
/**
* Minimal standalone library to work with Cymatic
* Register to get your credentials here: https://cymatic.io
*
* @license MIT
* @url https://cymatic.io
* @author Cymatic
* @package Cymatic
* @copyright Cymatic
*/
class Client
{
/**
* @var string
*/
public static $version = '1.0.0';
/**
* @var int
*/
public static $HTTP_RESPONSE_CODE_CREATED = 201;
/**
* @var int
*/
public static $HTTP_RESPONSE_CODE_OK = 200;
/**
* @var int
*/
protected $requestTimeout = 10;
/**
* @var string
*/
protected $userAgent = 'Cymatic\Client {{version}}';
/**
* Cloud Instance Name
* @var string
*/
protected $tenant;
/**
* Client ID
* @var string
*/
protected $clientId;
/**
* Client secret
* @var string
*/
protected $clientSecret;
/**
* Single sign on endpoint
* @var string
*/
protected $ssoUrl = 'https://sso.cymatic.info/';
/**
* Cymatic Security API endpoint
* @var string
*/
protected $apiUrl = 'https://api.cymaticsecurity.com/';
/**
* Key used to store token in any cache
*
* @var string
*/
protected $tokenCacheKey = "cymatic_security_access_token";
/**
* Caching framework with __get and __set interfaces
*
* @var null|Cache
*/
protected $cache = null;
/**
* Client constructor.
*
* @param $tenant
* @param $clientId
* @param $clientSecret
* @throws \Exception
*/
public function __construct($tenant, $clientId, $clientSecret)
{
if (!$tenant) {
throw new \Exception("Tenant is required");
}
if (!$clientId) {
throw new \Exception("Client ID is required");
}
if (!$clientSecret) {
throw new \Exception("Client Secret is required");
}
$this->tenant = $tenant;
$this->clientId = $clientId;
$this->clientSecret = $clientSecret;
}
/**
* @return string|string[]
*/
public function getUserAgent() {
return str_replace('{{version}}', Client::$version, $this->userAgent);
}
/**
* @param $cache
* @return $this
*/
public function setCache($cache)
{
$this->cache = $cache;
return $this;
}
/**
* Set default timeout for all requests
*
* @param $timeout
* @return Client
*/
public function setTimeout($timeout)
{
$this->requestTimeout = intval($timeout);
return $this;
}
/**
* Setup API url, commonly used for development purposes
*
* @param $apiUrl
* @return Client
* @throws \Exception
*/
public function setAPIUrl($apiUrl)
{
if (!$apiUrl) {
throw new \Exception("API Url is required");
}
$this->apiUrl = $apiUrl;
return $this;
}
/**
* Setup API url, commonly used for development purposes
*
* @param $ssoUrl
* @return Client
* @throws \Exception
*/
public function setSSOUrl($ssoUrl)
{
if (!$ssoUrl) {
throw new \Exception("SSO Url is required");
}
$this->ssoUrl = $ssoUrl;
return $this;
}
/**
* Return final API endpoint regarding API which needs to be called
*
* @param $apiName
* @return string
* @throws \Exception
*/
protected function getAPIUrl($apiName)
{
if (!$apiName) {
throw new \Exception("API name can not be empty");
}
switch ($apiName) {
case "register":
return $this->apiUrl . "profiles";
case "verify":
return $this->apiUrl . "verify";
case "login":
return $this->apiUrl . "login";
case "logout":
return $this->apiUrl . "logout";
case "token":
return str_replace("{{tenant}}", $this->tenant, $this->ssoUrl . "auth/realms/{{tenant}}/protocol/openid-connect/token");
default:
throw new \Exception("API is not supported: " . $apiName);
}
}
/**
* Return basic auth header to use in token retrieval request
*
* @return string
*/
protected function getBasicAuthHeader()
{
return "Basic " . base64_encode($this->clientId . ":" . $this->clientSecret);
}
/**
* Return bearer auth header to use in Authorization header
*
* @return string
* @throws \Exception
*/
protected function getBearerAuthHeader()
{
return "Bearer " . $this->retrieveToken();
}
/**
* Return cached token
*
* @return string
*/
protected function getCachedToken()
{
if ($this->cache) {
return $this->cache->{$this->tokenCacheKey . str_replace('-', '_', $this->clientId)};
}
return '';
}
/**
* Save token in apc cache
* If no apc is available then it doesn't do anything and
* proceed silently as non-critical behavior
*
* @param $token
* @throws \Exception
*/
protected function saveTokenInCache($token)
{
if (!$token) {
throw new \Exception("Token is required");
}
if ($this->cache) {
$this->cache->{$this->tokenCacheKey . str_replace('-', '_', $this->clientId)} = $token;
}
}
/**
* Retrieve token
*
* Method: POST
* URL: {{SSO URL}}/auth/realms/{{tenant}}/protocol/openid-connect/token
* Headers: ["Authorization": "Basic " + access_token]
* Body: {"grant_type": "client_credentials"}
*
* @return string
* @throws \Exception
*/
protected function retrieveToken()
{
try {
// Get cached token
$token = $this->getCachedToken();
if ($token) {
$tokenData = $this->decodeToken($token);
if (time() < $tokenData->exp) {
return $token;
}
}
// Retrieve fresh token
$body = array(
"grant_type" => "client_credentials"
);
$headers = array(
"Authorization: " . $this->getBasicAuthHeader()
);
$options = array(
'isJsonRequest' => false,
'responseCode' => Client::$HTTP_RESPONSE_CODE_OK
);
$response = $this->request('token', $body, $headers, $options);
if (isset($response->access_token)) {
$this->saveTokenInCache($response->access_token);
return $response->access_token;
}
throw new \Exception("Token is empty in SSO response: " . json_encode($response));
} catch (\Exception $exception) {
throw new \Exception("Retrieve token error: " . $exception->getMessage());
}
}
/**
* Register user in Cymatic
*
* Method: POST
* URL: https://{{API URL}}/profiles
* Headers: ["Authorization": "Bearer " + access_token]
* Body: {"jwt": jwt_from_sdk, "alias": any_alias}
*
* @param $sdkJWT
* @param $alias
* @return array|string
* @throws \Exception
*/
public function register($sdkJWT, $alias)
{
try {
if (!$sdkJWT) {
throw new \Exception("SDK JWT should be provided");
}
if (!$alias) {
throw new \Exception("Alias (email) should be provided");
}
$body = array(
"jwt" => $sdkJWT,
"alias" => $alias
);
$headers = array(
"Authorization: " . $this->getBearerAuthHeader()
);
$options = array(
'isJsonRequest' => true,
'responseCode' => Client::$HTTP_RESPONSE_CODE_CREATED
);
return $this->request('register', $body, $headers, $options);
} catch (\Exception $exception) {
throw new \Exception("Registration error: " . $exception->getMessage());
}
}
/**
* Verify registered user in Cymatic
*
* Method: POST
* URL: https://{{API URL}}/verify
* Headers: ["Authorization": "Bearer " + access_token]
* Body: {"jwt": jwt_from_sdk, "c_uuid": c_uuid}
*
* @param $sdkJWT
* @param $c_uuid
* @return array|string
* @throws \Exception
*/
public function verify($sdkJWT, $c_uuid)
{
try {
if (!$sdkJWT) {
throw new \Exception("SDK JWT should be provided");
}
if (!$c_uuid) {
throw new \Exception("c_uuid should be provided");
}
$body = array(
"jwt" => $sdkJWT,
"c_uuid" => $c_uuid
);
$headers = array(
"Authorization: " . $this->getBearerAuthHeader()
);
$options = array(
'isJsonRequest' => true,
'responseCode' => Client::$HTTP_RESPONSE_CODE_CREATED
);
return $this->request('verify', $body, $headers, $options);
} catch (\Exception $exception) {
throw new \Exception("Verification error: " . $exception->getMessage());
}
}
/**
* Login registered and verified user in Cymatic and create session
*
* Method: POST
* URL: https://{{API URL}}/login
* Headers: ["Authorization": "Bearer " + access_token]
* Body: {"jwt": jwt_from_sdk, "c_uuid": c_uuid}
*
* @param $sdkJWT
* @param $c_uuid
* @return array|string
* @throws \Exception
*/
public function login($sdkJWT, $c_uuid)
{
try {
if (!$sdkJWT) {
throw new \Exception("SDK JWT should be provided");
}
if (!$c_uuid) {
throw new \Exception("c_uuid should be provided");
}
$body = array(
"jwt" => $sdkJWT,
"c_uuid" => $c_uuid
);
$headers = array(
"Authorization: " . $this->getBearerAuthHeader()
);
$options = array(
'isJsonRequest' => true,
'responseCode' => Client::$HTTP_RESPONSE_CODE_OK
);
return $this->request('login', $body, $headers, $options);
} catch (\Exception $exception) {
throw new \Exception("Login error: " . $exception->getMessage());
}
}
/**
* Logout user from Cymatic
*
* Method: POST
* URL: https://{{API URL}}/logout
* Headers: ["Authorization": "Bearer " + access_token]
* Body: {"c_uuid": c_uuid, "session_id": session_id }
*
* @param $session_id
* @param $c_uuid
* @return array|string
* @throws \Exception
*/
public function logout($session_id, $c_uuid)
{
try {
if (!$c_uuid) {
throw new \Exception("c_uuid should be provided");
}
if (!$session_id) {
throw new \Exception("session_id should be provided");
}
$body = array(
"c_uuid" => $c_uuid,
"session_id" => $session_id
);
$headers = array(
"Authorization: " . $this->getBearerAuthHeader()
);
$options = array(
'isJsonRequest' => true,
'responseCode' => Client::$HTTP_RESPONSE_CODE_OK
);
return $this->request('logout', $body, $headers, $options);
} catch (\Exception $exception) {
throw new \Exception("Logout error: " . $exception->getMessage());
}
}
/**
* Make actual request to SSO/API endpoints and return data
* Compare returned HTTP code with provided in $options or with 200
* Throw exception if HTTP code does not match or request failed
*
* @param $api
* @param $headers
* @param $body
* @param array $options
* @return array|string
* @throws \Exception
*/
protected function request($api, $body, $headers = array(), $options = array())
{
$ch = null;
try {
// Options
$defaultOptions = array(
'isPostRequest' => true,
'isJsonResponse' => true,
'isJsonRequest' => true,
'responseCode' => Client::$HTTP_RESPONSE_CODE_OK
);
$options = array_merge($defaultOptions, $options);
// Initialize curl
$ch = curl_init($this->getAPIUrl($api));
if ($options['isPostRequest']) {
curl_setopt($ch, CURLOPT_POST, 1);
}
// Body
if (!empty($body)) {
if ($options['isJsonRequest']) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
} else {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($body));
}
}
// Headers
$defaultHeaders = array(
"Accept: application/json"
);
if ($options['isJsonRequest']) {
array_push($defaultHeaders, "Content-type: application/json; charset=utf-8");
} else {
array_push($defaultHeaders, "Content-type: application/x-www-form-urlencoded; charset=utf-8");
}
$headers = array_merge($defaultHeaders, $headers);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Other important options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->requestTimeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->requestTimeout);
curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
$response = curl_exec($ch);
if (curl_errno($ch)) {
throw new \Exception("Error during request: " . curl_error($ch));
}
// Decode JSON
if ($options['isJsonResponse'] && !empty($response)) {
$decodedResponse = json_decode($response);
if (!empty($decodedResponse)) {
$response = $decodedResponse;
}
}
// Check response status code
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($options['responseCode'] !== $httpCode) {
$errorDescription = '';
if (isset($response->error_description)) {
$errorDescription = $response->error_description;
}
if (!$errorDescription && isset($response->error)) {
$errorDescription = $response->error;
}
$errorDescription = $errorDescription ? $errorDescription : ($response ? $response : 'Unknown Error Occurred: ' . $httpCode);
throw new \Exception(json_encode($errorDescription));
}
// Close connection
curl_close($ch);
return $response;
} catch (\Exception $exception) {
throw $exception;
} finally {
// Cleanup things
if ($ch && is_resource($ch)) {
curl_close($ch);
}
}
}
/**
* Decode token and return it's data as associated array
*
* @param $token
* @return mixed
* @throws \Exception
*/
protected function decodeToken($token)
{
if (!$token) {
throw new \Exception("Token can not be empty");
}
try {
$accessToken = explode('.', $token)[1];
return json_decode(base64_decode(str_replace('_', '/', str_replace('-', '+', $accessToken))));
} catch (\Exception $exception) {
throw new \Exception("Provided token have wrong format");
}
}
}