-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathopenid_connect.module
1140 lines (1002 loc) · 37.5 KB
/
openid_connect.module
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
/**
* @file
* A pluggable client implementation for the OpenID Connect protocol.
*/
// phpcs:disable Backdrop.Commenting.FunctionComment.TypeHintMissing
/**
* Base path where to login providers can redirect in the OAuth2 flow.
*/
define('OPENID_CONNECT_REDIRECT_PATH_BASE', 'openid-connect');
/**
* Implements hook_menu().
*/
function openid_connect_menu() {
$items = array();
$items['admin/config/services/openid-connect'] = array(
'title' => 'OpenID Connect',
'description' => 'Configure OpenID Connect, choose active OpenID Connect clients etc.',
'page callback' => 'backdrop_get_form',
'page arguments' => array('openid_connect_admin_form'),
'access arguments' => array('configure openid connect clients'),
'file' => 'includes/openid_connect.admin.inc',
);
$items[OPENID_CONNECT_REDIRECT_PATH_BASE . '/%client'] = array(
'title' => 'OpenID Connect redirect page',
'page callback' => 'openid_connect_redirect_page',
'page arguments' => array(1),
'access callback' => 'openid_connect_redirect_access',
'access arguments' => array(1),
'access file' => 'includes/openid_connect.pages.inc',
'type' => MENU_CALLBACK,
'file' => 'includes/openid_connect.pages.inc',
);
$items['user/%user/connected-accounts'] = array(
'title' => 'Connected accounts',
'page callback' => 'backdrop_get_form',
'page arguments' => array('openid_connect_connect_form', 1),
'access callback' => 'openid_connect_connected_accounts_access',
'access arguments' => array(1),
'type' => MENU_LOCAL_TASK,
'weight' => 5,
'file' => 'includes/openid_connect.forms.inc',
);
return $items;
}
/**
* Implements hook_permission().
*/
function openid_connect_permission() {
return array(
'configure openid connect clients' => array(
'title' => t('Configure OpenID Connect clients'),
),
'manage own openid_connect accounts' => array(
'title' => t('Manage own connected accounts'),
),
'openid_connect set own password' => array(
'title' => t('Set a password for local authentication'),
'description' => t('If the account is connected with an external provider, the user needs this permission in order to set their own password.'),
),
);
}
/**
* Implements hook_config_info().
*/
function openid_connect_config_info() {
$prefixes['openid_connect.settings'] = array(
'label' => t('OpenID Connect settings'),
'group' => t('Configuration'),
);
return $prefixes;
}
/**
* Returns a client instance.
*
* @param string $client_name
* The name of the client to instantiate.
*
* @return OpenIDConnectClientInterface
* Client instance.
*/
function openid_connect_get_client($client_name) {
$clients = backdrop_static(__FUNCTION__);
if (!isset($clients[$client_name])) {
$plugin = openid_connect_get_plugin($client_name);
if ($plugin) {
$settings = config_get('openid_connect.settings', 'openid_connect_client_' . $client_name);
// Ensure settings is an array, even if the configuration is empty.
$settings = is_array($settings) ? $settings : array();
$clients[$client_name] = new $plugin['class']($client_name, $plugin['title'], $settings);
}
else {
$clients[$client_name] = FALSE;
}
}
return $clients[$client_name];
}
/**
* Returns an OpenID Connect client plugin.
*
* @param string $client_name
* Name of the plugin.
*
* @return array
* An array with information about the requested operation type plugin.
*/
function openid_connect_get_plugin($client_name) {
$plugins = openid_connect_get_plugins();
return isset($plugins[$client_name]) ? $plugins[$client_name] : NULL;
}
/**
* Returns the available OpenID Connect client plugins.
*
* @param bool $enabled_only
* Whether to return only the plugins enabled by the administrator.
*/
function openid_connect_get_plugins($enabled_only = FALSE) {
$plugins = &backdrop_static(__FUNCTION__);
if (!isset($plugins)) {
$plugins = array();
$config = config('openid_connect.settings');
$clients_enabled = $config->get('openid_connect_clients_enabled') ?: array();
// Look for client plugins in the plugins directory
$plugin_path = backdrop_get_path('module', 'openid_connect') . '/plugins/openid_connect_client';
if (is_dir($plugin_path)) {
$dirs = scandir($plugin_path);
foreach ($dirs as $dir) {
if ($dir[0] != '.' && is_dir($plugin_path . '/' . $dir)) {
$client_name = $dir;
$class_name = 'OpenIDConnectClient' . backdrop_ucfirst($client_name);
// Check for class file
if (file_exists($plugin_path . '/' . $client_name . '/' . $class_name . '.class.php')) {
$plugins[$client_name] = array(
'name' => $client_name,
'title' => backdrop_ucfirst($client_name),
'class' => $class_name,
);
}
}
}
}
}
// Filter plugins based on enabled status if requested
if ($enabled_only) {
$config = config('openid_connect.settings');
$clients_enabled = $config->get('openid_connect_clients_enabled') ?: array();
foreach ($plugins as $client_name => $plugin) {
if (empty($clients_enabled[$client_name])) {
unset($plugins[$client_name]);
}
}
}
return $plugins;
}
/**
* Implements hook_block_info().
*/
function openid_connect_block_info() {
return array(
'openid_connect_login' => array(
'info' => t('OpenID Connect login'),
'cache' => BACKDROP_CACHE_PER_ROLE | BACKDROP_CACHE_PER_PAGE,
),
);
}
/**
* Implements hook_block_view().
*/
function openid_connect_block_view($delta = '') {
if ($delta == 'openid_connect_login' && user_is_anonymous()) {
module_load_include('inc', 'openid_connect', 'includes/openid_connect.forms');
return array(
'subject' => t('Log in'),
'content' => backdrop_get_form('openid_connect_login_form'),
);
}
}
/**
* Creates a state token and stores it in the session for later validation.
*
* @return string
* A state token that later can be validated to prevent request forgery.
*/
function openid_connect_create_state_token() {
watchdog('openid_connect', 'Creating state token in openid_connect_create_state_token', array(), WATCHDOG_DEBUG);
$state = backdrop_random_key();
$_SESSION['openid_connect_state'] = $state;
return $state;
}
/**
* Confirms anti-forgery state token.
*
* @param string $state_token
* The state token that is used for validation.
*
* @return bool
* Whether the state token matches the previously created one that is stored
* in the session.
*/
function openid_connect_confirm_state_token($state_token) {
watchdog('openid_connect', 'Confirming state token in openid_connect_confirm_state_token', array(), WATCHDOG_DEBUG);
$result = isset($_SESSION['openid_connect_state']) && $state_token == $_SESSION['openid_connect_state'];
watchdog('openid_connect', 'State token confirmation result: %result', array('%result' => $result ? 'valid' : 'invalid'), WATCHDOG_DEBUG);
return $result;
}
/**
* Access callback: Connected accounts page.
*/
function openid_connect_connected_accounts_access($account) {
global $user;
if (user_access('administer users')) {
return TRUE;
}
return $user->uid && $user->uid === $account->uid && user_access('manage own openid_connect accounts');
}
/**
* Saves user profile information into a user account.
*/
function openid_connect_save_userinfo($account, $userinfo) {
watchdog('openid_connect', 'Starting to save userinfo in openid_connect_save_userinfo for user: %uid', array('%uid' => $account->uid), WATCHDOG_DEBUG);
$config = config('openid_connect.settings');
$account_wrapper = entity_metadata_wrapper('user', $account);
$properties = $account_wrapper->getPropertyInfo();
$properties_skip = _openid_connect_user_properties_to_skip();
foreach ($properties as $property_name => $property) {
if (isset($properties_skip[$property_name])) {
continue;
}
$claim = $config->get('openid_connect_userinfo_mapping_property_' . $property_name);
if ($claim && isset($userinfo[$claim])) {
try {
$account_wrapper->{$property_name} = $userinfo[$claim];
watchdog('openid_connect', 'Set property %property to %value in openid_connect_save_userinfo',
array('%property' => $property_name, '%value' => $userinfo[$claim]), WATCHDOG_DEBUG);
}
catch (EntityMetadataWrapperException $e) {
watchdog_exception('openid_connect', $e);
}
}
}
if (isset($userinfo['name'])) {
$account->data['oidc_name'] = $userinfo['name'];
watchdog('openid_connect', 'Set oidc_name in openid_connect_save_userinfo: %name', array('%name' => $userinfo['name']), WATCHDOG_DEBUG);
}
$account_wrapper->save();
watchdog('openid_connect', 'Saved account wrapper in openid_connect_save_userinfo', array(), WATCHDOG_DEBUG);
if (config_get('system.performance', 'user_pictures') && $config->get('openid_connect_user_pictures') && !empty($userinfo['picture'])) {
openid_connect_save_user_picture($account, $userinfo['picture']);
}
}
/**
* Save an image as the user picture.
*
* @param object $account
* The user account.
* @param string $picture_url
* The URL to a user picture.
*/
function openid_connect_save_user_picture($account, $picture_url) {
$config = config('openid_connect.settings');
$picture_directory = file_default_scheme() . '://' . config_get('system.performance', 'user_picture_path');
if (!file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY)) {
return;
}
$response = backdrop_http_request($picture_url);
if ($response->code != 200) {
watchdog('openid_connect', 'The user picture could not be fetched from URL: @url', array('@url' => $picture_url));
return;
}
// Skip saving if the remote picture has not changed.
$hash = md5($response->data);
if (!empty($account->picture) && isset($account->data['oidc_picture_hash']) && $account->data['oidc_picture_hash'] === $hash) {
return;
}
$picture_path = file_stream_wrapper_uri_normalize($picture_directory . '/picture-' . $account->uid . '-' . REQUEST_TIME . '.jpg');
$picture_file = file_save_data($response->data, $picture_path, FILE_EXISTS_REPLACE);
// Check to make sure the picture isn't too large for the site settings.
// Suppress the status message that Backdrop sets after a successful resizing.
$status_messages = isset($_SESSION['messages']['status']) ? $_SESSION['messages']['status'] : NULL;
file_validate_image_resolution($picture_file, config_get('system.performance', 'user_picture_dimensions'));
if (isset($status_messages)) {
$_SESSION['messages']['status'] = $status_messages;
}
else {
unset($_SESSION['messages']['status']);
}
// Update the user account object.
$account->picture = $picture_file;
$account->data['oidc_picture_hash'] = $hash;
user_save($account);
// Consider adding file type validation
$file_info = getimagesizefromstring($response->data);
if ($file_info === FALSE) {
watchdog('openid_connect', 'Invalid image file received from URL: @url', array('@url' => $picture_url), WATCHDOG_ERROR);
return;
}
}
/**
* Logs in a user.
*
* @param object $account
* The user account.
* @param string|array &$destination
* The path to redirect to after login.
*/
function openid_connect_login_user($account, $destination) {
watchdog('openid_connect', 'Starting login in openid_connect_login_user for user: %uid', array('%uid' => $account->uid), WATCHDOG_DEBUG);
$form_state['uid'] = $account->uid;
$form = array();
// TFA integration.
if (module_exists('tfa')) {
// The 'code' and 'state' parameters have now been used.
unset($_GET['code'], $_GET['state']);
// TFA will preserve the initial redirect if it is set in the $form_state.
$form_state['redirect'] = $destination;
tfa_login_submit($form, $form_state);
tfa_login_form_redirect($form, $form_state);
// TFA may want to change the redirect destination.
if (isset($form_state['redirect']) && $form_state['redirect'] != 'user/' . $form_state['uid']) {
$destination = $form_state['redirect'];
}
}
else {
watchdog('openid_connect', 'Proceeding with standard login', array(), WATCHDOG_DEBUG);
user_login_submit($form, $form_state);
}
watchdog('openid_connect', 'Completed login in openid_connect_login_user', array(), WATCHDOG_DEBUG);
}
/**
* Save the current path in the session, for redirecting after authorization.
*/
function openid_connect_save_destination() {
watchdog('openid_connect', 'Saving destination in openid_connect_save_destination', array(), WATCHDOG_DEBUG);
$destination = backdrop_get_destination();
$destination = $destination['destination'] == 'user/login' ? 'user' : $destination['destination'];
$parsed = backdrop_parse_url($destination);
$_SESSION['openid_connect_destination'] = array(
$parsed['path'],
array('query' => $parsed['query']),
);
watchdog('openid_connect', 'Saved destination: %path', array('%path' => $parsed['path']), WATCHDOG_DEBUG);
}
/**
* Creates a user indicating sub-id and login provider.
*
* @param string $sub
* The subject identifier.
* @param array $userinfo
* The user claims, containing at least 'email'.
* @param string $client_name
* The machine name of the client.
*
* @return object|false
* The user object or FALSE on failure.
*/
function openid_connect_create_user($sub, $userinfo, $client_name) {
watchdog('openid_connect', 'Creating new user in openid_connect_create_user for sub: %sub', array('%sub' => $sub), WATCHDOG_DEBUG);
$edit = array(
'name' => openid_connect_generate_username($sub, $userinfo, $client_name),
'pass' => user_password(),
'mail' => $userinfo['email'],
'init' => $userinfo['email'],
'status' => 1,
'openid_connect_client' => $client_name,
'openid_connect_sub' => $sub,
);
watchdog('openid_connect', 'User creation data: %data', array('%data' => print_r($edit, TRUE)), WATCHDOG_DEBUG);
$account = user_save(NULL, $edit);
watchdog('openid_connect', 'Created user with uid: %uid', array('%uid' => $account->uid), WATCHDOG_DEBUG);
return $account;
}
/**
* Generate a username for a new account.
*
* @param array $userinfo
* The user claims.
*
* @return string
* A unique username.
*/
function openid_connect_generate_username($sub, $userinfo, $client_name) {
watchdog('openid_connect', 'Generating username in openid_connect_generate_username for sub: %sub', array('%sub' => $sub), WATCHDOG_DEBUG);
$name = 'oidc_' . $client_name . '_' . $sub;
$candidates = array('preferred_username', 'name');
foreach ($candidates as $candidate) {
if (!empty($userinfo[$candidate])) {
$name = $userinfo[$candidate];
watchdog('openid_connect', 'Using %candidate for username: %name',
array('%candidate' => $candidate, '%name' => $name), WATCHDOG_DEBUG);
break;
}
}
backdrop_alter('openid_connect_new_username', $name, $userinfo, $client_name);
$sanitized_name = openid_connect_sanitize_new_username($name);
watchdog('openid_connect', 'Generated sanitized username: %name', array('%name' => $sanitized_name), WATCHDOG_DEBUG);
return $sanitized_name;
}
/**
* Sanitize a username for a new account. The account must not be saved already.
*
* @param string $name
* The new account's proposed username.
*
* @return string
* The sanitized username.
*/
function openid_connect_sanitize_new_username($name) {
watchdog('openid_connect', 'Sanitizing username in openid_connect_sanitize_new_username: %name', array('%name' => $name), WATCHDOG_DEBUG);
$name = preg_replace('/ +/', ' ', trim($name));
$illegal1 = '/[^\x{80}-\x{F7} a-z0-9@_.\'-]/i';
$illegal2 = '/[\x{80}-\x{A0}'
. '\x{AD}'
. '\x{2000}-\x{200F}'
. '\x{2028}-\x{202F}'
. '\x{205F}-\x{206F}'
. '\x{FEFF}'
. '\x{FF01}-\x{FF60}'
. '\x{FFF9}-\x{FFFD}'
. '\x{0}-\x{1F}]'
. '/u';
$name = preg_replace($illegal1, '-', $name);
$name = preg_replace($illegal2, '-', $name);
$name = truncate_utf8($name, USERNAME_MAX_LENGTH, TRUE, FALSE, 20);
for ($original = $name, $i = 1; openid_connect_username_exists($name); $i++) {
$suffix = '_' . $i;
$name = truncate_utf8($original, USERNAME_MAX_LENGTH - strlen($suffix)) . $suffix;
watchdog('openid_connect', 'Username exists, trying with suffix: %name', array('%name' => $name), WATCHDOG_DEBUG);
}
watchdog('openid_connect', 'Final sanitized username: %name', array('%name' => $name), WATCHDOG_DEBUG);
return $name;
}
/**
* Check if a user name already exists.
*
* @param string $name
* A name to test.
*
* @return bool
* TRUE if a user exists with the given name, FALSE otherwise.
*/
function openid_connect_username_exists($name) {
$exists = db_query('SELECT COUNT(*) FROM {users} WHERE name = :name', array(
':name' => $name,
))->fetchField() > 0;
watchdog('openid_connect', 'Checking if username exists: %name - %exists',
array('%name' => $name, '%exists' => $exists ? 'yes' : 'no'), WATCHDOG_DEBUG);
return $exists;
}
/**
* Implements hook_username_alter().
*/
function openid_connect_username_alter($name, $account) {
watchdog('openid_connect', 'Altering username in openid_connect_username_alter: %name', array('%name' => $name), WATCHDOG_DEBUG);
if (!empty($account->data['oidc_name']) && (strpos($name, 'oidc_') === 0 || strpos($name, '@'))) {
$name = $account->data['oidc_name'];
watchdog('openid_connect', 'Using OIDC name instead: %name', array('%name' => $name), WATCHDOG_DEBUG);
}
return $name;
}
/**
* Implements hook_user_insert().
*/
function openid_connect_user_insert($edit, $account, $category) {
if (isset($edit['openid_connect_client'])) {
openid_connect_connect_account($account, $edit['openid_connect_client'], $edit['openid_connect_sub']);
}
}
/**
* Deletes a user's authmap entries.
*/
function openid_connect_authmap_delete($uid) {
db_delete('authmap')
->condition('uid', $uid)
->condition('module', db_like('openid_connect_') . '%', 'LIKE')
->execute();
}
/**
* Implements hook_user_delete().
*/
function openid_connect_user_delete($account) {
openid_connect_authmap_delete($account->uid);
}
/**
* Implements hook_user_cancel().
*/
function openid_connect_user_cancel($edit, $account, $method) {
openid_connect_authmap_delete($account->uid);
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function openid_connect_form_user_profile_form_alter($form, $form_state) {
if (isset($form['account'])) {
$account_form = $form['account'];
}
else {
$account_form = $form;
}
// Do nothing if the user does not have access to password field.
if (isset($account_form['pass']['#access'])
&& !$account_form['pass']['#access']) {
return;
}
if (!openid_connect_set_password_access($form['#user'])) {
$account_form['current_pass']['#access'] = FALSE;
$account_form['current_pass_required_values']['#value'] = array();
$account_form['pass']['#access'] = FALSE;
}
}
/**
* Find whether the user is allowed to change their own password.
*
* @param object $account
* A user account object.
*
* @return bool
* TRUE if access is granted, FALSE otherwise.
*/
function openid_connect_set_password_access($account) {
if (user_access('openid_connect set own password', $account)) {
return TRUE;
}
$connected_accounts = openid_connect_get_connected_accounts($account);
return empty($connected_accounts);
}
/**
* Loads a user based on a sub-id and a login provider.
*/
function openid_connect_user_load_by_sub($sub, $client_name) {
watchdog('openid_connect', 'Loading user by sub in openid_connect_user_load_by_sub: %sub', array('%sub' => $sub), WATCHDOG_DEBUG);
$result = db_select('authmap', 'a')
->fields('a', array('uid', 'module'))
->condition('authname', $sub)
->condition('module', 'openid_connect_' . $client_name)
->execute()
->fetchAssoc();
if ($result) {
$account = user_load($result['uid']);
if (is_object($account)) {
watchdog('openid_connect', 'Found user with uid: %uid', array('%uid' => $account->uid), WATCHDOG_DEBUG);
return $account;
}
}
watchdog('openid_connect', 'No user found for sub: %sub', array('%sub' => $sub), WATCHDOG_DEBUG);
return FALSE;
}
/**
* Returns OpenID Connect claims.
*
* This defines the standard claims, and allows them to be extended via an
* alter hook.
*
* @see http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
* @see http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims
*
* @return array
* Set of standard claims.
*/
function openid_connect_claims() {
$claims = array(
'name' => array(
'scope' => 'profile',
),
'family_name' => array(
'scope' => 'profile',
),
'given_name' => array(
'scope' => 'profile',
),
'middle_name' => array(
'scope' => 'profile',
),
'nickname' => array(
'scope' => 'profile',
),
'preferred_username' => array(
'scope' => 'profile',
),
'profile' => array(
'scope' => 'profile',
),
'picture' => array(
'scope' => 'profile',
),
'website' => array(
'scope' => 'profile',
),
'gender' => array(
'scope' => 'profile',
),
'birthdate' => array(
'scope' => 'profile',
),
'zoneinfo' => array(
'scope' => 'profile',
),
'locale' => array(
'scope' => 'profile',
),
'updated_at' => array(
'scope' => 'profile',
),
'email' => array(
'scope' => 'email',
),
'email_verified' => array(
'scope' => 'email',
),
'address' => array(
'scope' => 'address',
),
'phone_number' => array(
'scope' => 'phone',
),
'phone_number_verified' => array(
'scope' => 'phone',
),
);
backdrop_alter(__FUNCTION__, $claims);
return $claims;
}
/**
* Returns OpenID Connect standard Claims as a Form API options array.
*/
function openid_connect_claims_options() {
$options = array();
foreach (openid_connect_claims() as $claim_name => $claim) {
$options[$claim['scope']][$claim_name] = $claim_name;
}
return $options;
}
/**
* Returns scopes that have to be requested based on the configured claims.
*
* @see http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims
*
* @return string
* Space delimited case sensitive list of ASCII scope values.
*/
function openid_connect_get_scopes() {
$claims = config_get('openid_connect.settings', 'openid_connect_userinfo_mapping_claims');
$scopes = array('openid', 'email');
$claims_info = openid_connect_claims();
foreach ($claims as $claim) {
if (isset($claims_info[$claim]) && !isset($scopes[$claims_info[$claim]['scope']]) && $claim != 'email') {
$scopes[$claims_info[$claim]['scope']] = $claims_info[$claim]['scope'];
}
}
return implode(' ', $scopes);
}
/**
* Returns user properties that can be skipped when mapping user profile info.
*/
function _openid_connect_user_properties_to_skip() {
$properties_to_skip = array(
'name',
'mail',
'uid',
'url',
'edit_url',
'last_access',
'last_login',
'created',
'roles',
'status',
'theme',
);
return backdrop_map_assoc($properties_to_skip);
}
/**
* Logs an error occured during a request towards a login provider.
*/
function openid_connect_log_request_error($method, $client_name, $response) {
switch ($method) {
case 'retrieveTokens':
$message = 'Could not retrieve tokens (@code @error). Details: @details';
break;
case 'retrieveUserInfo':
$message = 'Could not retrieve user profile information (@code @error). Details: @details';
break;
default:
return;
}
// Some error responses don't have a data key set.
$details = '';
if (!empty($response->data)) {
$details = print_r(backdrop_json_decode($response->data), TRUE);
}
$variables = array(
'@error' => $response->error,
'@code' => $response->code,
'@details' => $details,
);
watchdog('openid_connect_' . $client_name, $message, $variables, WATCHDOG_ERROR);
}
/**
* Implements hook_entity_property_info_alter().
*
* Adds the missing timezone property.
*/
function openid_connect_entity_property_info_alter($info) {
$properties = $info['user']['properties'];
if (!isset($properties['timezone'])) {
$properties['timezone'] = array(
'label' => t('Time zone'),
'description' => t("The user's time zone."),
'options list' => 'system_time_zones',
'getter callback' => 'entity_property_verbatim_get',
'setter callback' => 'entity_property_verbatim_set',
'schema field' => 'timezone',
);
}
}
/**
* Get a list of external OIDC accounts connected to this Backdrop account.
*
* @param object $account
* A Backdrop user entity.
*
* @return array
* An array of 'sub' properties keyed by the client name.
*/
function openid_connect_get_connected_accounts($account) {
$auth_maps = db_query(
"SELECT module, authname FROM {authmap} WHERE uid = :uid AND module LIKE 'openid_connect_%'",
array(':uid' => $account->uid)
);
$module_offset = strlen('openid_connect_');
$results = array();
foreach ($auth_maps as $auth_map) {
$client = substr($auth_map->module, $module_offset);
$sub = $auth_map->authname;
$results[$client] = $sub;
}
return $results;
}
/**
* Connect an external OpenID Connect account to a Backdrop user account.
*
* @param object $account
* The Backdrop user object.
* @param string $client_name
* The client machine name.
* @param string $sub
* The 'sub' property identifying the external account.
*/
function openid_connect_connect_account($account, $client_name, $sub) {
watchdog('openid_connect', 'Connecting account in openid_connect_connect_account: uid=%uid, client=%client, sub=%sub',
array('%uid' => $account->uid, '%client' => $client_name, '%sub' => $sub), WATCHDOG_DEBUG);
user_set_authmaps($account, array('authname_openid_connect_' . $client_name => $sub));
watchdog('openid_connect', 'Successfully connected account', array(), WATCHDOG_DEBUG);
}
/**
* Disconnect an external OpenID Connect account from a Backdrop user account.
*
* @param object $account
* The Backdrop user object.
* @param string $client_name
* The client machine name.
* @param string $sub
* The 'sub' property identifying the external account (optional).
*/
function openid_connect_disconnect_account($account, $client_name, $sub = NULL) {
watchdog('openid_connect', 'Disconnecting account in openid_connect_disconnect_account: uid=%uid, client=%client',
array('%uid' => $account->uid, '%client' => $client_name), WATCHDOG_DEBUG);
$query = db_delete('authmap');
$query->condition('uid', $account->uid)
->condition('module', 'openid_connect_' . $client_name);
if ($sub !== NULL) {
$query->condition('authname', $sub);
}
$query->execute();
watchdog('openid_connect', 'Successfully disconnected account', array(), WATCHDOG_DEBUG);
}
/**
* Get the 'sub' property from the user data and/or user claims.
*
* The 'sub' (Subject Identifier) is a unique ID for the external provider to
* identify the user.
*
* @param array $user_data
* The user data as returned from
* OpenIDConnectClientInterface::decodeIdToken().
* @param array $userinfo
* The user claims as returned from
* OpenIDConnectClientInterface::retrieveUserInfo().
*
* @return string|false
* The sub, or FALSE if there was an error.
*/
function openid_connect_extract_sub($user_data, $userinfo) {
watchdog('openid_connect', 'Extracting sub in openid_connect_extract_sub', array(), WATCHDOG_DEBUG);
if (!isset($user_data['sub']) && !isset($userinfo['sub'])) {
watchdog('openid_connect', 'No sub found in either user_data or userinfo', array(), WATCHDOG_DEBUG);
return FALSE;
}
elseif (!isset($user_data['sub'])) {
watchdog('openid_connect', 'Using sub from userinfo: %sub', array('%sub' => $userinfo['sub']), WATCHDOG_DEBUG);
return $userinfo['sub'];
}
elseif (isset($userinfo['sub']) && $user_data['sub'] != $userinfo['sub']) {
watchdog('openid_connect', 'Sub mismatch between user_data and userinfo', array(), WATCHDOG_DEBUG);
return FALSE;
}
else {
watchdog('openid_connect', 'Using sub from user_data: %sub', array('%sub' => $user_data['sub']), WATCHDOG_DEBUG);
return $user_data['sub'];
}
}
/**
* Complete the authorization after tokens have been retrieved.
*
* @param OpenIDConnectClientInterface $client
* The client.
* @param array $tokens
* The tokens as returned from OpenIDConnectClientInterface::retrieveTokens().
* @param string|array &$destination
* The path to redirect to after authorization.
*
* @return bool
* TRUE on success, FALSE on failure.
*/
function openid_connect_complete_authorization($client, $tokens, $destination) {
watchdog('openid_connect', 'Starting authorization in openid_connect_complete_authorization', array(), WATCHDOG_DEBUG);
$config = config('openid_connect.settings');
if (user_is_logged_in()) {
watchdog('openid_connect', 'User already logged in, throwing exception', array(), WATCHDOG_DEBUG);
throw new Exception('User already logged in');
}
$user_data = $client->decodeIdToken($tokens['id_token']);
$userinfo = $client->retrieveUserInfo($tokens['access_token']);
watchdog('openid_connect', 'Retrieved user data and userinfo in openid_connect_complete_authorization', array(), WATCHDOG_DEBUG);
if (empty($userinfo['email'])) {
watchdog('openid_connect', 'No e-mail address provided by @provider', array('@provider' => $client->getLabel()), WATCHDOG_ERROR);
return FALSE;
}
$sub = openid_connect_extract_sub($user_data, $userinfo);
if (empty($sub)) {
watchdog('openid_connect', 'No "sub" found from @provider', array('@provider' => $client->getLabel()), WATCHDOG_ERROR);
return FALSE;
}
// Check whether the e-mail address is valid.
if (!filter_var($userinfo['email'], FILTER_VALIDATE_EMAIL)) {
watchdog('openid_connect', 'Invalid email address in openid_connect_complete_authorization: %mail', array('%mail' => $userinfo['email']), WATCHDOG_DEBUG);
backdrop_set_message(t('The e-mail address %mail is not valid.', array('%mail' => $userinfo['email'])), 'error');
return FALSE;
}
$account = openid_connect_user_load_by_sub($sub, $client->getName());
watchdog('openid_connect', 'Loaded account by sub in openid_connect_complete_authorization: %uid', array('%uid' => $account ? $account->uid : 'not found'), WATCHDOG_DEBUG);
$results = module_invoke_all('openid_connect_pre_authorize', $tokens, $account, $userinfo, $client->getName());
watchdog('openid_connect', 'Pre-authorize hook results in openid_connect_complete_authorization: %results', array('%results' => print_r($results, TRUE)), WATCHDOG_DEBUG);
// Deny access if any module returns FALSE.
if (in_array(FALSE, $results, TRUE)) {
watchdog('openid_connect', 'Login denied for @email via pre-authorize hook.', array('@email' => $userinfo['email']), WATCHDOG_ERROR);
return FALSE;
}
if ($account) {
// An existing account was found. Save user claims.
watchdog('openid_connect', 'Existing account found in openid_connect_complete_authorization: %uid', array('%uid' => $account->uid), WATCHDOG_DEBUG);
if ($config->get('openid_connect_always_save_userinfo')) {
openid_connect_save_userinfo($account, $userinfo);
}
$account_is_new = FALSE;
}
elseif ($account = user_load_by_mail($userinfo['email'])) {
// Check whether there is an e-mail address conflict.
watchdog('openid_connect', 'Account found by email in openid_connect_complete_authorization: %uid', array('%uid' => $account->uid), WATCHDOG_DEBUG);
if ($config->get('openid_connect_connect_existing_users')) {
openid_connect_connect_account($account, $client->getName(), $sub);
$account_is_new = FALSE;
}
else {
backdrop_set_message(t('The e-mail address %email is already taken.', array('%email' => $userinfo['email'])), 'error');
return FALSE;
}
}
else {
// Create a new account.
watchdog('openid_connect', 'Creating new account in openid_connect_complete_authorization', array(), WATCHDOG_DEBUG);
$account = openid_connect_create_user($sub, $userinfo, $client->getName());
// Reload $account in case it has been altered in a user hook elsewhere.
$account = user_load($account->uid);
openid_connect_save_userinfo($account, $userinfo);
$account_is_new = TRUE;
}
watchdog('openid_connect', 'Logging in user in openid_connect_complete_authorization: %uid', array('%uid' => $account->uid), WATCHDOG_DEBUG);
openid_connect_login_user($account, $destination);
module_invoke_all('openid_connect_post_authorize', $tokens, $account, $userinfo, $client->getName(), $account_is_new);
watchdog('openid_connect', 'Completed authorization in openid_connect_complete_authorization', array(), WATCHDOG_DEBUG);
return TRUE;
}