Skip to content

Commit cdf1918

Browse files
authored
Merge pull request #7 from skurrilo/feature/client_init
Add Client-Init Method
2 parents 5206caf + 11edc74 commit cdf1918

File tree

3 files changed

+66
-47
lines changed

3 files changed

+66
-47
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,5 @@ composer.lock
66
*.iml
77
.phpunit.result.cache
88
node_modules
9+
phpunit.xml
910

src/Cidaas.php

Lines changed: 65 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -6,67 +6,86 @@
66
use GuzzleHttp\HandlerStack;
77
use GuzzleHttp\Promise\PromiseInterface;
88
use GuzzleHttp\RequestOptions;
9+
use LogicException;
910
use Psr\Http\Message\ResponseInterface;
11+
use UnexpectedValueException;
1012

1113
/**
1214
* Cidaas connector.
1315
* @package Cidaas\OAuth2\Client\Provider
1416
*/
1517
class Cidaas {
16-
private static $well_known_uri = "/.well-known/openid-configuration";
17-
private static $requestIdUri = '/authz-srv/authrequest/authz/generate';
18-
private static $getRegistrationSetupUri = '/registration-setup-srv/public/list';
19-
private static $registerSdkUri = '/users-srv/register';
20-
private static $loginSdkUri = '/login-srv/login/sdk';
21-
private static $changePasswordUri = '/users-srv/changepassword';
22-
private static $updateProfileUriPrefix = '/users-srv/user/profile/';
23-
private static $initiateResetPasswordUri = '/users-srv/resetpassword/initiate';
24-
private static $handleResetPasswordUri = '/users-srv/resetpassword/validatecode';
25-
private static $resetPasswordUri = '/users-srv/resetpassword/accept';
26-
27-
private $openid_config;
28-
private $baseUrl = "";
29-
private $clientId = "";
30-
private $clientSecret = "";
31-
private $redirectUri = "";
32-
private $handler;
33-
private $debug = false;
18+
private static string $well_known_uri = "/.well-known/openid-configuration";
19+
private static string $requestIdUri = '/authz-srv/authrequest/authz/generate';
20+
private static string $getRegistrationSetupUri = '/registration-setup-srv/public/list';
21+
private static string $registerSdkUri = '/users-srv/register';
22+
private static string $loginSdkUri = '/login-srv/login/sdk';
23+
private static string $changePasswordUri = '/users-srv/changepassword';
24+
private static string $updateProfileUriPrefix = '/users-srv/user/profile/';
25+
private static string $initiateResetPasswordUri = '/users-srv/resetpassword/initiate';
26+
private static string $handleResetPasswordUri = '/users-srv/resetpassword/validatecode';
27+
private static string $resetPasswordUri = '/users-srv/resetpassword/accept';
28+
29+
private array $openid_config;
30+
private string $baseUrl = "";
31+
private string $clientId = "";
32+
private string $clientSecret = "";
33+
private string $redirectUri = "";
34+
private HandlerStack $handler;
35+
private bool $debug = false;
36+
/** @var bool has the init method already been called? */
37+
private bool $init = false;
3438

3539
/**
3640
* Cidaas constructor.
3741
* @param string $baseUrl of cidaas server
38-
* @param string $cliendId of cidaas application
42+
* @param string $clientId of cidaas application
3943
* @param string $clientSecret of cidaas application
4044
* @param string $redirectUri to redirect to after login
4145
* @param HandlerStack|null $handler (optional) for http requests
4246
* @param bool $debug (optional) to enable debugging
4347
*/
44-
public function __construct(string $baseUrl, string $cliendId, string $clientSecret, string $redirectUri, HandlerStack $handler = null, bool $debug = false) {
45-
$this->validate($baseUrl, '$baseUrl');
46-
$this->validate($cliendId, '$cliendId');
47-
$this->validate($clientSecret, '$clientSecret');
48-
$this->validate($redirectUri, '$redirectUri');
48+
public function __construct(string $baseUrl, string $clientId, string $clientSecret, string $redirectUri, HandlerStack $handler = null, bool $debug = false) {
49+
$this->validate($baseUrl, 'Base URL');
50+
$this->validate($clientId, 'Client-ID');
51+
$this->validate($clientSecret, 'Client-Secret');
52+
$this->validate($redirectUri, 'Redirect URL');
4953

5054
$this->baseUrl = rtrim($baseUrl, "/");
51-
$this->clientId = $cliendId;
55+
$this->clientId = $clientId;
5256
$this->clientSecret = $clientSecret;
5357
$this->redirectUri = $redirectUri;
5458
if (isset($handler)) {
5559
$this->handler = $handler;
5660
}
5761
$this->debug = $debug;
5862

63+
}
64+
65+
/**
66+
* loads the OpenID config from the server the first time the client is used.
67+
*
68+
* @return void
69+
*/
70+
private function initClient()
71+
{
72+
if($this->init)
73+
{
74+
return;
75+
}
5976
$this->openid_config = $this->loadOpenIdConfig();
77+
$this->init = true;
6078
}
6179

80+
6281
/**
6382
* Retrieve the requestId for a given scope in order to start an oidc interaction.
6483
* @param string $scope for the requestId
6584
* @param string $responseType for the response type
6685
* @param string $acceptLanguage for the language. defaults to "en-GB"
6786
* @return PromiseInterface promise with the requestId or error
6887
*/
69-
public function getRequestId($scope = 'openid', $responseType = 'code', string $acceptLanguage = 'en-GB'): PromiseInterface {
88+
public function getRequestId(string $scope = 'openid', string $responseType = 'code', string $acceptLanguage = 'en-GB'): PromiseInterface {
7089
$client = $this->createClient();
7190

7291
$params = [
@@ -186,11 +205,12 @@ public function loginWithCredentials(string $username, string $username_type, st
186205

187206
/**
188207
* Performs a redirect to the hosted login page.
189-
* @param string scope for login
208+
* @param string $scope for login
190209
* @param array $queryParameters (optional) optionally adds more query parameters to the url.
191-
* @throws \LogicException if no loginUrl has been set
210+
* @throws LogicException if no loginUrl has been set
192211
*/
193212
public function loginWithBrowser(string $scope = 'openid profile offline_access', array $queryParameters = array()) {
213+
$this->initClient();
194214
$loginUrl = $this->openid_config['authorization_endpoint'];
195215
$loginUrl .= '?client_id=' . $this->clientId;
196216
$loginUrl .= '&response_type=code';
@@ -257,7 +277,6 @@ public function changePassword(string $oldPassword, string $newPassword, string
257277
* @return PromiseInterface promise with access token or error
258278
*/
259279
public function getAccessToken(string $grantType, string $code = '', string $refreshToken = ''): PromiseInterface {
260-
$params = [];
261280
if ($grantType === GrantType::AuthorizationCode) {
262281
if (empty($code)) {
263282
throw new \InvalidArgumentException('code must not be empty in authorization_code flow');
@@ -290,9 +309,8 @@ public function getAccessToken(string $grantType, string $code = '', string $ref
290309
throw new \InvalidArgumentException('invalid grant type');
291310
}
292311

293-
$url = $this->openid_config["token_endpoint"];
294-
295312
$client = $this->createClient();
313+
$url = $this->openid_config["token_endpoint"];
296314
$responsePromise = $client->requestAsync('POST', $url, ['form_params' => $params]);
297315
return $responsePromise->then(function (ResponseInterface $response) {
298316
$body = $response->getBody();
@@ -307,12 +325,12 @@ public function getAccessToken(string $grantType, string $code = '', string $ref
307325
* @return PromiseInterface promise with user profile or error
308326
*/
309327
public function getUserProfile(string $accessToken, string $sub = ""): PromiseInterface {
328+
$client = $this->createClient();
310329
$url = $this->openid_config["userinfo_endpoint"];
311330
if (!empty($sub)) {
312331
$url .= "/" . $sub;
313332
}
314333

315-
$client = $this->createClient();
316334
$responsePromise = $client->requestAsync('POST', $url, [
317335
"headers" => [
318336
"Authorization" => "Bearer " . $accessToken,
@@ -489,51 +507,52 @@ public function validateAccessToken(string $accessTokenToValidate, $accessTokenF
489507
* @return PromiseInterface promise with success (redirect) or error message
490508
*/
491509
public function logout(string $accessToken, string $postLogoutUri = ""): PromiseInterface {
510+
$client = $this->createClient();
492511
$url = $this->openid_config["end_session_endpoint"] . "?access_token_hint=" . $accessToken;
493512

494513
if (!empty($postLogoutUri)) {
495514
$url .= "&post_logout_redirect_uri=" . urlencode($postLogoutUri);
496515
}
497516

498-
$client = $this->createClient();
499517
return $client->requestAsync('POST', $url, ['allow_redirects' => false]);
500518
}
501519

502-
private function createClient(): Client {
503-
$client = null;
520+
private function createClient(): Client
521+
{
522+
$this->initClient();
523+
return $this->__createClient();
524+
}
525+
526+
private function __createClient(): Client
527+
{
504528
if (isset($this->handler)) {
505-
$client = new Client(['handler' => $this->handler, 'debug' => $this->debug]);
506-
} else {
507-
$client = new Client(['debug' => $this->debug]);
529+
return new Client(['handler' => $this->handler, 'debug' => $this->debug]);
508530
}
509-
510-
return $client;
531+
return new Client(['debug' => $this->debug]);
511532
}
512533

513534
private function parseJson($content): array {
514535
$content = json_decode($content, true);
515536

516537
if (json_last_error() !== JSON_ERROR_NONE) {
517-
throw new \UnexpectedValueException(sprintf("Failed to parse JSON response: %s", json_last_error_msg()));
538+
throw new UnexpectedValueException(sprintf("Failed to parse JSON response: %s", json_last_error_msg()));
518539
}
519540

520541
return $content;
521542
}
522543

523544
private function validate($param, $name) {
524-
if (!isset($param) || empty($param)) {
545+
if (empty($param)) {
525546
throw new \InvalidArgumentException($name . ' is not specified');
526547
}
527548
}
528549

529550
private function loadOpenIdConfig(): array {
530551
$openid_configuration_url = $this->baseUrl . self::$well_known_uri;
531-
$client = $this->createClient();
532-
$openid_config = $client->getAsync($openid_configuration_url)->then(function (ResponseInterface $response) {
552+
$client = $this->__createClient();
553+
return $client->getAsync($openid_configuration_url)->then(function (ResponseInterface $response) {
533554
$body = $response->getBody();
534555
return $this->parseJson($body);
535556
})->wait();
536-
537-
return $openid_config;
538557
}
539558
}

tests/LoginWithBrowserTest.php

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ protected function setUp(): void {
1414
}
1515

1616
public function test_loginWithBrowser_withRequestId_redirectsToLoginPage() {
17-
$this->mock->reset();
1817
$this->mock->append(new Response(302, ['location' => self::$LOGIN_URL]));
1918

2019
$this->provider->loginWithBrowser();

0 commit comments

Comments
 (0)