This repository has been archived by the owner on Mar 9, 2020. It is now read-only.
/
DoctrineAdapter.php
1603 lines (1406 loc) · 49.6 KB
/
DoctrineAdapter.php
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace ZF\OAuth2\Doctrine\Adapter;
use OAuth2\OpenID\Storage\UserClaimsInterface as OpenIDUserClaimsInterface;
use OAuth2\OpenID\Storage\AuthorizationCodeInterface as OpenIDAuthorizationCodeInterface;
use OAuth2\Storage\AuthorizationCodeInterface;
use OAuth2\Storage\AccessTokenInterface;
use OAuth2\Storage\ClientCredentialsInterface;
use OAuth2\Storage\UserCredentialsInterface;
use OAuth2\Storage\RefreshTokenInterface;
use OAuth2\Storage\JwtBearerInterface;
use OAuth2\Storage\ScopeInterface;
use OAuth2\Storage\PublicKeyInterface;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Zend\Crypt\Password\Bcrypt;
use Zend\Mvc\MvcEvent;
use Zend\ServiceManager\ServiceLocatorInterface;
use ZF\OAuth2\Doctrine\EventListener\DynamicMappingSubscriber;
use DoctrineModule\Persistence\ProvidesObjectManager as ProvidesObjectManagerTrait;
use ZF\OAuth2\Doctrine\Mapper\MapperManager;
use Doctrine\ORM\Mapping\Driver\XmlDriver;
use Zend\Config\Config;
use Exception;
use DateTime;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerAwareTrait;
/**
* Doctrine storage for OAuth2
*
* @author Tom Anderson <tom.h.anderson@gmail.com>
*/
class DoctrineAdapter implements
AuthorizationCodeInterface,
AccessTokenInterface,
ClientCredentialsInterface,
UserCredentialsInterface,
RefreshTokenInterface,
JwtBearerInterface,
ScopeInterface,
PublicKeyInterface,
OpenIDUserClaimsInterface,
OpenIDAuthorizationCodeInterface,
ObjectManagerAwareInterface,
EventManagerAwareInterface
{
use ProvidesObjectManagerTrait;
use EventManagerAwareTrait;
/**
* @var MapperManager
*/
protected $mapperManager;
/**
* @var Bcrypt
*/
protected $bcrypt;
/**
* @var array
*/
protected $config = [];
/**
* @return MapperManager
*/
public function getMapperManager()
{
return $this->mapperManager;
}
/**
* @param MapperManager $manager
* @return $this
*/
public function setMapperManager(MapperManager $manager)
{
$this->mapperManager = $manager;
return $this;
}
/**
* @return Bcrypt
*/
public function getBcrypt()
{
if (null === $this->bcrypt) {
$this->bcrypt = new Bcrypt();
$this->bcrypt->setCost($this->getConfig()->bcrypt_cost);
}
return $this->bcrypt;
}
/**
* Check password using bcrypt
*
* @param string $user
* @param string $password
* @return bool
*/
protected function checkPassword($user, $password)
{
return $this->verifyHash($password, $user['password']);
}
/**
* Check hash using bcrypt
*
* @param $hash
* @param $check
* @return bool
*/
protected function verifyHash($check, $hash)
{
return $this->getBcrypt()->verify($check, $hash);
}
/**
* Set the config for the entities implementing the interfaces
*
* @param Config $config
* @return $this
*/
public function setConfig(Config $config)
{
$this->config = $config;
return $this;
}
/**
* return Config
*/
public function getConfig()
{
return $this->config;
}
/**
* Because the DoctrineAdapter is not created when added to the service
* manager it must be bootstrapped specifically in the onBootstrap event
*
* @param MvcEvent $e
*/
public function bootstrap(MvcEvent $e)
{
/** @var ServiceLocatorInterface $serviceManager */
$serviceManager = $e->getParam('application')->getServiceManager();
// Enable default entities
if (isset($this->getConfig()->enable_default_entities) && $this->getConfig()->enable_default_entities) {
$chain = $serviceManager->get($this->getConfig()->driver);
$chain->addDriver(new XmlDriver(__DIR__ . '/../../config/orm'), 'ZF\OAuth2\Doctrine\Entity');
}
if (isset($this->getConfig()->dynamic_mapping) && $this->getConfig()->dynamic_mapping) {
$userClientSubscriber = new DynamicMappingSubscriber(
$this->getConfig()->dynamic_mapping,
$this->getConfig()->mapping
);
$eventManager = $serviceManager->get($this->getConfig()->event_manager);
$eventManager->addEventSubscriber($userClientSubscriber);
}
}
/* OAuth2\Storage\ClientCredentialsInterface */
/**
* Make sure that the client credentials is valid.
*
* @param string $client_id Client identifier to be check with.
* @param string $client_secret (optional) If a secret is required, check that they've given the right one.
*
* @return bool TRUE if the client credentials are valid, and MUST return FALSE if it isn't.
* @endcode
*
* @see http://tools.ietf.org/html/rfc6749#section-3.1
*
* @ingroup oauth2_section_3
*/
public function checkClientCredentials($client_id, $client_secret = null)
{
$results = $this->getEventManager()->trigger(
__FUNCTION__,
$this,
[
'client_id' => $client_id,
'client_secret' => $client_secret,
]
);
if ($results->stopped()) {
return $results->last();
}
$doctrineClientIdField =
$this->getConfig()->mapping->Client->mapping->client_id->name;
$doctrineClientSecretField =
$this->getConfig()->mapping->Client->mapping->client_secret->name;
$client = $this->getObjectManager()
->getRepository($this->getConfig()->mapping->Client->entity)
->findOneBy([
$doctrineClientIdField => $client_id,
]);
if (! $client) {
return false;
}
$mapper = $this->getMapperManager()->get('Client');
$mapper->exchangeDoctrineArray($client->getArrayCopy());
$data = $mapper->getOAuth2ArrayCopy();
return $this->verifyHash($client_secret, $data['client_secret']);
}
/* OAuth2\Storage\ClientCredentialsInterface */
/**
* Determine if the client is a "public" client, and therefore
* does not require passing credentials for certain grant types
*
* @param string $client_id
* Client identifier to be check with.
*
* @return bool
* TRUE if the client is public, and FALSE if it isn't.
* @endcode
*
* @see http://tools.ietf.org/html/rfc6749#section-2.3
* @see https://github.com/bshaffer/oauth2-server-php/issues/257
*
* @ingroup oauth2_section_2
*/
public function isPublicClient($client_id)
{
$results = $this->getEventManager()->trigger(
__FUNCTION__,
$this,
[
'client_id' => $client_id,
]
);
if ($results->stopped()) {
return $results->last();
}
$doctrineClientIdField =
$this->getConfig()->mapping->Client->mapping->client_id->name;
$client = $this->getObjectManager()
->getRepository($this->getConfig()->mapping->Client->entity)
->findOneBy([
$doctrineClientIdField => $client_id,
]);
if (! $client) {
return false;
}
return ($client->getSecret()) ? false : true;
}
/* OAuth2\Storage\ClientInterface */
/**
* Get client details corresponding client_id.
*
* OAuth says we should store request URIs for each registered client.
* Implement this function to grab the stored URI for a given client id.
*
* @param $client_id
* Client identifier to be check with.
*
* @return array
* Client details. The only mandatory key in the array is "redirect_uri".
* This function MUST return FALSE if the given client does not exist or is
* invalid. "redirect_uri" can be space-delimited to allow for multiple valid uris.
* <code>
* return array(
* "redirect_uri" => REDIRECT_URI, // REQUIRED redirect_uri registered for the client
* "client_id" => CLIENT_ID, // OPTIONAL the client id
* "grant_types" => GRANT_TYPES, // OPTIONAL an array of restricted grant types
* "user_id" => USER_ID, // OPTIONAL the user identifier associated with this client
* "scope" => SCOPE, // OPTIONAL the scopes allowed for this client
* );
* </code>
*
* @ingroup oauth2_section_4
*/
public function getClientDetails($client_id)
{
$results = $this->getEventManager()->trigger(
__FUNCTION__,
$this,
[
'client_id' => $client_id,
]
);
if ($results->stopped()) {
return $results->last();
}
$doctrineClientIdField =
$this->getConfig()->mapping->Client->mapping->client_id->name;
$client = $this->getObjectManager()
->getRepository($this->getConfig()->mapping->Client->entity)
->findOneBy([
$doctrineClientIdField => $client_id,
]);
if (! $client) {
return false;
}
$mapper = $this->getMapperManager()->get('Client');
$mapper->exchangeDoctrineArray($client->getArrayCopy());
$data = $mapper->getOAuth2ArrayCopy();
return $data;
}
/* !!!!! OAuth2\Storage\ClientInterface */
/**
* This function isn't in the interface but called often
*/
public function setClientDetails(
$client_id,
$client_secret = null,
$redirect_uri = null,
$grant_types = null,
$scope = null,
$user_id = null
) {
$results = $this->getEventManager()->trigger(
__FUNCTION__,
$this,
[
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri,
'grant_types' => $grant_types,
'scope' => $scope,
'user_id' => $user_id,
]
);
if ($results->stopped()) {
return $results->last();
}
$doctrineClientIdField =
$this->getConfig()->mapping->Client->mapping->client_id->name;
$client = $this->getObjectManager()
->getRepository($this->getConfig()->mapping->Client->entity)
->findOneBy([
$doctrineClientIdField => $client_id,
]);
if (! $client) {
$clientClass = $this->getConfig()->mapping->Client->entity;
$client = new $clientClass;
$client->setClientId($client_id);
$this->getObjectManager()->persist($client);
}
$scopes = new ArrayCollection;
foreach ((array)$scope as $scopeString) {
$scopes->add($this->getObjectManager()
->getRepository($this->getConfig()->mapping->Scope->entity)
->findOneBy([
$this->getConfig()->mapping->Scope->mapping->scope->name => $scopeString,
]));
}
$client->exchangeArray([
$this->getConfig()->mapping->Client->mapping->client_secret->name => $client_secret,
$this->getConfig()->mapping->Client->mapping->redirect_uri->name => $redirect_uri,
$this->getConfig()->mapping->Client->mapping->grant_types->name => $grant_types,
$this->getConfig()->mapping->Client->mapping->scope->name => $scopes,
]);
$this->getObjectManager()->flush();
return true;
}
/* OAuth2\Storage\ClientInterface */
/**
* Check restricted grant types of corresponding client identifier.
*
* If you want to restrict clients to certain grant types, override this
* function.
*
* @param $client_id
* Client identifier to be check with.
* @param $grant_type
* Grant type to be check with
*
* @return bool
* TRUE if the grant type is supported by this client identifier, and
* FALSE if it isn't.
*
* @ingroup oauth2_section_4
*/
public function checkRestrictedGrantType($client_id, $grant_type)
{
$results = $this->getEventManager()->trigger(
__FUNCTION__,
$this,
[
'client_id' => $client_id,
'grant_type' => $grant_type,
]
);
if ($results->stopped()) {
return $results->last();
}
$doctrineClientIdField =
$this->getConfig()->mapping->Client->mapping->client_id->name;
$client = $this->getObjectManager()
->getRepository($this->getConfig()->mapping->Client->entity)
->findOneBy([
$doctrineClientIdField => $client_id,
]);
if (! $client) {
return false;
}
if ($client->getGrantType()) {
return in_array($grant_type, $client->getGrantType());
}
// @codeCoverageIgnoreStart
// if grant_types are not defined, then none are restricted
return true;
// @codeCoverageIgnoreEnd
}
/* OAuth2\Storage\ClientInterface */
/**
* Get the scope associated with this client
*
* @return
* STRING the space-delineated scope list for the specified client_id
*/
public function getClientScope($client_id)
{
$results = $this->getEventManager()->trigger(
__FUNCTION__,
$this,
[
'client_id' => $client_id,
]
);
if ($results->stopped()) {
return $results->last();
}
$doctrineClientIdField =
$this->getConfig()->mapping->Client->mapping->client_id->name;
$client = $this->getObjectManager()
->getRepository($this->getConfig()->mapping->Client->entity)
->findOneBy([
$doctrineClientIdField => $client_id,
]);
if (! $client) {
return false;
}
$mapper = $this->getMapperManager()->get('Client');
$mapper->exchangeDoctrineArray($client->getArrayCopy());
$data = $mapper->getOAuth2ArrayCopy();
return $data['scope'];
}
/* OAuth2\Storage\AccessTokenInterface */
/**
* Look up the supplied oauth_token from storage.
*
* We need to retrieve access token data as we create and verify tokens.
*
* @param $oauth_token
* oauth_token to be check with.
*
* @return
* An associative array as below, and return NULL if the supplied oauth_token
* is invalid:
* - expires: Stored expiration in unix timestamp.
* - client_id: (optional) Stored client identifier.
* - user_id: (optional) Stored user identifier.
* - scope: (optional) Stored scope values in space-separated string.
* - id_token: (optional) Stored id_token (if "use_openid_connect" is true).
*
* @ingroup oauth2_section_7
*/
public function getAccessToken($access_token)
{
$results = $this->getEventManager()->trigger(
__FUNCTION__,
$this,
[
'access_token' => $access_token,
]
);
if ($results->stopped()) {
return $results->last();
}
$doctrineAccessTokenField =
$this->getConfig()->mapping->AccessToken->mapping->access_token->name;
$accessToken = $this->getObjectManager()
->getRepository($this->getConfig()->mapping->AccessToken->entity)
->findOneBy([
$doctrineAccessTokenField => $access_token,
]);
if (! $accessToken) {
return false;
}
$mapper = $this->getMapperManager()->get('AccessToken');
$mapper->exchangeDoctrineArray($accessToken->getArrayCopy());
$data = $mapper->getOAuth2ArrayCopy();
return $data;
}
/* OAuth2\Storage\AccessTokenInterface */
/**
* Store the supplied access token values to storage.
*
* We need to store access token data as we create and verify tokens.
*
* @param $oauth_token oauth_token to be stored.
* @param $client_id client identifier to be stored.
* @param $user_id user identifier to be stored.
* @param int $expires expiration to be stored as a Unix timestamp.
* @param string $scope OPTIONAL Scopes to be stored in space-separated string.
*
* @ingroup oauth2_section_4
*/
public function setAccessToken(
$access_token,
$client_id,
$user_id,
$expires,
$scope = null
) {
$results = $this->getEventManager()->trigger(
__FUNCTION__,
$this,
[
'access_token' => $access_token,
'client_id' => $client_id,
'user_id' => $user_id,
'expires' => $expires,
'scope' => $scope,
]
);
if ($results->stopped()) {
return $results->last();
}
$doctrineAccessTokenField =
$this->getConfig()->mapping->AccessToken->mapping->access_token->name;
$accessToken = $this->getObjectManager()
->getRepository($this->getConfig()->mapping->AccessToken->entity)
->findOneBy([
$doctrineAccessTokenField => $access_token,
]);
if (! $accessToken) {
$entityClass = $this->getConfig()->mapping->AccessToken->entity;
$accessToken = new $entityClass;
$this->getObjectManager()->persist($accessToken);
}
$mapper = $this->getMapperManager()->get('AccessToken');
$mapper->exchangeOAuth2Array([
'access_token' => $access_token,
'client_id' => $client_id,
'user_id' => $user_id,
'expires' => $expires,
'scope' => $scope,
]);
$accessToken->exchangeArray($mapper->getDoctrineArrayCopy());
$this->getObjectManager()->flush();
return true;
}
/* OAuth2\Storage\AuthorizationCodeInterface */
/**
* Fetch authorization code data (probably the most common grant type).
*
* Retrieve the stored data for the given authorization code.
*
* Required for OAuth2::GRANT_TYPE_AUTH_CODE.
*
* @param $code
* Authorization code to be check with.
*
* @return
* An associative array as below, and NULL if the code is invalid
* @code
* return array(
* "client_id" => CLIENT_ID, // REQUIRED Stored client identifier
* "user_id" => USER_ID, // REQUIRED Stored user identifier
* "expires" => EXPIRES, // REQUIRED Stored expiration in unix timestamp
* "redirect_uri" => REDIRECT_URI, // REQUIRED Stored redirect URI
* "scope" => SCOPE, // OPTIONAL Stored scope values in space-separated string
* );
* @endcode
*
* @see http://tools.ietf.org/html/rfc6749#section-4.1
*
* @ingroup oauth2_section_4
*/
public function getAuthorizationCode($code)
{
$results = $this->getEventManager()->trigger(
__FUNCTION__,
$this,
[
'code' => $code,
]
);
if ($results->stopped()) {
return $results->last();
}
$doctrineAuthorizationCode =
$this->getConfig()->mapping->AuthorizationCode->mapping->authorization_code->name;
$doctrineExpiresField =
$this->getConfig()->mapping->AuthorizationCode->mapping->expires->name;
$queryBuilder = $this->getObjectManager()->createQueryBuilder();
$queryBuilder->select('authorizationCode')
->from($this->getConfig()->mapping->AuthorizationCode->entity, 'authorizationCode')
->andwhere("authorizationCode.$doctrineAuthorizationCode = :code")
->andwhere("authorizationCode.$doctrineExpiresField > :now")
->setParameter('code', $code)
->setParameter('now', new DateTime());
try {
$authorizationCode = $queryBuilder->getQuery()->getSingleResult();
} catch (Exception $e) {
$authorizationCode = false;
}
if (! $authorizationCode) {
return false;
}
$mapper = $this->getMapperManager()->get('AuthorizationCode');
$mapper->exchangeDoctrineArray($authorizationCode->getArrayCopy());
$authorizationCodeClientAssertion = new \ZF\OAuth2\Doctrine\ClientAssertionType\AuthorizationCode();
$authorizationCodeClientAssertion->exchangeArray($mapper->getOAuth2ArrayCopy());
return $authorizationCodeClientAssertion;
}
/* OAuth2\Storage\AuthorizationCodeInterface */
/**
* Take the provided authorization code values and store them somewhere.
*
* This function should be the storage counterpart to getAuthCode().
*
* If storage fails for some reason, we're not currently checking for
* any sort of success/failure, so you should bail out of the script
* and provide a descriptive fail message.
*
* Required for OAuth2::GRANT_TYPE_AUTH_CODE.
*
* @param string $code Authorization code to be stored.
* @param mixed $client_id Client identifier to be stored.
* @param mixed $user_id User identifier to be stored.
* @param string $redirect_uri Redirect URI(s) to be stored in a space-separated string.
* @param int $expires Expiration to be stored as a Unix timestamp.
* @param string $scope OPTIONAL Scopes to be stored in space-separated string.
*
* @ingroup oauth2_section_4
*/
public function setAuthorizationCode(
$code,
$client_id,
$user_id,
$redirect_uri,
$expires,
$scope = null,
$id_token = null
) {
$results = $this->getEventManager()->trigger(
__FUNCTION__,
$this,
[
'code' => $code,
'client_id' => $client_id,
'user_id' => $user_id,
'redirect_uri' => $redirect_uri,
'expires' => $expires,
'scope ' => $scope,
'id_token ' => $id_token,
]
);
if ($results->stopped()) {
return $results->last();
}
$doctrineAuthorizationCodeField =
$this->getConfig()->mapping->AuthorizationCode->mapping->authorization_code->name;
$authorizationCode = $this->getObjectManager()
->getRepository($this->getConfig()->mapping->AuthorizationCode->entity)
->findOneBy([
$doctrineAuthorizationCodeField => $code,
]);
if (! $authorizationCode) {
$entityClass = $this->getConfig()->mapping->AuthorizationCode->entity;
$authorizationCode = new $entityClass;
$this->getObjectManager()->persist($authorizationCode);
}
$mapper = $this->getMapperManager()->get('AuthorizationCode');
$mapper->exchangeOAuth2Array([
'authorization_code' => $code,
'client_id' => $client_id,
'redirect_uri' => $redirect_uri,
'expires' => $expires,
'scope' => $scope,
'id_token' => $id_token,
'user_id' => $user_id,
]);
$authorizationCode->exchangeArray($mapper->getDoctrineArrayCopy());
$this->getObjectManager()->flush();
return true;
}
/* OAuth2\Storage\AuthorizationCodeInterface */
/**
* once an Authorization Code is used, it must be exipired
*
* @see http://tools.ietf.org/html/rfc6749#section-4.1.2
*
* The client MUST NOT use the authorization code
* more than once. If an authorization code is used more than
* once, the authorization server MUST deny the request and SHOULD
* revoke (when possible) all tokens previously issued based on
* that authorization code
*
*/
public function expireAuthorizationCode($code)
{
$results = $this->getEventManager()->trigger(
__FUNCTION__,
$this,
[
'code' => $code,
]
);
if ($results->stopped()) {
return $results->last();
}
$doctrineAuthorizationCodeField =
$this->getConfig()->mapping->AuthorizationCode->mapping->authorization_code->name;
$authorizationCode = $this->getObjectManager()
->getRepository($this->getConfig()->mapping->AuthorizationCode->entity)
->findOneBy([
$doctrineAuthorizationCodeField => $code,
]);
if ($authorizationCode) {
$doctrineExpiresField =
$this->getConfig()->mapping->AuthorizationCode->mapping->expires->name;
$authorizationCode->exchangeArray([
$doctrineExpiresField => new DateTime(), # maybe subtract 1 second?
]);
$this->getObjectManager()->flush();
}
return true;
}
/* OAuth2\Storage\UserCredentialsInterface */
/**
* Grant access tokens for basic user credentials.
*
* Check the supplied username and password for validity.
*
* You can also use the $client_id param to do any checks required based
* on a client, if you need that.
*
* Required for OAuth2::GRANT_TYPE_USER_CREDENTIALS.
*
* @param $username
* Username to be check with.
* @param $password
* Password to be check with.
*
* @return
* TRUE if the username and password are valid, and FALSE if it isn't.
* Moreover, if the username and password are valid, and you want to
*
* @see http://tools.ietf.org/html/rfc6749#section-4.3
*
* @ingroup oauth2_section_4
*/
public function checkUserCredentials($username, $password)
{
$results = $this->getEventManager()->trigger(
__FUNCTION__,
$this,
[
'username' => $username,
'password' => $password,
]
);
if ($results->stopped()) {
return $results->last();
}
$qb = $this->getObjectManager()->createQueryBuilder();
$qb->select(['u'])
->from($this->getConfig()->mapping->User->entity, 'u')
->setParameter('username', $username);
foreach ($this->getConfig()->auth_identity_fields as $field) {
$doctrineField = $this->getConfig()->mapping->User->mapping->$field->name;
$qb->orWhere(sprintf("u.%s = :username", $doctrineField));
}
$user = $qb->getQuery()->getOneOrNullResult();
if ($user) {
$mapper = $this->getMapperManager()->get('User');
$mapper->exchangeDoctrineArray($user->getArrayCopy());
return $this->checkPassword($mapper->getOAuth2ArrayCopy(), $password);
}
return false;
}
/* OAuth2\Storage\UserCredentialsInterface */
/**
* @return
* ARRAY the associated "user_id" and optional "scope" values
* This function MUST return FALSE if the requested user does not exist or is
* invalid. "scope" is a space-separated list of restricted scopes.
* @code
* return array(
* "user_id" => USER_ID, // REQUIRED user_id to be stored with the authorization code or access token
* "scope" => SCOPE // OPTIONAL space-separated list of restricted scopes
* );
* @endcode
*/
public function getUserDetails($username)
{
$results = $this->getEventManager()->trigger(
__FUNCTION__,
$this,
[
'username' => $username,
]
);
if ($results->stopped()) {
return $results->last();
}
$qb = $this->getObjectManager()->createQueryBuilder();
$qb->select(['u'])
->from($this->getConfig()->mapping->User->entity, 'u')
->setParameter('username', $username);
foreach ($this->getConfig()->auth_identity_fields as $field) {
$doctrineField = $this->getConfig()->mapping->User->mapping->$field->name;
$qb->orWhere(sprintf("u.%s = :username", $doctrineField));
}
$user = $qb->getQuery()->getOneOrNullResult();
if ($user) {
$mapper = $this->getMapperManager()->get('User');
$mapper->exchangeDoctrineArray($user->getArrayCopy());
return $mapper->getOAuth2ArrayCopy();
}
return false;
}
/* OAuth2\OpenID\Storage\UserClaimsInterface */
/**
* Return claims about the provided user id.
*
* Groups of claims are returned based on the requested scopes. No group
* is required, and no claim is required.
*
* @param $user_id
* The id of the user for which claims should be returned.
* ## Although the spec says id the rest of the class uses username so I changed this to use username
* @param $scope
* The requested scope.
* Scopes with matching claims: profile, email, address, phone.
*
* @return
* An array in the claim => value format.
*
* @see http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims
*/
public function getUserClaims($username, $scope)
{
$results = $this->getEventManager()->trigger(
__FUNCTION__,
$this,
[
'username' => $username,
'scope' => $scope,
]
);
if ($results->stopped()) {
return $results->last();
}
$doctrineUsernameField = $this->getConfig()->mapping->User->mapping->username->name;
$user = $this->getObjectManager()
->getRepository($this->getConfig()->mapping->User->entity)
->findOneBy([
$doctrineUsernameField => $username,
]);
if (! $user) {
return false;
}
// Return any fields from the user table as an associative array
// which match the constants defined in this class.
switch ($scope) {
case 'profile':
return array_intersect_key(
$user->getArrayCopy(),
array_flip(explode(' ', self::PROFILE_CLAIM_VALUES))
);
break;
case 'email':
return array_intersect_key(
$user->getArrayCopy(),
array_flip(explode(' ', self::EMAIL_CLAIM_VALUES))
);
break;
case 'address':
return array_intersect_key(
$user->getArrayCopy(),
array_flip(explode(' ', self::ADDRESS_CLAIM_VALUES))
);
break;
case 'phone':
return array_intersect_key(
$user->getArrayCopy(),
array_flip(explode(' ', self::PHONE_CLAIM_VALUES))
);
break;
default:
break;
}
return false;
}
/* OAuth2\Storage\RefreshTokenInterface */