This repository was archived by the owner on Sep 19, 2019. It is now read-only.
forked from uhm-coe/authorizer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthorizer.php
More file actions
8321 lines (7461 loc) · 371 KB
/
authorizer.php
File metadata and controls
8321 lines (7461 loc) · 371 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
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
/**
* Plugin Name: Authorizer (TNTP)
* Description: Authorizer limits login attempts, restricts access to specified users, and authenticates against external sources (e.g., Google, LDAP, or CAS).
* Author: Paul Ryan <prar@hawaii.edu>, Zay Collier <zay.collier@tntp.org>
* Plugin URI: https://github.com/uhm-coe/authorizer
* Text Domain: authorizer
* Domain Path: /languages
* License: GPL2
* Version: 2.8.8
*
* @package authorizer
*/
/**
* Portions forked from Restricted Site Access plugin: http://wordpress.org/plugins/restricted-site-access/
* Portions forked from wpCAS plugin: http://wordpress.org/extend/plugins/cas-authentication/
* Portions forked from Limit Login Attempts: http://wordpress.org/plugins/limit-login-attempts/
*/
require_once dirname( __FILE__ ) . '/vendor/autoload.php';
use FreeDSx\Ldap\LdapClient;
use FreeDSx\Ldap\Operations;
use FreeDSx\Ldap\Search\Filters;
/**
* Add phpCAS library if it's not included.
*
* @see https://wiki.jasig.org/display/CASC/phpCAS+installation+guide
*/
if ( ! defined( 'PHPCAS_VERSION' ) ) {
require_once dirname( __FILE__ ) . '/vendor/phpCAS-1.3.6/CAS.php';
}
if ( ! class_exists( 'WP_Plugin_Authorizer' ) ) {
/**
* Define class for plugin: Authorizer.
*
* @category Authentication
* @package Authorizer
* @author Paul Ryan <prar@hawaii.edu>
* @license http://www.gnu.org/licenses/gpl-2.0.html GPL2
* @link http://hawaii.edu/coe/dcdc/wordpress/authorizer/doc/
*/
class WP_Plugin_Authorizer {
/**
* Constants for determining our admin context (network or individual site).
*/
const NETWORK_CONTEXT = 'multisite_admin';
const SINGLE_CONTEXT = 'single_admin';
/**
* Current site ID (Multisite).
*
* @var string
*/
public $current_site_blog_id = 1;
/**
* HTML allowed when rendering translatable strings in the Authorizer UI.
* This is passed to wp_kses() when sanitizing HMTL strings.
*
* @var array
*/
private $allowed_html = array(
'a' => array(
'class' => array(),
'href' => array(),
'style' => array(),
'target' => array(),
'title' => array(),
),
'b' => array(),
'br' => array(),
'div' => array(
'class' => array(),
),
'em' => array(),
'hr' => array(),
'i' => array(),
'input' => array(
'aria-describedby' => array(),
'class' => array(),
'id' => array(),
'name' => array(),
'size' => array(),
'type' => array(),
'value' => array(),
),
'label' => array(
'class' => array(),
'for' => array(),
),
'p' => array(
'style' => array(),
),
'span' => array(
'aria-hidden' => array(),
'class' => array(),
'id' => array(),
'style' => array(),
),
'strong' => array(),
);
/**
* Constructor.
*/
public function __construct() {
// Save reference to current blog id in the network (support deprecated
// constant BLOGID_CURRENT_SITE).
if ( defined( 'BLOG_ID_CURRENT_SITE' ) ) {
$this->current_site_blog_id = BLOG_ID_CURRENT_SITE;
} elseif ( defined( 'BLOGID_CURRENT_SITE' ) ) { // deprecated.
$this->current_site_blog_id = BLOGID_CURRENT_SITE;
}
// Installation and uninstallation hooks.
register_activation_hook( __FILE__, array( $this, 'activate' ) );
register_deactivation_hook( __FILE__, array( $this, 'deactivate' ) );
/**
* Register filters.
*/
// Custom wp authentication routine using external service.
add_filter( 'authenticate', array( $this, 'custom_authenticate' ), 1, 3 );
// Custom logout action using external service.
add_action( 'wp_logout', array( $this, 'custom_logout' ) );
// Create settings link on Plugins page.
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'plugin_settings_link' ) );
add_filter( 'network_admin_plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'network_admin_plugin_settings_link' ) );
// Modify login page with a custom password url (if option is set).
add_filter( 'lostpassword_url', array( $this, 'custom_lostpassword_url' ) );
// If we have a custom login error, add the filter to show it.
$error = get_option( 'auth_settings_advanced_login_error' );
if ( $error && strlen( $error ) > 0 ) {
add_filter( 'login_errors', array( $this, 'show_advanced_login_error' ) );
}
/**
* Register actions.
*/
// Enable localization. Translation files stored in /languages.
add_action( 'plugins_loaded', array( $this, 'load_textdomain' ) );
// Perform plugin updates if newer version installed.
add_action( 'plugins_loaded', array( $this, 'auth_update_check' ) );
// Update the user meta with this user's failed login attempt.
add_action( 'wp_login_failed', array( $this, 'update_login_failed_count' ) );
// Add users who successfully login to the approved list.
add_action( 'wp_login', array( $this, 'ensure_wordpress_user_in_approved_list_on_login' ), 10, 2 );
// Create menu item in Settings.
add_action( 'admin_menu', array( $this, 'add_plugin_page' ) );
// Create options page.
add_action( 'admin_init', array( $this, 'page_init' ) );
// Update user role in approved list if it's changed in the WordPress edit user page.
add_action( 'user_profile_update_errors', array( $this, 'edit_user_profile_update_role' ), 10, 3 );
// Update user email in approved list if it's changed in the WordPress edit user page.
add_filter( 'send_email_change_email', array( $this, 'edit_user_profile_update_email' ), 10, 3 );
// Enqueue javascript and css on the plugin's options page, the
// dashboard (for the widget), and the network admin.
add_action( 'load-settings_page_authorizer', array( $this, 'load_options_page' ) );
add_action( 'admin_head-index.php', array( $this, 'load_options_page' ) );
add_action( 'load-toplevel_page_authorizer', array( $this, 'load_options_page' ) );
// Add custom css and js to wp-login.php.
add_action( 'login_enqueue_scripts', array( $this, 'login_enqueue_scripts_and_styles' ) );
add_action( 'login_footer', array( $this, 'load_login_footer_js' ) );
// Create google nonce cookie when loading wp-login.php if Google is enabled.
add_action( 'login_init', array( $this, 'login_init__maybe_set_google_nonce_cookie' ) );
// Modify login page with external auth links (if enabled; e.g., google or cas).
add_action( 'login_form', array( $this, 'login_form_add_external_service_links' ) );
// Redirect to CAS login when visiting login page (only if option is
// enabled, CAS is the only service, and WordPress logins are hidden).
// Note: hook into wp_login_errors filter so this fires after the
// authenticate hook (where the redirect to CAS happens), but before html
// output is started (so the redirect header doesn't complain about data
// already being sent).
add_filter( 'wp_login_errors', array( $this, 'wp_login_errors__maybe_redirect_to_cas' ), 10, 2 );
// Verify current user has access to page they are visiting.
add_action( 'parse_request', array( $this, 'restrict_access' ), 9 );
add_action( 'init', array( $this, 'init__maybe_add_network_approved_user' ) );
// AJAX: Save options from dashboard widget.
add_action( 'wp_ajax_update_auth_user', array( $this, 'ajax_update_auth_user' ) );
// AJAX: Save options from multisite options page.
add_action( 'wp_ajax_save_auth_multisite_settings', array( $this, 'ajax_save_auth_multisite_settings' ) );
// AJAX: Save usermeta from options page.
add_action( 'wp_ajax_update_auth_usermeta', array( $this, 'ajax_update_auth_usermeta' ) );
// AJAX: Verify google login.
add_action( 'wp_ajax_process_google_login', array( $this, 'ajax_process_google_login' ) );
add_action( 'wp_ajax_nopriv_process_google_login', array( $this, 'ajax_process_google_login' ) );
// AJAX: Refresh approved user list.
add_action( 'wp_ajax_refresh_approved_user_list', array( $this, 'ajax_refresh_approved_user_list' ) );
// Add dashboard widget so instructors can add/edit users with access.
// Hint: For Multisite Network Admin Dashboard use wp_network_dashboard_setup instead of wp_dashboard_setup.
add_action( 'wp_dashboard_setup', array( $this, 'add_dashboard_widgets' ) );
// If we have a custom admin message, add the action to show it.
$notice = get_option( 'auth_settings_advanced_admin_notice' );
if ( $notice && strlen( $notice ) > 0 ) {
add_action( 'admin_notices', array( $this, 'show_advanced_admin_notice' ) );
add_action( 'network_admin_notices', array( $this, 'show_advanced_admin_notice' ) );
}
// Load custom javascript for the main site (e.g., for displaying alerts).
add_action( 'wp_enqueue_scripts', array( $this, 'auth_public_scripts' ), 20 );
// Multisite-specific actions.
if ( is_multisite() ) {
// Add network admin options page (global settings for all sites).
add_action( 'network_admin_menu', array( $this, 'network_admin_menu' ) );
}
// Remove user from authorizer lists when that user is deleted in WordPress.
add_action( 'delete_user', array( $this, 'remove_user_from_authorizer_when_deleted' ) );
if ( is_multisite() ) {
// Remove multisite user from authorizer lists when that user is deleted from Network Users.
add_action( 'remove_user_from_blog', array( $this, 'remove_network_user_from_site_when_removed' ), 10, 2 );
add_action( 'wpmu_delete_user', array( $this, 'remove_network_user_from_authorizer_when_deleted' ) );
}
// Add user to authorizer approved list when that user is added to a blog from the Users screen.
// Multisite: invite_user action fired when adding (inviting) an existing network user to the current site (with email confirmation).
add_action( 'invite_user', array( $this, 'add_existing_user_to_authorizer_when_created' ), 10, 3 );
// Multisite: added_existing_user action fired when adding an existing network user to the current site (without email confirmation).
add_action( 'added_existing_user', array( $this, 'add_existing_user_to_authorizer_when_created_noconfirmation' ), 10, 2 );
// Multisite: after_signup_user action fired when adding a new user to the site (with or without email confirmation).
add_action( 'after_signup_user', array( $this, 'add_new_user_to_authorizer_when_created' ), 10, 4 );
// Single site: edit_user_created_user action fired when adding a new user to the site (with or without email notification).
add_action( 'edit_user_created_user', array( $this, 'add_new_user_to_authorizer_when_created_single_site' ), 10, 2 );
// Add user to network approved users (and remove from individual sites)
// when user is elevated to super admin status.
add_action( 'grant_super_admin', array( $this, 'grant_super_admin__add_to_network_approved' ) );
// Remove user from network approved users (and add them to the approved
// list on sites they are already on) when super admin status is removed.
add_action( 'revoke_super_admin', array( $this, 'revoke_super_admin__remove_from_network_approved' ) );
}
/**
* Plugin activation hook.
* Will also activate the plugin for all sites/blogs if this is a "Network enable."
*
* @return void
*/
public function activate( $network_wide ) {
global $wpdb;
// If we're in a multisite environment, run the plugin activation for each
// site when network enabling.
// Note: wp-cli does not use nonces, so we skip the nonce check here to
// allow the "wp plugin activate authorizer" command.
// phpcs:ignore WordPress.CSRF.NonceVerification.NoNonceVerification
if ( is_multisite() && $network_wide ) {
// Add super admins to the multisite approved list.
$auth_multisite_settings_access_users_approved = get_blog_option( $this->current_site_blog_id, 'auth_multisite_settings_access_users_approved', array() );
$should_update_auth_multisite_settings_access_users_approved = false;
foreach ( get_super_admins() as $super_admin ) {
$user = get_user_by( 'login', $super_admin );
// Add to approved list if not there.
if ( ! $this->in_multi_array( $user->user_email, $auth_multisite_settings_access_users_approved ) ) {
$approved_user = array(
'email' => $this->lowercase( $user->user_email ),
'role' => count( $user->roles ) > 0 ? $user->roles[0] : 'administrator',
'date_added' => date( 'M Y', strtotime( $user->user_registered ) ),
'local_user' => true,
);
array_push( $auth_multisite_settings_access_users_approved, $approved_user );
$should_update_auth_multisite_settings_access_users_approved = true;
}
}
if ( $should_update_auth_multisite_settings_access_users_approved ) {
update_blog_option( $this->current_site_blog_id, 'auth_multisite_settings_access_users_approved', $auth_multisite_settings_access_users_approved );
}
// Run plugin activation on each site in the network.
$current_blog_id = $wpdb->blogid;
// phpcs:ignore WordPress.WP.DeprecatedFunctions.wp_get_sitesFound
$sites = function_exists( 'get_sites' ) ? get_sites() : wp_get_sites( array( 'limit' => PHP_INT_MAX ) );
foreach ( $sites as $site ) {
$blog_id = function_exists( 'get_sites' ) ? $site->blog_id : $site['blog_id'];
switch_to_blog( $blog_id );
// Set default plugin options and add current users to approved list.
$this->set_default_options();
$this->add_wp_users_to_approved_list();
}
switch_to_blog( $current_blog_id );
} else {
// Set default plugin options and add current users to approved list.
$this->set_default_options();
$this->add_wp_users_to_approved_list();
}
}
/**
* Adds all WordPress users in the current site to the approved list,
* unless they are already in the blocked list. Also removes them
* from the pending list if they are there.
*
* Runs in plugin activation hook.
*
* @return void
*/
private function add_wp_users_to_approved_list() {
// Add current WordPress users to the approved list.
$auth_multisite_settings_access_users_approved = is_multisite() ? get_blog_option( $this->current_site_blog_id, 'auth_multisite_settings_access_users_approved', array() ) : array();
$auth_settings_access_users_pending = $this->get_plugin_option( 'access_users_pending', WP_Plugin_Authorizer::SINGLE_CONTEXT );
$auth_settings_access_users_approved = $this->get_plugin_option( 'access_users_approved', WP_Plugin_Authorizer::SINGLE_CONTEXT );
$auth_settings_access_users_blocked = $this->get_plugin_option( 'access_users_blocked', WP_Plugin_Authorizer::SINGLE_CONTEXT );
$updated = false;
foreach ( get_users() as $user ) {
// Skip if user is in blocked list.
if ( $this->in_multi_array( $user->user_email, $auth_settings_access_users_blocked ) ) {
continue;
}
// Remove from pending list if there.
foreach ( $auth_settings_access_users_pending as $key => $pending_user ) {
if ( 0 === strcasecmp( $pending_user['email'], $user->user_email ) ) {
unset( $auth_settings_access_users_pending[ $key ] );
$updated = true;
}
}
// Skip if user is in multisite approved list.
if ( $this->in_multi_array( $user->user_email, $auth_multisite_settings_access_users_approved ) ) {
continue;
}
// Add to approved list if not there.
if ( ! $this->in_multi_array( $user->user_email, $auth_settings_access_users_approved ) ) {
$approved_user = array(
'email' => $this->lowercase( $user->user_email ),
'role' => count( $user->roles ) > 0 ? $user->roles[0] : '',
'date_added' => date( 'M Y', strtotime( $user->user_registered ) ),
'local_user' => true,
);
array_push( $auth_settings_access_users_approved, $approved_user );
$updated = true;
}
}
if ( $updated ) {
update_option( 'auth_settings_access_users_pending', $auth_settings_access_users_pending );
update_option( 'auth_settings_access_users_approved', $auth_settings_access_users_approved );
}
}
/**
* Plugin deactivation.
*
* @return void
*/
public function deactivate() {
// Do nothing.
}
/**
* ***************************
* External Authentication
* ***************************
*/
/**
* Authenticate against an external service.
*
* Filter: authenticate
*
* @param WP_User $user user to authenticate.
* @param string $username optional username to authenticate.
* @param string $password optional password to authenticate.
* @return WP_User|WP_Error WP_User on success, WP_Error on failure.
*/
public function custom_authenticate( $user, $username, $password ) {
// Pass through if already authenticated.
if ( is_a( $user, 'WP_User' ) ) {
return $user;
} else {
$user = null;
}
// If username and password are blank, this isn't a log in attempt.
$is_login_attempt = strlen( $username ) > 0 && strlen( $password ) > 0;
// Check to make sure that $username is not locked out due to too
// many invalid login attempts. If it is, tell the user how much
// time remains until they can try again.
$unauthenticated_user = $is_login_attempt ? get_user_by( 'login', $username ) : false;
$unauthenticated_user_is_blocked = false;
if ( $is_login_attempt && false !== $unauthenticated_user ) {
$last_attempt = get_user_meta( $unauthenticated_user->ID, 'auth_settings_advanced_lockouts_time_last_failed', true );
$num_attempts = get_user_meta( $unauthenticated_user->ID, 'auth_settings_advanced_lockouts_failed_attempts', true );
// Also check the auth_blocked user_meta flag (users in blocked list will get this flag).
$unauthenticated_user_is_blocked = get_user_meta( $unauthenticated_user->ID, 'auth_blocked', true ) === 'yes';
} else {
$last_attempt = get_option( 'auth_settings_advanced_lockouts_time_last_failed' );
$num_attempts = get_option( 'auth_settings_advanced_lockouts_failed_attempts' );
}
// Inactive users should be treated like deleted users (we just
// do this to preserve any content they created, but here we should
// pretend they don't exist).
if ( $unauthenticated_user_is_blocked ) {
remove_filter( 'authenticate', 'wp_authenticate_username_password', 20, 3 );
return new WP_Error( 'empty_password', __( '<strong>ERROR</strong>: Incorrect username or password.', 'authorizer' ) );
}
// Grab plugin settings.
$auth_settings = $this->get_plugin_options( WP_Plugin_Authorizer::SINGLE_CONTEXT, 'allow override' );
// Make sure $last_attempt (time) and $num_attempts are positive integers.
// Note: this addresses resetting them if either is unset from above.
$last_attempt = abs( intval( $last_attempt ) );
$num_attempts = abs( intval( $num_attempts ) );
// Create semantic lockout variables.
$lockouts = $auth_settings['advanced_lockouts'];
$time_since_last_fail = time() - $last_attempt;
$reset_duration = $lockouts['reset_duration'] * 60; // minutes to seconds.
$num_attempts_long_lockout = $lockouts['attempts_1'] + $lockouts['attempts_2'];
$num_attempts_short_lockout = $lockouts['attempts_1'];
$seconds_remaining_long_lockout = $lockouts['duration_2'] * 60 - $time_since_last_fail;
$seconds_remaining_short_lockout = $lockouts['duration_1'] * 60 - $time_since_last_fail;
// Check if we need to institute a lockout delay.
if ( $is_login_attempt && $time_since_last_fail > $reset_duration ) {
// Enough time has passed since the last invalid attempt and
// now that we can reset the failed attempt count, and let this
// login attempt go through.
$num_attempts = 0; // This does nothing, but include it for semantic meaning.
} elseif ( $is_login_attempt && $num_attempts > $num_attempts_long_lockout && $seconds_remaining_long_lockout > 0 ) {
// Stronger lockout (1st/2nd round of invalid attempts reached)
// Note: set the error code to 'empty_password' so it doesn't
// trigger the wp_login_failed hook, which would continue to
// increment the failed attempt count.
remove_filter( 'authenticate', 'wp_authenticate_username_password', 20, 3 );
return new WP_Error(
'empty_password',
sprintf(
/* TRANSLATORS: 1: username 2: duration of lockout in seconds 3: duration of lockout as a phrase 4: lost password URL */
__( '<strong>ERROR</strong>: There have been too many invalid login attempts for the username <strong>%1$s</strong>. Please wait <strong id="seconds_remaining" data-seconds="%2$s">%3$s</strong> before trying again. <a href="%4$s" title="Password Lost and Found">Lost your password</a>?', 'authorizer' ),
$username,
$seconds_remaining_long_lockout,
$this->seconds_as_sentence( $seconds_remaining_long_lockout ),
wp_lostpassword_url()
)
);
} elseif ( $is_login_attempt && $num_attempts > $num_attempts_short_lockout && $seconds_remaining_short_lockout > 0 ) {
// Normal lockout (1st round of invalid attempts reached)
// Note: set the error code to 'empty_password' so it doesn't
// trigger the wp_login_failed hook, which would continue to
// increment the failed attempt count.
remove_filter( 'authenticate', 'wp_authenticate_username_password', 20, 3 );
return new WP_Error(
'empty_password',
sprintf(
/* TRANSLATORS: 1: username 2: duration of lockout in seconds 3: duration of lockout as a phrase 4: lost password URL */
__( '<strong>ERROR</strong>: There have been too many invalid login attempts for the username <strong>%1$s</strong>. Please wait <strong id="seconds_remaining" data-seconds="%2$s">%3$s</strong> before trying again. <a href="%4$s" title="Password Lost and Found">Lost your password</a>?', 'authorizer' ),
$username,
$seconds_remaining_short_lockout,
$this->seconds_as_sentence( $seconds_remaining_short_lockout ),
wp_lostpassword_url()
)
);
}
// Start external authentication.
$externally_authenticated_emails = array();
$authenticated_by = '';
$result = null;
// Try Google authentication if it's enabled and we don't have a
// successful login yet.
if (
'1' === $auth_settings['google'] &&
0 === count( $externally_authenticated_emails ) &&
! is_wp_error( $result )
) {
$result = $this->custom_authenticate_google( $auth_settings );
if ( ! is_null( $result ) && ! is_wp_error( $result ) ) {
if ( is_array( $result['email'] ) ) {
$externally_authenticated_emails = $result['email'];
} else {
$externally_authenticated_emails[] = $result['email'];
}
$authenticated_by = $result['authenticated_by'];
}
}
// Try CAS authentication if it's enabled and we don't have a
// successful login yet.
if (
'1' === $auth_settings['cas'] &&
0 === count( $externally_authenticated_emails ) &&
! is_wp_error( $result )
) {
$result = $this->custom_authenticate_cas( $auth_settings );
if ( ! is_null( $result ) && ! is_wp_error( $result ) ) {
if ( is_array( $result['email'] ) ) {
$externally_authenticated_emails = $result['email'];
} else {
$externally_authenticated_emails[] = $result['email'];
}
$authenticated_by = $result['authenticated_by'];
}
}
// Try LDAP authentication if it's enabled and we don't have an
// authenticated user yet.
if (
'1' === $auth_settings['ldap'] &&
0 === count( $externally_authenticated_emails ) &&
! is_wp_error( $result )
) {
$result = $this->custom_authenticate_ldap( $auth_settings, $username, $password );
if ( ! is_null( $result ) && ! is_wp_error( $result ) ) {
if ( is_array( $result['email'] ) ) {
$externally_authenticated_emails = $result['email'];
} else {
$externally_authenticated_emails[] = $result['email'];
}
$authenticated_by = $result['authenticated_by'];
}
}
// Skip to WordPress authentication if we don't have an externally
// authenticated user.
if ( count( array_filter( $externally_authenticated_emails ) ) < 1 ) {
return $result;
}
// Remove duplicate and blank emails, if any.
$externally_authenticated_emails = array_filter( array_unique( $externally_authenticated_emails ) );
/**
* If we've made it this far, we should have an externally
* authenticated user. The following should be set:
* $externally_authenticated_emails
* $authenticated_by
*/
// Look for an existing WordPress account matching the externally
// authenticated user. Perform the match either by username or email.
if ( isset( $auth_settings['cas_link_on_username'] ) && 1 === intval( $auth_settings['cas_link_on_username'] ) ) {
// Get the external user's WordPress account by username. This is less
// secure, but a user reported having an installation where a previous
// CAS plugin had created over 9000 WordPress accounts without email
// addresses. This option was created to support that case, and any
// other CAS servers where emails are not used as account identifiers.
$user = get_user_by( 'login', $result['username']);
} else {
// Get the external user's WordPress account by email address. This is
// the normal behavior (and the most secure).
foreach ( $externally_authenticated_emails as $externally_authenticated_email ) {
$user = get_user_by( 'email', $this->lowercase( $externally_authenticated_email ) );
// Stop trying email addresses once we have found a match.
if ( false !== $user ) {
break;
}
}
}
// Check this external user's access against the access lists
// (pending, approved, blocked).
$result = $this->check_user_access( $user, $externally_authenticated_emails, $result );
// Fail with message if there was an error creating/adding the user.
if ( is_wp_error( $result ) || 0 === $result ) {
return $result;
}
// If we have a valid user from check_user_access(), log that user in.
if ( get_class( $result ) === 'WP_User' ) {
$user = $result;
}
// We'll track how this user was authenticated in user meta.
if ( $user ) {
update_user_meta( $user->ID, 'authenticated_by', $authenticated_by );
}
// If we haven't exited yet, we have a valid/approved user, so authenticate them.
return $user;
}
/**
* This function will fail with a wp_die() message to the user if they
* don't have access.
*
* @param WP_User $user User to check.
* @param array $user_emails Array of user's plaintext emails (in case current user doesn't have a WP account).
* @param array $user_data Array of keys for email, username, first_name, last_name,
* authenticated_by, google_attributes, cas_attributes, ldap_attributes.
* @return WP_Error|WP_User
* WP_Error if there was an error on user creation / adding user to blog.
* WP_Error / wp_die() if user does not have access.
* WP_User if user has access.
*/
private function check_user_access( $user, $user_emails, $user_data = array() ) {
// Grab plugin settings.
$auth_settings = $this->get_plugin_options( WP_Plugin_Authorizer::SINGLE_CONTEXT, 'allow override' );
$auth_settings_access_users_pending = $this->sanitize_user_list(
$this->get_plugin_option( 'access_users_pending', WP_Plugin_Authorizer::SINGLE_CONTEXT )
);
$auth_settings_access_users_approved_single = $this->get_plugin_option( 'access_users_approved', WP_Plugin_Authorizer::SINGLE_CONTEXT );
$auth_settings_access_users_approved_multi = $this->get_plugin_option( 'access_users_approved', WP_Plugin_Authorizer::NETWORK_CONTEXT );
$auth_settings_access_users_approved = $this->sanitize_user_list(
array_merge(
$auth_settings_access_users_approved_single,
$auth_settings_access_users_approved_multi
)
);
/**
* Filter whether to block the currently logging in user based on any of
* their user attributes.
*
* @param bool $allow_login Whether to block the currently logging in user.
* @param array $user_data User data returned from external service.
*/
$allow_login = apply_filters( 'authorizer_allow_login', true, $user_data );
$blocked_by_filter = ! $allow_login; // Use this for better readability.
// Check our externally authenticated user against the block list.
// If any of their email addresses are blocked, set the relevant user
// meta field, and show them an error screen.
foreach ( $user_emails as $user_email ) {
if ( $blocked_by_filter || $this->is_email_in_list( $user_email, 'blocked' ) ) {
// Add user to blocked list if it was blocked via the filter.
if ( $blocked_by_filter && ! $this->is_email_in_list( $user_email, 'blocked' ) ) {
$auth_settings_access_users_blocked = $this->sanitize_user_list(
$this->get_plugin_option( 'access_users_blocked', WP_Plugin_Authorizer::SINGLE_CONTEXT )
);
array_push(
$auth_settings_access_users_blocked, array(
'email' => $this->lowercase( $user_email ),
'date_added' => date( 'M Y' ),
)
);
update_option( 'auth_settings_access_users_blocked', $auth_settings_access_users_blocked );
}
// If the blocked external user has a WordPress account, mark it as
// blocked (enforce block in this->authenticate()).
if ( $user ) {
update_user_meta( $user->ID, 'auth_blocked', 'yes' );
}
// Notify user about blocked status and return without authenticating them.
// phpcs:ignore WordPress.CSRF.NonceVerification.NoNonceVerification
$redirect_to = ! empty( $_REQUEST['redirect_to'] ) ? esc_url_raw( wp_unslash( $_REQUEST['redirect_to'] ) ) : home_url();
$page_title = sprintf(
/* TRANSLATORS: %s: Name of blog */
__( '%s - Access Restricted', 'authorizer' ),
get_bloginfo( 'name' )
);
$error_message =
apply_filters( 'the_content', $auth_settings['access_blocked_redirect_to_message'] ) .
'<hr />' .
'<p style="text-align: center;">' .
'<a class="button" href="' . wp_logout_url( $redirect_to ) . '">' .
__( 'Back', 'authorizer' ) .
'</a></p>';
update_option( 'auth_settings_advanced_login_error', $error_message );
wp_die( wp_kses( $error_message, $this->allowed_html ), esc_html( $page_title ) );
return new WP_Error( 'invalid_login', __( 'Invalid login attempted.', 'authorizer' ) );
}
}
// Get the default role for this user (or their current role, if they
// already have an account).
$default_role = $user && is_array( $user->roles ) && count( $user->roles ) > 0 ? $user->roles[0] : $auth_settings['access_default_role'];
/**
* Filter the role of the user currently logging in. The role will be
* set to the default (specified in Authorizer options) for new users,
* or the user's current role for existing users. This filter allows
* changing user roles based on custom CAS/LDAP attributes.
*
* @param bool $role Role of the user currently logging in.
* @param array $user_data User data returned from external service.
*/
$approved_role = apply_filters( 'authorizer_custom_role', $default_role, $user_data );
/**
* Filter whether to automatically approve the currently logging in user
* based on any of their user attributes.
*
* @param bool $automatically_approve_login
* Whether to automatically approve the currently logging in user.
* @param array $user_data User data returned from external service.
*/
$automatically_approve_login = apply_filters( 'authorizer_automatically_approve_login', false, $user_data );
// Iterate through each of the email addresses provided by the external
// service and determine if any of them have access.
$last_email = end( $user_emails );
reset( $user_emails );
foreach ( $user_emails as $user_email ) {
$is_newly_approved_user = false;
// If this externally authenticated user is an existing administrator
// (administrator in single site mode, or super admin in network mode),
// and is not in the blocked list, let them in.
if ( $user && is_super_admin( $user->ID ) ) {
return $user;
}
// If this externally authenticated user isn't in the approved list
// and login access is set to "All authenticated users," or if they were
// automatically approved in the "authorizer_approve_login" filter
// above, then add them to the approved list (they'll get an account
// created below if they don't have one yet).
if (
! $this->is_email_in_list( $user_email, 'approved' ) &&
( 'external_users' === $auth_settings['access_who_can_login'] || $automatically_approve_login )
) {
$is_newly_approved_user = true;
// If this user happens to be in the pending list (rare),
// remove them from pending before adding them to approved.
if ( $this->is_email_in_list( $user_email, 'pending' ) ) {
foreach ( $auth_settings_access_users_pending as $key => $pending_user ) {
if ( 0 === strcasecmp( $pending_user['email'], $user_email ) ) {
unset( $auth_settings_access_users_pending[ $key ] );
update_option( 'auth_settings_access_users_pending', $auth_settings_access_users_pending );
break;
}
}
}
// Add this user to the approved list.
$approved_user = array(
'email' => $this->lowercase( $user_email ),
'role' => $approved_role,
'date_added' => date( 'Y-m-d H:i:s' ),
);
array_push( $auth_settings_access_users_approved, $approved_user );
array_push( $auth_settings_access_users_approved_single, $approved_user );
update_option( 'auth_settings_access_users_approved', $auth_settings_access_users_approved_single );
}
// Check our externally authenticated user against the approved
// list. If they are approved, log them in (and create their account
// if necessary).
if ( $is_newly_approved_user || $this->is_email_in_list( $user_email, 'approved' ) ) {
$user_info = $is_newly_approved_user ? $approved_user : $this->get_user_info_from_list( $user_email, $auth_settings_access_users_approved );
// If this user's role was modified above (in the
// authorizer_custom_role filter), use that value instead of
// whatever is specified in the approved list.
if ( $default_role !== $approved_role ) {
$user_info['role'] = $approved_role;
}
// If the approved external user does not have a WordPress account, create it.
if ( ! $user ) {
if ( array_key_exists( 'username', $user_data ) ) {
$username = $user_data['username'];
} else {
$username = explode( '@', $user_info['email'] );
$username = $username[0];
}
// If there's already a user with this username (e.g.,
// johndoe/johndoe@gmail.com exists, and we're trying to add
// johndoe/johndoe@example.com), use the full email address
// as the username.
if ( get_user_by( 'login', $username ) !== false ) {
$username = $user_info['email'];
}
$result = wp_insert_user(
array(
'user_login' => strtolower( $username ),
'user_pass' => wp_generate_password(), // random password.
'first_name' => array_key_exists( 'first_name', $user_data ) ? $user_data['first_name'] : '',
'last_name' => array_key_exists( 'last_name', $user_data ) ? $user_data['last_name'] : '',
'user_email' => $this->lowercase( $user_info['email'] ),
'user_registered' => date( 'Y-m-d H:i:s' ),
'role' => $user_info['role'],
)
);
// Fail with message if error.
if ( is_wp_error( $result ) || 0 === $result ) {
return $result;
}
// Authenticate as new user.
$user = new WP_User( $result );
/**
* Fires after an external user is authenticated for the first time
* and a new WordPress account is created for them.
*
* @since 2.8.0
*
* @param WP_User $user User object.
* @param array $user_data User data from external service.
*
* Example $user_data:
* array(
* 'email' => 'user@example.edu',
* 'username' => 'user',
* 'first_name' => 'First',
* 'last_name' => 'Last',
* 'authenticated_by' => 'cas',
* 'cas_attributes' => array( ... ),
* );
*/
do_action( 'authorizer_user_register', $user, $user_data );
// If multisite, iterate through all sites in the network and add the user
// currently logging in to any of them that have the user on the approved list.
// Note: this is useful for first-time logins--some users will have access
// to multiple sites, and this prevents them from having to log into each
// site individually to get access.
if ( is_multisite() ) {
$site_ids_of_user = array_map(
function ( $site_of_user ) {
return intval( $site_of_user->userblog_id );
},
get_blogs_of_user( $user->ID )
);
// phpcs:ignore WordPress.WP.DeprecatedFunctions.wp_get_sitesFound
$sites = function_exists( 'get_sites' ) ? get_sites() : wp_get_sites( array( 'limit' => PHP_INT_MAX ) );
foreach ( $sites as $site ) {
$blog_id = function_exists( 'get_sites' ) ? $site->blog_id : $site['blog_id'];
// Skip if user is already added to this site.
if ( in_array( intval( $blog_id ), $site_ids_of_user, true ) ) {
continue;
}
// Check if user is on the approved list of this site they are not added to.
$other_auth_settings_access_users_approved = get_blog_option( $blog_id, 'auth_settings_access_users_approved', array() );
if ( $this->in_multi_array( $user->user_email, $other_auth_settings_access_users_approved ) ) {
$other_user_info = $this->get_user_info_from_list( $user->user_email, $other_auth_settings_access_users_approved );
// Add user to other site.
add_user_to_blog( $blog_id, $user->ID, $other_user_info['role'] );
}
}
}
// Check if this new user has any preassigned usermeta
// values in their approved list entry, and apply them to
// their new WordPress account.
if ( array_key_exists( 'usermeta', $user_info ) && is_array( $user_info['usermeta'] ) ) {
$meta_key = $this->get_plugin_option( 'advanced_usermeta' );
if ( array_key_exists( 'meta_key', $user_info['usermeta'] ) && array_key_exists( 'meta_value', $user_info['usermeta'] ) ) {
// Only update the usermeta if the stored value matches
// the option set in authorizer settings (if they don't
// match it's probably old data).
if ( $meta_key === $user_info['usermeta']['meta_key'] ) {
// Update user's usermeta value for usermeta key stored in authorizer options.
if ( strpos( $meta_key, 'acf___' ) === 0 && class_exists( 'acf' ) ) {
// We have an ACF field value, so use the ACF function to update it.
update_field( str_replace( 'acf___', '', $meta_key ), $user_info['usermeta']['meta_value'], 'user_' . $user->ID );
} else {
// We have a normal usermeta value, so just update it via the WordPress function.
update_user_meta( $user->ID, $meta_key, $user_info['usermeta']['meta_value'] );
}
}
} elseif ( is_multisite() && count( $user_info['usermeta'] ) > 0 ) {
// Update usermeta for each multisite blog defined for this user.
foreach ( $user_info['usermeta'] as $blog_id => $usermeta ) {
if ( array_key_exists( 'meta_key', $usermeta ) && array_key_exists( 'meta_value', $usermeta ) ) {
// Add this new user to the blog before we create their user meta (this step typically happens below, but we need it to happen early so we can create user meta here).
if ( ! is_user_member_of_blog( $user->ID, $blog_id ) ) {
add_user_to_blog( $blog_id, $user->ID, $user_info['role'] );
}
switch_to_blog( $blog_id );
// Update user's usermeta value for usermeta key stored in authorizer options.
if ( strpos( $meta_key, 'acf___' ) === 0 && class_exists( 'acf' ) ) {
// We have an ACF field value, so use the ACF function to update it.
update_field( str_replace( 'acf___', '', $meta_key ), $usermeta['meta_value'], 'user_' . $user->ID );
} else {
// We have a normal usermeta value, so just update it via the WordPress function.
update_user_meta( $user->ID, $meta_key, $usermeta['meta_value'] );
}
restore_current_blog();
}
}
}
}
} else {
// Update first/last names of WordPress user from external
// service if that option is set.
if ( ( array_key_exists( 'authenticated_by', $user_data ) && 'cas' === $user_data['authenticated_by'] && array_key_exists( 'cas_attr_update_on_login', $auth_settings ) && 1 === intval( $auth_settings['cas_attr_update_on_login'] ) ) || ( array_key_exists( 'authenticated_by', $user_data ) && 'ldap' === $user_data['authenticated_by'] && array_key_exists( 'ldap_attr_update_on_login', $auth_settings ) && 1 === intval( $auth_settings['ldap_attr_update_on_login'] ) ) ) {
if ( array_key_exists( 'first_name', $user_data ) && 0 < strlen( $user_data['first_name'] ) ) {
wp_update_user(
array(
'ID' => $user->ID,
'first_name' => $user_data['first_name'],
)
);
}
if ( array_key_exists( 'last_name', $user_data ) && strlen( $user_data['last_name'] ) > 0 ) {
wp_update_user(
array(
'ID' => $user->ID,
'last_name' => $user_data['last_name'],
)
);
}
}
// Update this user's role if it was modified in the
// authorizer_custom_role filter.
if ( $default_role !== $approved_role ) {
// Update user's role in WordPress.
$user->set_role( $approved_role );
// Update user's role in this site's approved list and save.
foreach ( $auth_settings_access_users_approved_single as $key => $existing_user ) {
if ( 0 === strcasecmp( $user->user_email, $existing_user['email'] ) ) {
$auth_settings_access_users_approved_single[ $key ]['role'] = $approved_role;
break;
}
}
update_option( 'auth_settings_access_users_approved', $auth_settings_access_users_approved_single );
}
}
// If this is multisite, add new user to current blog.
if ( is_multisite() && ! is_user_member_of_blog( $user->ID ) ) {
$result = add_user_to_blog( get_current_blog_id(), $user->ID, $user_info['role'] );
// Fail with message if error.
if ( is_wp_error( $result ) ) {
return $result;
}
}
// Ensure user has the same role as their entry in the approved list.
if ( $user_info && ! in_array( $user_info['role'], $user->roles, true ) ) {
$user->set_role( $user_info['role'] );
}
return $user;
} elseif ( 0 === strcasecmp( $user_email, $last_email ) ) {
/**
* Note: only do this for the last email address we are checking (we need
* to iterate through them all to make sure one of them isn't approved).
*/
// User isn't an admin, is not blocked, and is not approved.
// Add them to the pending list and notify them and their instructor.
if ( strlen( $user_email ) > 0 && ! $this->is_email_in_list( $user_email, 'pending' ) ) {
$pending_user = array();
$pending_user['email'] = $this->lowercase( $user_email );
$pending_user['role'] = $approved_role;
$pending_user['date_added'] = '';
array_push( $auth_settings_access_users_pending, $pending_user );
update_option( 'auth_settings_access_users_pending', $auth_settings_access_users_pending );
// Create strings used in the email notification.
$site_name = get_bloginfo( 'name' );
$site_url = get_bloginfo( 'url' );
$authorizer_options_url = 'settings' === $auth_settings['advanced_admin_menu'] ? admin_url( 'options-general.php?page=authorizer' ) : admin_url( '?page=authorizer' );
// Notify users with the role specified in "Which role should
// receive email notifications about pending users?".
if ( strlen( $auth_settings['access_role_receive_pending_emails'] ) > 0 ) {