forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
authlib.php
1268 lines (1109 loc) · 42.2 KB
/
authlib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Multiple plugin authentication Support library
*
* 2006-08-28 File created, AUTH return values defined.
*
* @package core
* @subpackage auth
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* Returned when the login was successful.
*/
define('AUTH_OK', 0);
/**
* Returned when the login was unsuccessful.
*/
define('AUTH_FAIL', 1);
/**
* Returned when the login was denied (a reason for AUTH_FAIL).
*/
define('AUTH_DENIED', 2);
/**
* Returned when some error occurred (a reason for AUTH_FAIL).
*/
define('AUTH_ERROR', 4);
/**
* Authentication - error codes for user confirm
*/
define('AUTH_CONFIRM_FAIL', 0);
define('AUTH_CONFIRM_OK', 1);
define('AUTH_CONFIRM_ALREADY', 2);
define('AUTH_CONFIRM_ERROR', 3);
# MDL-14055
define('AUTH_REMOVEUSER_KEEP', 0);
define('AUTH_REMOVEUSER_SUSPEND', 1);
define('AUTH_REMOVEUSER_FULLDELETE', 2);
/** Login attempt successful. */
define('AUTH_LOGIN_OK', 0);
/** Can not login because user does not exist. */
define('AUTH_LOGIN_NOUSER', 1);
/** Can not login because user is suspended. */
define('AUTH_LOGIN_SUSPENDED', 2);
/** Can not login, most probably password did not match. */
define('AUTH_LOGIN_FAILED', 3);
/** Can not login because user is locked out. */
define('AUTH_LOGIN_LOCKOUT', 4);
/** Can not login becauser user is not authorised. */
define('AUTH_LOGIN_UNAUTHORISED', 5);
/**
* Abstract authentication plugin.
*
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package moodlecore
*/
class auth_plugin_base {
/**
* The configuration details for the plugin.
* @var object
*/
var $config;
/**
* Authentication plugin type - the same as db field.
* @var string
*/
var $authtype;
/*
* The fields we can lock and update from/to external authentication backends
* @var array
*/
var $userfields = \core_user::AUTHSYNCFIELDS;
/**
* Moodle custom fields to sync with.
* @var array()
*/
var $customfields = null;
/**
* The tag we want to prepend to any error log messages.
*
* @var string
*/
protected $errorlogtag = '';
/**
* This is the primary method that is used by the authenticate_user_login()
* function in moodlelib.php.
*
* This method should return a boolean indicating
* whether or not the username and password authenticate successfully.
*
* Returns true if the username and password work and false if they are
* wrong or don't exist.
*
* @param string $username The username (with system magic quotes)
* @param string $password The password (with system magic quotes)
*
* @return bool Authentication success or failure.
*/
function user_login($username, $password) {
print_error('mustbeoveride', 'debug', '', 'user_login()' );
}
/**
* Returns true if this authentication plugin can change the users'
* password.
*
* @return bool
*/
function can_change_password() {
//override if needed
return false;
}
/**
* Returns the URL for changing the users' passwords, or empty if the default
* URL can be used.
*
* This method is used if can_change_password() returns true.
* This method is called only when user is logged in, it may use global $USER.
* If you are using a plugin config variable in this method, please make sure it is set before using it,
* as this method can be called even if the plugin is disabled, in which case the config values won't be set.
*
* @return moodle_url url of the profile page or null if standard used
*/
function change_password_url() {
//override if needed
return null;
}
/**
* Returns true if this authentication plugin can edit the users'
* profile.
*
* @return bool
*/
function can_edit_profile() {
//override if needed
return true;
}
/**
* Returns the URL for editing the users' profile, or empty if the default
* URL can be used.
*
* This method is used if can_edit_profile() returns true.
* This method is called only when user is logged in, it may use global $USER.
*
* @return moodle_url url of the profile page or null if standard used
*/
function edit_profile_url() {
//override if needed
return null;
}
/**
* Returns true if this authentication plugin is "internal".
*
* Internal plugins use password hashes from Moodle user table for authentication.
*
* @return bool
*/
function is_internal() {
//override if needed
return true;
}
/**
* Returns false if this plugin is enabled but not configured.
*
* @return bool
*/
public function is_configured() {
return false;
}
/**
* Indicates if password hashes should be stored in local moodle database.
* @return bool true means md5 password hash stored in user table, false means flag 'not_cached' stored there instead
*/
function prevent_local_passwords() {
return !$this->is_internal();
}
/**
* Indicates if moodle should automatically update internal user
* records with data from external sources using the information
* from get_userinfo() method.
*
* @return bool true means automatically copy data from ext to user table
*/
function is_synchronised_with_external() {
return !$this->is_internal();
}
/**
* Updates the user's password.
*
* In previous versions of Moodle, the function
* auth_user_update_password accepted a username as the first parameter. The
* revised function expects a user object.
*
* @param object $user User table object
* @param string $newpassword Plaintext password
*
* @return bool True on success
*/
function user_update_password($user, $newpassword) {
//override if needed
return true;
}
/**
* Called when the user record is updated.
* Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
* compares information saved modified information to external db.
*
* @param mixed $olduser Userobject before modifications (without system magic quotes)
* @param mixed $newuser Userobject new modified userobject (without system magic quotes)
* @return boolean true if updated or update ignored; false if error
*
*/
function user_update($olduser, $newuser) {
//override if needed
return true;
}
/**
* User delete requested - internal user record is mared as deleted already, username not present anymore.
*
* Do any action in external database.
*
* @param object $user Userobject before delete (without system magic quotes)
* @return void
*/
function user_delete($olduser) {
//override if needed
return;
}
/**
* Returns true if plugin allows resetting of internal password.
*
* @return bool
*/
function can_reset_password() {
//override if needed
return false;
}
/**
* Returns true if plugin allows resetting of internal password.
*
* @return bool
*/
function can_signup() {
//override if needed
return false;
}
/**
* Sign up a new user ready for confirmation.
* Password is passed in plaintext.
*
* @param object $user new user object
* @param boolean $notify print notice with link and terminate
*/
function user_signup($user, $notify=true) {
//override when can signup
print_error('mustbeoveride', 'debug', '', 'user_signup()' );
}
/**
* Return a form to capture user details for account creation.
* This is used in /login/signup.php.
* @return moodle_form A form which edits a record from the user table.
*/
function signup_form() {
global $CFG;
require_once($CFG->dirroot.'/login/signup_form.php');
return new login_signup_form(null, null, 'post', '', array('autocomplete'=>'on'));
}
/**
* Returns true if plugin allows confirming of new users.
*
* @return bool
*/
function can_confirm() {
//override if needed
return false;
}
/**
* Confirm the new user as registered.
*
* @param string $username
* @param string $confirmsecret
*/
function user_confirm($username, $confirmsecret) {
//override when can confirm
print_error('mustbeoveride', 'debug', '', 'user_confirm()' );
}
/**
* Checks if user exists in external db
*
* @param string $username (with system magic quotes)
* @return bool
*/
function user_exists($username) {
//override if needed
return false;
}
/**
* return number of days to user password expires
*
* If userpassword does not expire it should return 0. If password is already expired
* it should return negative value.
*
* @param mixed $username username (with system magic quotes)
* @return integer
*/
function password_expire($username) {
return 0;
}
/**
* Sync roles for this user - usually creator
*
* @param $user object user object (without system magic quotes)
*/
function sync_roles($user) {
//override if needed
}
/**
* Read user information from external database and returns it as array().
* Function should return all information available. If you are saving
* this information to moodle user-table you should honour synchronisation flags
*
* @param string $username username
*
* @return mixed array with no magic quotes or false on error
*/
function get_userinfo($username) {
//override if needed
return array();
}
/**
* Prints a form for configuring this authentication plugin.
*
* This function is called from admin/auth.php, and outputs a full page with
* a form for configuring this plugin.
*
* @param object $config
* @param object $err
* @param array $user_fields
* @deprecated since Moodle 3.3
*/
function config_form($config, $err, $user_fields) {
debugging('Use of config.html files have been deprecated, please update your code to use the admin settings API.');
//override if needed
}
/**
* A chance to validate form data, and last chance to
* do stuff before it is inserted in config_plugin
* @param object object with submitted configuration settings (without system magic quotes)
* @param array $err array of error messages
* @deprecated since Moodle 3.3
*/
function validate_form($form, &$err) {
debugging('Use of config.html files have been deprecated, please update your code to use the admin settings API.');
//override if needed
}
/**
* Processes and stores configuration data for this authentication plugin.
*
* @param object object with submitted configuration settings (without system magic quotes)
* @deprecated since Moodle 3.3
*/
function process_config($config) {
debugging('Use of config.html files have been deprecated, please update your code to use the admin settings API.');
//override if needed
return true;
}
/**
* Hook for overriding behaviour of login page.
* This method is called from login/index.php page for all enabled auth plugins.
*
* @global object
* @global object
*/
function loginpage_hook() {
global $frm; // can be used to override submitted login form
global $user; // can be used to replace authenticate_user_login()
//override if needed
}
/**
* Hook for overriding behaviour before going to the login page.
*
* This method is called from require_login from potentially any page for
* all enabled auth plugins and gives each plugin a chance to redirect
* directly to an external login page, or to instantly login a user where
* possible.
*
* If an auth plugin implements this hook, it must not rely on ONLY this
* hook in order to work, as there are many ways a user can browse directly
* to the standard login page. As a general rule in this case you should
* also implement the loginpage_hook as well.
*
*/
function pre_loginpage_hook() {
// override if needed, eg by redirecting to an external login page
// or logging in a user:
// complete_user_login($user);
}
/**
* Pre user_login hook.
* This method is called from authenticate_user_login() right after the user
* object is generated. This gives the auth plugins an option to make adjustments
* before the verification process starts.
*
* @param object $user user object, later used for $USER
*/
public function pre_user_login_hook(&$user) {
// Override if needed.
}
/**
* Post authentication hook.
* This method is called from authenticate_user_login() for all enabled auth plugins.
*
* @param object $user user object, later used for $USER
* @param string $username (with system magic quotes)
* @param string $password plain text password (with system magic quotes)
*/
function user_authenticated_hook(&$user, $username, $password) {
//override if needed
}
/**
* Pre logout hook.
* This method is called from require_logout() for all enabled auth plugins,
*
* @global object
*/
function prelogout_hook() {
global $USER; // use $USER->auth to find the plugin used for login
//override if needed
}
/**
* Hook for overriding behaviour of logout page.
* This method is called from login/logout.php page for all enabled auth plugins.
*
* @global object
* @global string
*/
function logoutpage_hook() {
global $USER; // use $USER->auth to find the plugin used for login
global $redirect; // can be used to override redirect after logout
//override if needed
}
/**
* Hook called before timing out of database session.
* This is useful for SSO and MNET.
*
* @param object $user
* @param string $sid session id
* @param int $timecreated start of session
* @param int $timemodified user last seen
* @return bool true means do not timeout session yet
*/
function ignore_timeout_hook($user, $sid, $timecreated, $timemodified) {
return false;
}
/**
* Return the properly translated human-friendly title of this auth plugin
*
* @todo Document this function
*/
function get_title() {
return get_string('pluginname', "auth_{$this->authtype}");
}
/**
* Get the auth description (from core or own auth lang files)
*
* @return string The description
*/
function get_description() {
$authdescription = get_string("auth_{$this->authtype}description", "auth_{$this->authtype}");
return $authdescription;
}
/**
* Returns whether or not the captcha element is enabled.
*
* @abstract Implement in child classes
* @return bool
*/
function is_captcha_enabled() {
return false;
}
/**
* Returns whether or not this authentication plugin can be manually set
* for users, for example, when bulk uploading users.
*
* This should be overriden by authentication plugins where setting the
* authentication method manually is allowed.
*
* @return bool
* @since Moodle 2.6
*/
function can_be_manually_set() {
// Override if needed.
return false;
}
/**
* Returns a list of potential IdPs that this authentication plugin supports.
*
* This is used to provide links on the login page and the login block.
*
* The parameter $wantsurl is typically used by the plugin to implement a
* return-url feature.
*
* The returned value is expected to be a list of associative arrays with
* string keys:
*
* - url => (moodle_url|string) URL of the page to send the user to for authentication
* - name => (string) Human readable name of the IdP
* - iconurl => (moodle_url|string) URL of the icon representing the IdP (since Moodle 3.3)
*
* For legacy reasons, pre-3.3 plugins can provide the icon via the key:
*
* - icon => (pix_icon) Icon representing the IdP
*
* @param string $wantsurl The relative url fragment the user wants to get to.
* @return array List of associative arrays with keys url, name, iconurl|icon
*/
function loginpage_idp_list($wantsurl) {
return array();
}
/**
* Return custom user profile fields.
*
* @return array list of custom fields.
*/
public function get_custom_user_profile_fields() {
global $CFG;
require_once($CFG->dirroot . '/user/profile/lib.php');
// If already retrieved then return.
if (!is_null($this->customfields)) {
return $this->customfields;
}
$this->customfields = array();
if ($proffields = profile_get_custom_fields()) {
foreach ($proffields as $proffield) {
$this->customfields[] = 'profile_field_'.$proffield->shortname;
}
}
unset($proffields);
return $this->customfields;
}
/**
* Post logout hook.
*
* This method is used after moodle logout by auth classes to execute server logout.
*
* @param stdClass $user clone of USER object before the user session was terminated
*/
public function postlogout_hook($user) {
}
/**
* Update a local user record from an external source.
* This is a lighter version of the one in moodlelib -- won't do
* expensive ops such as enrolment.
*
* @param string $username username
* @param array $updatekeys fields to update, false updates all fields.
* @param bool $triggerevent set false if user_updated event should not be triggered.
* This will not affect user_password_updated event triggering.
* @param bool $suspenduser Should the user be suspended?
* @return stdClass|bool updated user record or false if there is no new info to update.
*/
protected function update_user_record($username, $updatekeys = false, $triggerevent = false, $suspenduser = false) {
global $CFG, $DB;
require_once($CFG->dirroot.'/user/profile/lib.php');
// Just in case check text case.
$username = trim(core_text::strtolower($username));
// Get the current user record.
$user = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id));
if (empty($user)) { // Trouble.
error_log($this->errorlogtag . get_string('auth_usernotexist', 'auth', $username));
print_error('auth_usernotexist', 'auth', '', $username);
die;
}
// Protect the userid from being overwritten.
$userid = $user->id;
$needsupdate = false;
if ($newinfo = $this->get_userinfo($username)) {
$newinfo = truncate_userinfo($newinfo);
if (empty($updatekeys)) { // All keys? this does not support removing values.
$updatekeys = array_keys($newinfo);
}
if (!empty($updatekeys)) {
$newuser = new stdClass();
$newuser->id = $userid;
// The cast to int is a workaround for MDL-53959.
$newuser->suspended = (int) $suspenduser;
// Load all custom fields.
$profilefields = (array) profile_user_record($user->id, false);
$newprofilefields = [];
foreach ($updatekeys as $key) {
if (isset($newinfo[$key])) {
$value = $newinfo[$key];
} else {
$value = '';
}
if (!empty($this->config->{'field_updatelocal_' . $key})) {
if (preg_match('/^profile_field_(.*)$/', $key, $match)) {
// Custom field.
$field = $match[1];
$currentvalue = isset($profilefields[$field]) ? $profilefields[$field] : null;
$newprofilefields[$field] = $value;
} else {
// Standard field.
$currentvalue = isset($user->$key) ? $user->$key : null;
$newuser->$key = $value;
}
// Only update if it's changed.
if ($currentvalue !== $value) {
$needsupdate = true;
}
}
}
}
if ($needsupdate) {
user_update_user($newuser, false, $triggerevent);
profile_save_custom_fields($newuser->id, $newprofilefields);
return $DB->get_record('user', array('id' => $userid, 'deleted' => 0));
}
}
return false;
}
/**
* Return the list of enabled identity providers.
*
* Each identity provider data contains the keys url, name and iconurl (or
* icon). See the documentation of {@link auth_plugin_base::loginpage_idp_list()}
* for detailed description of the returned structure.
*
* @param array $authsequence site's auth sequence (list of auth plugins ordered)
* @return array List of arrays describing the identity providers
*/
public static function get_identity_providers($authsequence) {
global $SESSION;
$identityproviders = [];
foreach ($authsequence as $authname) {
$authplugin = get_auth_plugin($authname);
$wantsurl = (isset($SESSION->wantsurl)) ? $SESSION->wantsurl : '';
$identityproviders = array_merge($identityproviders, $authplugin->loginpage_idp_list($wantsurl));
}
return $identityproviders;
}
/**
* Prepare a list of identity providers for output.
*
* @param array $identityproviders as returned by {@link self::get_identity_providers()}
* @param renderer_base $output
* @return array the identity providers ready for output
*/
public static function prepare_identity_providers_for_output($identityproviders, renderer_base $output) {
$data = [];
foreach ($identityproviders as $idp) {
if (!empty($idp['icon'])) {
// Pre-3.3 auth plugins provide icon as a pix_icon instance. New auth plugins (since 3.3) provide iconurl.
$idp['iconurl'] = $output->image_url($idp['icon']->pix, $idp['icon']->component);
}
if ($idp['iconurl'] instanceof moodle_url) {
$idp['iconurl'] = $idp['iconurl']->out(false);
}
unset($idp['icon']);
if ($idp['url'] instanceof moodle_url) {
$idp['url'] = $idp['url']->out(false);
}
$data[] = $idp;
}
return $data;
}
/**
* Returns information on how the specified user can change their password.
*
* @param stdClass $user A user object
* @return string[] An array of strings with keys subject and message
*/
public function get_password_change_info(stdClass $user) : array {
global $USER;
$site = get_site();
$systemcontext = context_system::instance();
$data = new stdClass();
$data->firstname = $user->firstname;
$data->lastname = $user->lastname;
$data->username = $user->username;
$data->sitename = format_string($site->fullname);
$data->admin = generate_email_signoff();
// This is a workaround as change_password_url() is designed to allow
// use of the $USER global. See MDL-66984.
$olduser = $USER;
$USER = $user;
if ($this->can_change_password() and $this->change_password_url()) {
// We have some external url for password changing.
$data->link = $this->change_password_url()->out();
} else {
// No way to change password, sorry.
$data->link = '';
}
$USER = $olduser;
if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
$subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
$message = get_string('emailpasswordchangeinfo', '', $data);
} else {
$subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
$message = get_string('emailpasswordchangeinfofail', '', $data);
}
return [
'subject' => $subject,
'message' => $message
];
}
}
/**
* Verify if user is locked out.
*
* @param stdClass $user
* @return bool true if user locked out
*/
function login_is_lockedout($user) {
global $CFG;
if ($user->mnethostid != $CFG->mnet_localhost_id) {
return false;
}
if (isguestuser($user)) {
return false;
}
if (empty($CFG->lockoutthreshold)) {
// Lockout not enabled.
return false;
}
if (get_user_preferences('login_lockout_ignored', 0, $user)) {
// This preference may be used for accounts that must not be locked out.
return false;
}
$locked = get_user_preferences('login_lockout', 0, $user);
if (!$locked) {
return false;
}
if (empty($CFG->lockoutduration)) {
// Locked out forever.
return true;
}
if (time() - $locked < $CFG->lockoutduration) {
return true;
}
login_unlock_account($user);
return false;
}
/**
* To be called after valid user login.
* @param stdClass $user
*/
function login_attempt_valid($user) {
global $CFG;
// Note: user_loggedin event is triggered in complete_user_login().
if ($user->mnethostid != $CFG->mnet_localhost_id) {
return;
}
if (isguestuser($user)) {
return;
}
// Always unlock here, there might be some race conditions or leftovers when switching threshold.
login_unlock_account($user);
}
/**
* To be called after failed user login.
* @param stdClass $user
* @throws moodle_exception
*/
function login_attempt_failed($user) {
global $CFG;
if ($user->mnethostid != $CFG->mnet_localhost_id) {
return;
}
if (isguestuser($user)) {
return;
}
// Force user preferences cache reload to ensure the most up-to-date login_failed_count is fetched.
// This is perhaps overzealous but is the documented way of reloading the cache, as per the test method
// 'test_check_user_preferences_loaded'.
unset($user->preference);
$resource = 'user:' . $user->id;
$lockfactory = \core\lock\lock_config::get_lock_factory('core_failed_login_count_lock');
// Get a new lock for the resource, waiting for it for a maximum of 10 seconds.
if ($lock = $lockfactory->get_lock($resource, 10)) {
try {
$count = get_user_preferences('login_failed_count', 0, $user);
$last = get_user_preferences('login_failed_last', 0, $user);
$sincescuccess = get_user_preferences('login_failed_count_since_success', $count, $user);
$sincescuccess = $sincescuccess + 1;
set_user_preference('login_failed_count_since_success', $sincescuccess, $user);
if (empty($CFG->lockoutthreshold)) {
// No threshold means no lockout.
// Always unlock here, there might be some race conditions or leftovers when switching threshold.
login_unlock_account($user);
$lock->release();
return;
}
if (!empty($CFG->lockoutwindow) and time() - $last > $CFG->lockoutwindow) {
$count = 0;
}
$count = $count + 1;
set_user_preference('login_failed_count', $count, $user);
set_user_preference('login_failed_last', time(), $user);
if ($count >= $CFG->lockoutthreshold) {
login_lock_account($user);
}
// Release locks when we're done.
$lock->release();
} catch (Exception $e) {
// Always release the lock on a failure.
$lock->release();
}
} else {
// We did not get access to the resource in time, give up.
throw new moodle_exception('locktimeout');
}
}
/**
* Lockout user and send notification email.
*
* @param stdClass $user
*/
function login_lock_account($user) {
global $CFG;
if ($user->mnethostid != $CFG->mnet_localhost_id) {
return;
}
if (isguestuser($user)) {
return;
}
if (get_user_preferences('login_lockout_ignored', 0, $user)) {
// This user can not be locked out.
return;
}
$alreadylockedout = get_user_preferences('login_lockout', 0, $user);
set_user_preference('login_lockout', time(), $user);
if ($alreadylockedout == 0) {
$secret = random_string(15);
set_user_preference('login_lockout_secret', $secret, $user);
$oldforcelang = force_current_language($user->lang);
$site = get_site();
$supportuser = core_user::get_support_user();
$data = new stdClass();
$data->firstname = $user->firstname;
$data->lastname = $user->lastname;
$data->username = $user->username;
$data->sitename = format_string($site->fullname);
$data->link = $CFG->wwwroot.'/login/unlock_account.php?u='.$user->id.'&s='.$secret;
$data->admin = generate_email_signoff();
$message = get_string('lockoutemailbody', 'admin', $data);
$subject = get_string('lockoutemailsubject', 'admin', format_string($site->fullname));
if ($message) {
// Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
email_to_user($user, $supportuser, $subject, $message);
}
force_current_language($oldforcelang);
}
}
/**
* Unlock user account and reset timers.
*
* @param stdClass $user
*/
function login_unlock_account($user) {