forked from SondagesPro/limesurvey-oauth2
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAuthOAuth2.php
More file actions
955 lines (901 loc) · 39.7 KB
/
Copy pathAuthOAuth2.php
File metadata and controls
955 lines (901 loc) · 39.7 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
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
<?php
/* @version 1.5.0 */
require_once(__DIR__ . '/vendor/autoload.php');
use League\OAuth2\Client\Provider\GenericProvider;
use LimeSurvey\PluginManager\AuthPluginBase;
use LimeSurvey\PluginManager\LimesurveyApi;
use LimeSurvey\PluginManager\PluginEvent;
use LimeSurvey\PluginManager\PluginManager;
class AuthOAuth2 extends AuthPluginBase
{
protected const SESSION_STATE_KEY = 'oauth_auth_state';
protected $storage = 'DbStorage';
protected static $name = 'OAuth2 Authentication';
protected static $description = 'Enable Single Sign-On using OAuth2';
protected $resourceData = [];
/* @var array Check getPluginSettings */
protected $settings = [];
public function init(): void
{
$this->subscribe('beforeLogin');
$this->subscribe('beforeLogout');
$this->subscribe('newUserSession');
$this->subscribe('newLoginForm');
$this->subscribe('getGlobalBasePermissions');
}
/**
* @see parent:getPluginSettings
* @param mixed $getValues
*/
public function getPluginSettings($getValues = true)
{
if (!Permission::model()->hasGlobalPermission('settings', 'read')) {
throw new CHttpException(403);
}
/* Definition and default */
$fixedPluginSettings = $this->getFixedGlobalSetting();
$this->settings = [
'client_id' => [
'type' => 'string',
'label' => $this->gT('Client ID'),
'default' => $this->getGlobalSetting('client_id'),
'htmlOptions' => [
'readonly' => in_array('client_id', $fixedPluginSettings)
]
],
'client_secret' => [
'type' => 'string',
'label' => $this->gT('Client Secret'),
'default' => $this->getGlobalSetting('client_secret'),
'htmlOptions' => [
'readonly' => in_array('client_secret', $fixedPluginSettings)
]
],
'redirect_uri' => [
'type' => 'info',
'label' => $this->gT('Redirect URI'),
'content' => CHtml::tag(
'input',
[
'type' => 'text',
'class' => 'form-control',
'readonly' => true,
'value' => $this->api->createUrl('admin/authentication/sa/login', []),
]
),
],
'authorize_url' => [
'type' => 'string',
'label' => $this->gT('Authorize URL'),
'default' => $this->getGlobalSetting('authorize_url'),
'htmlOptions' => [
'readonly' => in_array('authorize_url', $fixedPluginSettings)
]
],
'scopes' => [
'type' => 'string',
'label' => $this->gT('Scopes'),
'help' => $this->gT('Comma-separated list of scopes to use for authorization.'),
'default' => $this->getGlobalSetting('scopes'),
'htmlOptions' => [
'readonly' => in_array('scopes', $fixedPluginSettings)
]
],
'scope_separator' => [
'type' => 'string',
'label' => $this->gT('Scopes separator in URL'),
'help' => $this->gT('Separate scopes in authorization URL.'),
'default' => $this->getGlobalSetting('scope_separator', ','),
'htmlOptions' => [
'readonly' => in_array('scope_separator', $fixedPluginSettings)
]
],
'access_token_url' => [
'type' => 'string',
'label' => $this->gT('Access Token URL'),
'default' => $this->getGlobalSetting('access_token_url', ''),
'htmlOptions' => [
'readonly' => in_array('access_token_url', $fixedPluginSettings)
]
],
'resource_owner_details_url' => [
'type' => 'string',
'label' => $this->gT('User Details URL'),
'help' => $this->gT('URL to load the user details from using the retrieved access token.'),
'default' => $this->getGlobalSetting('resource_owner_details_url', ''),
'htmlOptions' => [
'readonly' => in_array('resource_owner_details_url', $fixedPluginSettings)
]
],
'logout_url' => [
'type' => 'string',
'label' => $this->gT('Logout URL'),
'default' => $this->getGlobalSetting('logout_url', ''),
'htmlOptions' => [
'readonly' => in_array('logout_url', $fixedPluginSettings)
]
],
'identifier_attribute' => [
'type' => 'select',
'label' => $this->gT('Identifier Attribute'),
'help' => $this->gT('Attribute of the LimeSurvey user to match against.'),
'options' => [
'username' => $this->gT('Username'),
'email' => $this->gT('E-Mail'),
],
'default' => $this->getGlobalSetting('identifier_attribute', 'username'),
'htmlOptions' => [
'disabled' => in_array('identifier_attribute', $fixedPluginSettings)
],
'selectOptions' => [
'disabled' => in_array('identifier_attribute', $fixedPluginSettings)
]
],
'username_key' => [
'type' => 'string',
'label' => $this->gT('Key for username in user details'),
'help' => $this->gT('Key for the username in the user details data. Only required if used as "Identifier Attibute" or if "Create new users" is enabled.'),
'default' => $this->getGlobalSetting('username_key', ''),
'htmlOptions' => [
'readonly' => in_array('username_key', $fixedPluginSettings)
]
],
'email_key' => [
'type' => 'string',
'label' => $this->gT('Key for e-mail in user details'),
'help' => $this->gT('Key for the e-mail in the user details data. Only required if used as "Identifier Attibute" or if "Create new users" is enabled.'),
'default' => $this->getGlobalSetting('email_key', ''),
'htmlOptions' => [
'readonly' => in_array('email_key', $fixedPluginSettings)
]
],
'display_name_key' => [
'type' => 'string',
'label' => $this->gT('Key for display name in user details'),
'help' => $this->gT('Key for the full name in the user details data. Only required if "Create new users" is enabled.'),
'default' => $this->getGlobalSetting('display_name_key', ''),
'htmlOptions' => [
'readonly' => in_array('display_name_key', $fixedPluginSettings)
]
],
'is_default' => [
'type' => 'checkbox',
'label' => $this->gT('Use as default login'),
'help' => sprintf(
'%s<br>%s',
$this->gT('If enabled instead of showing the LimeSurvey login the user is redirected directly to the OAuth2 login. The default login form can always be accessed via:'),
htmlspecialchars($this->api->createUrl('admin/authentication/sa/login', ['authMethod' => 'Authdb']))
),
'default' => $this->getGlobalSetting('is_default', false),
'htmlOptions' => [
'disabled' => in_array('is_default', $fixedPluginSettings)
]
],
'autocreate_users' => [
'type' => 'checkbox',
'label' => $this->gT('Create new users'),
'help' => $this->gT('If enabled users that do not exist yet will be created in LimeSurvey after successfull login.'),
'default' => $this->getGlobalSetting('autocreate_users', false),
'htmlOptions' => [
'disabled' => in_array('autocreate_users', $fixedPluginSettings)
]
],
'introduction_text' => [
'type' => 'string',
'label' => $this->gT('Introduction to the OAuth login button.'),
'default' => $this->getGlobalSetting('introduction_text', ''),
'htmlOptions' => [
'placeholder' => $this->gT('Login with OAuth2'),
'readonly' => in_array('introduction_text', $fixedPluginSettings)
]
],
'button_text' => [
'type' => 'string',
'label' => $this->gT('Text on login button.'),
'default' => $this->getGlobalSetting('button_text', ''),
'htmlOptions' => [
'placeholder' => $this->gT('Login'),
'readonly' => in_array('button_text', $fixedPluginSettings)
]
],
'key_separator' => [
'type' => 'string',
'label' => $this->gT('Separate key for user detail'),
'help' => $this->gT('Separate key to get to the user details. Split key by dot notation by default.'),
'default' => $this->getGlobalSetting('key_separator', '.'),
'htmlOptions' => [
'readonly' => in_array('key_separator', $fixedPluginSettings)
]
],
'word_separator' => [
'type' => 'string',
'label' => $this->gT('Separate word key for user detail'),
'help' => $this->gT('Separate word key to get to the user details. Split word key by plus notation by default.'),
'default' => $this->getGlobalSetting('word_separator', '+'),
'htmlOptions' => [
'readonly' => in_array('word_separator', $fixedPluginSettings)
]
],
'display_separator_username' => [
'type' => 'string',
'label' => $this->gT('Display separation if using for username in user details'),
'help' => $this->gT('Separate word key for username. Split by dot notation by default.'),
'default' => $this->getGlobalSetting('display_separator_username', '.'),
'htmlOptions' => [
'readonly' => in_array('display_separator_username', $fixedPluginSettings)
]
],
'display_separator_display_name' => [
'type' => 'string',
'label' => $this->gT('Display separation if using for display name in user details'),
'help' => $this->gT('Separate word key for display name. Split by space notation by default.'),
'default' => $this->getGlobalSetting('display_separator_display_name', ' '),
'htmlOptions' => [
'readonly' => in_array('display_separator_display_name', $fixedPluginSettings)
]
],
'debug' => [
'type' => 'checkbox',
'label' => $this->gT('Activate debugger'),
'help' => $this->gT('Activate debugger'),
'default' => $this->getGlobalSetting('debug', false),
'htmlOptions' => [
'readonly' => in_array('debug', $fixedPluginSettings)
]
]
];
if (method_exists(Permissiontemplates::class, 'applyToUser')) {
$roles = [];
foreach (Permissiontemplates::model()->findAll() as $role) {
$roles[$role->ptid] = $role->name;
}
$this->settings['autocreate_roles'] = [
'type' => 'select',
'label' => $this->gT('Global roles for new users'),
'help' => $this->gT('Global user roles to be assigned to users that are automatically created.'),
'options' => $roles,
'htmlOptions' => [
'multiple' => true,
'disabled' => in_array('autocreate_roles', $fixedPluginSettings)
],
'default' => $this->getGlobalSetting('autocreate_roles', ''),
'selectOptions' => [
'disabled' => in_array('autocreate_roles', $fixedPluginSettings)
]
];
$this->settings['roles_key'] = [
'type' => 'string',
'label' => $this->gT('Key for roles in user detail'),
'help' => $this->gT('Key to get the user roles. Must be an array, if roles exist : it was assigned to the user when it was created.'),
'default' => $this->getGlobalSetting('roles_key', ''),
'htmlOptions' => [
'readonly' => in_array('roles_key', $fixedPluginSettings)
]
];
$this->settings['roles_update'] = [
'type' => 'checkbox',
'label' => $this->gT('Update roles at each log in'),
'help' => $this->gT('Check and update roles each time an user log in.'),
'default' => $this->getGlobalSetting('roles_update', ''),
'htmlOptions' => [
'disabled' => in_array('roles_update', $fixedPluginSettings)
]
];
$this->settings['roles_needed'] = [
'type' => 'checkbox',
'label' => $this->gT('Need a minimum one role to allow log in or create user.'),
'help' => $this->gT('If user didn\'t have any roles : disallow log in.'),
'default' => $this->getGlobalSetting('roles_needed', false),
'htmlOptions' => [
'disabled' => in_array('roles_needed', $fixedPluginSettings)
]
];
$this->settings['roles_to_check'] = [
'type' => 'string',
'label' => $this->gT('Separated Roles Name List'),
'help' => $this->gT('Separated Roles Name List to be compared with user role list. If one is present, allow login. If user didn\'t have at least one of the role : disallow log in. Default separator comma'),
'default' => $this->getGlobalSetting('roles_to_check', ''),
'htmlOptions' => [
'disabled' => in_array('roles_to_check', $fixedPluginSettings)
]
];
$this->settings['roles_to_check_separator'] = [
'type' => 'string',
'label' => $this->gT('Role name list separator'),
'help' => $this->gT('Role name list separator. Default to comma'),
'default' => $this->getGlobalSetting('roles_to_check_separator', ','),
'htmlOptions' => [
'disabled' => in_array('roles_to_check_separator', $fixedPluginSettings)
]
];
$this->settings['roles_removetext'] = [
'type' => 'string',
'label' => $this->gT('Allow you to remove specific string on the roles returned'),
'help' => $this->gT('This string was removed to the roles returned before comparaison.'),
'default' => $this->getGlobalSetting('roles_removetext', ''),
'htmlOptions' => [
'readonly' => in_array('roles_removetext', $fixedPluginSettings)
]
];
$this->settings['roles_insensitive'] = [
'type' => 'checkbox',
'label' => $this->gT('Insensitive comparaison for roles'),
'help' => $this->gT('Do an insensitive comparaison before search the roles.'),
'default' => $this->getGlobalSetting('roles_insensitive', ''),
'htmlOptions' => [
'disabled' => in_array('roles_insensitive', $fixedPluginSettings)
]
];
}
$this->settings['autocreate_permissions'] = [
'type' => 'json',
'label' => $this->gT('Global permissions for new users'),
'help' => sprintf(
$this->gT('A JSON object describing the default permissions to be assigned to users that are automatically created. The JSON object has the following form: %s'),
CHtml::tag('pre', [], "{\n\t\"surveys\": { ... },\n\t\"templates\": {\n\t\t\"create\": false,\n\t\t\"read\": false,\n\t\t\"update\": false,\n\t\t\"delete\": false,\n\t\t\"import\": false,\n\t\t\"export\": false,\n\t},\n\t\"users\": { ... },\n\t...\n}")
),
'editorOptions' => array('mode' => 'tree'),
'default' => $this->getGlobalSetting(
'autocreate_permissions',
self::getDefaultPermission()
),
'htmlOptions' => [
'disabled' => in_array('autocreate_permissions', $fixedPluginSettings)
],
];
/* Get current */
$pluginSettings = parent::getPluginSettings($getValues);
/* Update current for fixed one */
if ($getValues) {
foreach ($fixedPluginSettings as $setting) {
$pluginSettings[$setting]['current'] = $this->getGlobalSetting($setting);
}
}
/* Remove hidden */
foreach ($this->getHiddenGlobalSetting() as $setting) {
unset($pluginSettings[$setting]);
}
return $pluginSettings;
}
public function newLoginForm()
{
$oEvent = $this->getEvent();
$introductionText = viewHelper::purified(trim($this->getGlobalSetting('introduction_text','')));
if (empty($introductionText)) {
$introductionText = $this->gT("Login with Oauth2");
}
$buttonText = viewHelper::purified(trim($this->getGlobalSetting('button_text', '')));
if (empty($buttonText)) {
$buttonText = $this->gT("Login");
}
$aData = [
'introductionText' => $introductionText,
'buttonText' => $buttonText,
];
$authContent = $content = $this->renderPartial('admin.authentication.Oauth2LoginButton', $aData, true);
$allFromsContent = $oEvent->getAllContent();
foreach ($allFromsContent as $plugin => $content) {
$oEvent->getContent($plugin)->addContent($authContent, 'prepend');
}
}
/**
* @throws CHttpException
*/
public function beforeLogin()
{
$debug = (boolean)$this->getGlobalSetting('debug', false);
$request = $this->api->getRequest();
if ($error = $request->getParam('error')) {
throw new CHttpException(401, $request->getParam('error_description', $error));
}
$provider = new GenericProvider([
'clientId' => $this->getGlobalSetting('client_id'),
'clientSecret' => $this->getGlobalSetting('client_secret'),
'redirectUri' => $this->api->createUrl('admin/authentication/sa/login', []),
'urlAuthorize' => $this->getGlobalSetting('authorize_url'),
'urlAccessToken' => $this->getGlobalSetting('access_token_url'),
'urlResourceOwnerDetails' => $this->getGlobalSetting('resource_owner_details_url'),
'scopeSeparator' => $this->getGlobalSetting('scope_separator'),
'scopes' => array_map(
function ($scope) {
return trim($scope);
},
explode(',', $this->getGlobalSetting('scopes', ''))
),
]);
$code = $request->getParam('code');
$defaultAuth = $this->getGlobalSetting('is_default') ? self::class : null;
if (empty($code) && $request->getParam('authMethod', $defaultAuth) !== self::class) {
return;
}
if (empty($code)) {
$authorizationUrl = $provider->getAuthorizationUrl();
Yii::app()->session->add(self::SESSION_STATE_KEY, $provider->getState());
$request->redirect($authorizationUrl);
}
$state = $request->getParam('state');
$safedState = Yii::app()->session->get(self::SESSION_STATE_KEY);
if ($state !== $safedState) {
throw new CHttpException(400, $this->gT('Invalid state in OAuth response'));
}
Yii::app()->session->remove(self::SESSION_STATE_KEY);
try {
$accessToken = $provider->getAccessToken('authorization_code', ['code' => $code]);
if($debug) {
error_log("AccessToken : " . $accessToken);
}
} catch (Throwable $exception) {
error_log($exception);
throw new CHttpException(400, $this->gT('Failed to retrieve access token'));
}
Yii::app()->session['access_token']=$accessToken;
try {
$resourceOwner = $provider->getResourceOwner($accessToken);
$this->resourceData = $resourceOwner->toArray();
} catch (Throwable $exception) {
error_log($exception);
throw new CHttpException(400, $this->gT('Failed to retrieve user details'));
}
if ($this->getGlobalSetting('identifier_attribute') === 'email') {
$identifierKey = $this->getGlobalSetting('email_key');
$userIdentifier = $this->getFromResourceData($identifierKey);
} else {
$identifierKey = $this->getGlobalSetting('username_key');
$identifierSeparator = $this->getGlobalSetting('display_separator_username', '.');
$userIdentifier = $this->getTemplatedKey($identifierKey, $identifierSeparator);
}
if (empty($userIdentifier)) {
throw new CHttpException(400, 'User identifier not found or empty');
}
$this->setUsername($userIdentifier);
$this->setAuthPlugin();
}
/**
* @throws CHttpException
*/
public function newUserSession()
{
$userIdentifier = $this->getUserName();
$identity = $this->getEvent()->get('identity');
if ($identity->plugin != self::class || $identity->username !== $userIdentifier) {
return;
}
$oIdentityEvent = $this->getEvent();
if ($this->getGlobalSetting('identifier_attribute') === 'email') {
$user = $this->api->getUserByEmail($userIdentifier);
} else {
$user = $this->api->getUserByName($userIdentifier);
}
if (!$user && !$this->getGlobalSetting('autocreate_users')) {
if ($this->getGlobalSetting('is_default')) {
$this->beforeLogout();
/* No way to connect : throw a 403 error (avoid looping) */
throw new CHttpException(403, gT('Incorrect username and/or password!'));
} else {
$this->beforeLogout();
$this->setAuthFailure(self::ERROR_AUTH_METHOD_INVALID);
return;
}
}
if ($this->getGlobalSetting('roles_needed', false) && $rolesKey = $this->getGlobalSetting('roles_key', '')) {
$aRoles = $this->getFromResourceData($rolesKey);
$debug = (boolean)$this->getGlobalSetting('debug', false);
if($debug) {
error_log("Data : " . json_encode($aRoles));
}
if (empty($aRoles)) {
if ($this->getGlobalSetting('is_default')) {
$this->beforeLogout();
/* No way to connect : throw a 403 error (avoid looping) */
throw new CHttpException(403, gT('Incorrect username and/or password!'));
} else {
$this->beforeLogout();
$this->setAuthFailure(self::ERROR_AUTH_METHOD_INVALID);
return;
}
}
}
if ($this->getGlobalSetting('roles_to_check', '') != '' && $rolesKey = $this->getGlobalSetting('roles_key', '')) {
$aRoles = $this->getFromResourceData($rolesKey);
$rolesToCheck=explode($this->getGlobalSetting('roles_to_check_separator', ','),$this->getGlobalSetting('roles_to_check', ''));
$debug = (boolean)$this->getGlobalSetting('debug', false);
if($debug) {
error_log("Data : " . json_encode($aRoles));
error_log("rolesToCheck : " . json_encode($rolesToCheck));
}
$incorrectRole=true;
foreach ($rolesToCheck as $role) {
if(in_array($role, $aRoles)) {
$incorrectRole=false;
}
}
if ($incorrectRole) {
if ($this->getGlobalSetting('is_default')) {
$this->beforeLogout();
/* No way to connect : throw a 403 error (avoid looping) */
throw new CHttpException(403, gT('Incorrect role!'));
} else {
$this->beforeLogout();
$this->setAuthFailure(self::ERROR_AUTH_METHOD_INVALID);
return;
}
}
}
if (!$user) {
/* unregister to don't update event */
$this->unsubscribe('getGlobalBasePermissions');
$usernameKey = $this->getGlobalSetting('username_key');
$usernameSeparator = $this->getGlobalSetting('display_separator_username', '.');
$username = $this->getTemplatedKey($usernameKey, $usernameSeparator);
$displayNameKey = $this->getGlobalSetting('display_name_key');
$displayNameSeparator = $this->getGlobalSetting('display_separator_displayname', ' ');
$displayName = $this->getTemplatedKey($displayNameKey, $displayNameSeparator);
$emailKey = $this->getGlobalSetting('email_key');
$email = $this->getFromResourceData($emailKey);
$user = new User();
$user->parent_id = 1;
$user->setPassword(createPassword());
$user->users_name = $username;
$user->full_name = $displayName;
$user->email = $email;
if (!$user->save()) {
throw new CHttpException(401, $this->gT('Failed to create new user'));
}
$defaultPermissions = @json_decode($this->getGlobalSetting('autocreate_permissions', self::getDefaultPermission()), true);
if (!empty($defaultPermissions)) {
Permission::setPermissions($user->uid, 0, 'global', $defaultPermissions, true);
}
/* Add auth_oauth2 permission if not already exist*/
self::setOauthPermission($user->uid, true);
/* Add optional roles */
if (method_exists(Permissiontemplates::class, 'applyToUser')) {
$autocreateRoles = $this->getGlobalSetting('autocreate_roles');
if (!empty($autocreateRoles)) {
foreach ($autocreateRoles as $role) {
Permissiontemplates::model()->applyToUser($user->uid, $role);
}
}
$this->setRolesToUser($user->uid);
}
$this->setUsername($user->users_name);
$this->setAuthSuccess($user, $oIdentityEvent);
} else {
/* Update roles if needed */
if ($this->getGlobalSetting('roles_update', false)) {
UserInPermissionrole::model()->deleteAll("uid = :uid", [':uid' => $user->uid]);
$this->setRolesToUser($user->uid);
}
/* Check for permission */
if (!Permission::model()->hasGlobalPermission('auth_oauth', 'read', $user->uid)) {
/* Check if permission exist : if not create as true, else send error */
$permissionnExist = Permission::model()->findByAttributes([
'entity_id' => 0,
'entity' => 'global',
'uid' => $user->uid,
'permission' => 'auth_oauth'
]);
if (empty($permissionnExist)) {
Permission::model()->setGlobalPermission($user->uid, 'auth_oauth');
} else {
if ($this->getGlobalSetting('is_default')) {
$this->beforeLogout();
/* No way to connect : throw a 403 error (avoid looping) */
throw new CHttpException(403, gT('Incorrect username and/or password!'));
} else {
$this->beforeLogout();
$this->setAuthFailure(self::ERROR_AUTH_METHOD_INVALID);
return;
}
}
}
$this->setUsername($user->users_name);
$this->setAuthSuccess($user);
}
}
/**
* @throws CHttpException
*/
public function beforeLogout(): void
{
$logoutUrl = $this->getGlobalSetting("logout_url");
$clientId = $this->getGlobalSetting("client_id");
$clientSecret = $this->getGlobalSetting("client_secret");
$debug = (boolean)$this->getGlobalSetting('debug', false);
if($debug) {
error_log("LogoutUrl : " . $logoutUrl);
error_log("clientid : " . $clientId);
error_log(json_encode(Yii::app()->session));
}
$accessToken = Yii::app()->session['access_token'];
if (!$accessToken) {
return;
}
$refreshToken = $accessToken->getRefreshToken();
if (!$refreshToken) {
return;
}
if($debug) {
error_log("AccessToken and RefreshToken presents.");
}
$postData = http_build_query([
'client_id' => $clientId,
'client_secret' => $clientSecret,
'refresh_token' => $refreshToken,
]);
$headers = [
'Authorization: Bearer ' . $accessToken,
'Content-Type: application/x-www-form-urlencoded',
];
$ch = curl_init($logoutUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Optionally log the response or check for errors
if (intval($httpCode / 100) !== 2) { // Ok for 200 201 204 etc
error_log("Logout request failed: HTTP $httpCode - $response");
}
// Clear session data after logout
Yii::app()->session->clear();
Yii::app()->session->destroy();
}
public function getGlobalBasePermissions(): void
{
$this->getEvent()->append('globalBasePermissions', array(
'auth_oauth' => array(
'create' => false,
'update' => false,
'delete' => false,
'import' => false,
'export' => false,
'title' => "Use OAuth authentication",
'description' => "Use OAuth authentication",
'img' => 'fa fa-user-circle-o'
),
));
}
/**
* @param string $iKey
* @param string $iSeparator
* @return string
*/
public function getTemplatedKey(string $iKey, string $iSeparator = '.'): string
{
$rValue = '';
$keySeparator = $this->getGlobalSetting('key_separator', '.');
$wordSeparator = $this->getGlobalSetting('word_separator', '+');
if (str_contains($iKey, $keySeparator) || str_contains($iKey, $wordSeparator)) {
$newUsernameKey = '';
$sub_values = array_map(
function ($sub_key) {
return $this->getFromResourceData($sub_key, true);
},
explode($wordSeparator, $iKey)
);
$rValue = join($iSeparator, $sub_values);
} else {
$rValue = $this->getFromResourceData($iKey);
}
return $rValue;
}
/**
* @param string $key
* @param bool $modifier
* @return mixed
*/
private function getFromResourceData(string $key, bool $modifier=false): mixed
{
$keySeparator = $this->getGlobalSetting('key_separator', '.');
$keys = explode($keySeparator, $key); // Split key by dot notation
$value = $this->resourceData;
$debug = (boolean)$this->getGlobalSetting('debug', false);
if($debug) {
error_log("Data : " . json_encode($value));
error_log("Keys : " . json_encode($keys));
}
foreach ($keys as $part) {
if (!is_array($value)) {
if($modifier) {
// Apply modifications if a known modifier exists
if ($part === 'first_letter') {
$value = join('', array_map(fn($word) => strtolower($word[0]), explode(' ', $value)));
} elseif ($part === 'capitalize') {
$value = ucfirst(strtolower($value));
} elseif ($part === 'upper_case') {
$value = strtoupper($value);
} elseif ($part === 'lower_case') {
$value = strtolower($value);
} else {
throw new CHttpException(401, $this->gT('User data or modifier is missing required attributes to create new user:') . $key);
}
} else {
throw new CHttpException(401, $this->gT('User data is missing required attributes to create new user:') . $key);
}
} else {
if (array_key_exists($part, $value)) {
$value = $value[$part]; // Move deeper into the array
} else {
throw new CHttpException(401, $this->gT('User data is missing required attributes to create new user:') . $key);
}
}
}
if($debug) {
error_log("Value : " . json_encode($value));
}
return $value;
}
/**
* get settings according to current DB and fixed config.php
* @param string $setting
* @param mixed $default
* @return mixed
*/
private function getGlobalSetting($setting, $default = null)
{
$AuthOAuth2Settings = App()->getConfig('AuthOAuth2Settings');
if (isset($AuthOAuth2Settings['fixed'][$setting])) {
return $AuthOAuth2Settings['fixed'][$setting];
}
if (isset($AuthOAuth2Settings[$setting])) {
return $this->get($setting, null, null, $AuthOAuth2Settings[$setting]);
}
return $this->get($setting, null, null, $default);
}
/**
* Get the fixed settings name
* @return string[]
*/
private function getFixedGlobalSetting()
{
$AuthOAuth2Setting = App()->getConfig('AuthOAuth2Settings');
if (isset($AuthOAuth2Setting['fixed'])) {
return array_keys($AuthOAuth2Setting['fixed']);
}
return [];
}
/**
* Get the hidden settings name
* @return string[]
*/
private function getHiddenGlobalSetting()
{
$AuthOAuth2Setting = App()->getConfig('AuthOAuth2Settings');
if (isset($AuthOAuth2Setting['hidden'])) {
return $AuthOAuth2Setting['hidden'];
}
return [];
}
/**
* Return global default permission
* @return string
*/
private static function getDefaultPermission()
{
return json_encode([
'surveys' => [
'create' => true,
'read' => false,
'update' => false,
'delete' => false,
'export' => false,
],
'surveysgroups' => [
'create' => false,
'read' => true,
'update' => false,
'delete' => false,
],
'labelsets' => [
'create' => false,
'read' => true,
'update' => false,
'delete' => false,
'import' => false,
'export' => false,
],
'templates' => [
'create' => false,
'read' => true,
'update' => false,
'delete' => false,
'import' => false,
'export' => false,
],
'users' => [
'create' => false,
'read' => false,
'update' => false,
'delete' => false,
],
'usergroups' => [
'create' => false,
'read' => false,
'update' => false,
'delete' => false,
],
'settings' => [
'read' => false,
'update' => false,
'import' => false,
],
'participantpanel' => [
'create' => false,
'read' => false,
'update' => false,
'delete' => false,
'import' => false,
'export' => false,
],
'auth_db' => [
'read' => false,
]
]);
}
/**
* Set the roles using current settings
* @param integer $userId
*/
private function setRolesToUser($userId)
{
$rolesKey = $this->getGlobalSetting('roles_key', '');
if (!empty($rolesKey)) {
$aRoles = $this->getFromResourceData($rolesKey);
if (!empty($aRoles)) {
$resetPermission = false;
$aRoles = (array) $aRoles;
foreach ($aRoles as $role) {
$rolesRemovetext = $this->getGlobalSetting('roles_removetext', '');
$role = str_replace($rolesRemovetext, '', $role);
$criteria = new CDbCriteria();
if ($this->getGlobalSetting('roles_insensitive', false)) {
$criteria->compare('LOWER(name)', strtolower($role), true);
} else {
$criteria->compare('name', $role, true);
}
$oRole = Permissiontemplates::model()->find($criteria);
if ($oRole) {
$resetPermission = true;
Permissiontemplates::model()->applyToUser($userId, $oRole->ptid);
}
}
// Set the auth_oauth global permission to 0 (not used if have roles, but keep it at 0 for roles_needed
if ($resetPermission) {
self::setOauthPermission($userId, false);
}
}
}
}
/**
* Set Oauth permission : use to create permission with 0 ar read_p or update if exist.
* @param integer $userId
* @param boolean $read permission
*/
private static function setOauthPermission($userId, $allow = true)
{
$oPermission = Permission::model()->find(
"uid= :uid AND entity = :entity AND permission = :permission",
array(
'uid' => $userId,
'entity' => 'global',
'permission' => 'auth_oauth',
)
);
if (!$oPermission) {
$oPermission = new Permission();
$oPermission->uid = $userId;
$oPermission->entity = 'global';
$oPermission->entity_id = 0;
$oPermission->permission = 'auth_oauth';
}
$oPermission->create_p = 0;
$oPermission->read_p = intval(boolval($allow));
$oPermission->update_p = 0;
$oPermission->delete_p = 0;
$oPermission->import_p = 0;
$oPermission->export_p = 0;
$oPermission->save();
}
}