Merge branch 'wip-mdl-50675-m28' of https://github.com/rajeshtaneja/moodle into MOODL...
[moodle.git] / lib / authlib.php
blobdc2ceb90f0c7f775900cc3647bacd85c9e9b1fd7
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Multiple plugin authentication Support library
21 * 2006-08-28 File created, AUTH return values defined.
23 * @package core
24 * @subpackage auth
25 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
31 /**
32 * Returned when the login was successful.
34 define('AUTH_OK', 0);
36 /**
37 * Returned when the login was unsuccessful.
39 define('AUTH_FAIL', 1);
41 /**
42 * Returned when the login was denied (a reason for AUTH_FAIL).
44 define('AUTH_DENIED', 2);
46 /**
47 * Returned when some error occurred (a reason for AUTH_FAIL).
49 define('AUTH_ERROR', 4);
51 /**
52 * Authentication - error codes for user confirm
54 define('AUTH_CONFIRM_FAIL', 0);
55 define('AUTH_CONFIRM_OK', 1);
56 define('AUTH_CONFIRM_ALREADY', 2);
57 define('AUTH_CONFIRM_ERROR', 3);
59 # MDL-14055
60 define('AUTH_REMOVEUSER_KEEP', 0);
61 define('AUTH_REMOVEUSER_SUSPEND', 1);
62 define('AUTH_REMOVEUSER_FULLDELETE', 2);
64 /** Login attempt successful. */
65 define('AUTH_LOGIN_OK', 0);
67 /** Can not login because user does not exist. */
68 define('AUTH_LOGIN_NOUSER', 1);
70 /** Can not login because user is suspended. */
71 define('AUTH_LOGIN_SUSPENDED', 2);
73 /** Can not login, most probably password did not match. */
74 define('AUTH_LOGIN_FAILED', 3);
76 /** Can not login because user is locked out. */
77 define('AUTH_LOGIN_LOCKOUT', 4);
79 /** Can not login becauser user is not authorised. */
80 define('AUTH_LOGIN_UNAUTHORISED', 5);
82 /**
83 * Abstract authentication plugin.
85 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
86 * @package moodlecore
88 class auth_plugin_base {
90 /**
91 * The configuration details for the plugin.
92 * @var object
94 var $config;
96 /**
97 * Authentication plugin type - the same as db field.
98 * @var string
100 var $authtype;
102 * The fields we can lock and update from/to external authentication backends
103 * @var array
105 var $userfields = array(
106 'firstname',
107 'lastname',
108 'email',
109 'city',
110 'country',
111 'lang',
112 'description',
113 'url',
114 'idnumber',
115 'institution',
116 'department',
117 'phone1',
118 'phone2',
119 'address',
120 'firstnamephonetic',
121 'lastnamephonetic',
122 'middlename',
123 'alternatename'
127 * Moodle custom fields to sync with.
128 * @var array()
130 var $customfields = null;
133 * This is the primary method that is used by the authenticate_user_login()
134 * function in moodlelib.php.
136 * This method should return a boolean indicating
137 * whether or not the username and password authenticate successfully.
139 * Returns true if the username and password work and false if they are
140 * wrong or don't exist.
142 * @param string $username The username (with system magic quotes)
143 * @param string $password The password (with system magic quotes)
145 * @return bool Authentication success or failure.
147 function user_login($username, $password) {
148 print_error('mustbeoveride', 'debug', '', 'user_login()' );
152 * Returns true if this authentication plugin can change the users'
153 * password.
155 * @return bool
157 function can_change_password() {
158 //override if needed
159 return false;
163 * Returns the URL for changing the users' passwords, or empty if the default
164 * URL can be used.
166 * This method is used if can_change_password() returns true.
167 * This method is called only when user is logged in, it may use global $USER.
168 * If you are using a plugin config variable in this method, please make sure it is set before using it,
169 * as this method can be called even if the plugin is disabled, in which case the config values won't be set.
171 * @return moodle_url url of the profile page or null if standard used
173 function change_password_url() {
174 //override if needed
175 return null;
179 * Returns true if this authentication plugin can edit the users'
180 * profile.
182 * @return bool
184 function can_edit_profile() {
185 //override if needed
186 return true;
190 * Returns the URL for editing the users' profile, or empty if the default
191 * URL can be used.
193 * This method is used if can_edit_profile() returns true.
194 * This method is called only when user is logged in, it may use global $USER.
196 * @return moodle_url url of the profile page or null if standard used
198 function edit_profile_url() {
199 //override if needed
200 return null;
204 * Returns true if this authentication plugin is "internal".
206 * Internal plugins use password hashes from Moodle user table for authentication.
208 * @return bool
210 function is_internal() {
211 //override if needed
212 return true;
216 * Indicates if password hashes should be stored in local moodle database.
217 * @return bool true means md5 password hash stored in user table, false means flag 'not_cached' stored there instead
219 function prevent_local_passwords() {
220 return !$this->is_internal();
224 * Indicates if moodle should automatically update internal user
225 * records with data from external sources using the information
226 * from get_userinfo() method.
228 * @return bool true means automatically copy data from ext to user table
230 function is_synchronised_with_external() {
231 return !$this->is_internal();
235 * Updates the user's password.
237 * In previous versions of Moodle, the function
238 * auth_user_update_password accepted a username as the first parameter. The
239 * revised function expects a user object.
241 * @param object $user User table object
242 * @param string $newpassword Plaintext password
244 * @return bool True on success
246 function user_update_password($user, $newpassword) {
247 //override if needed
248 return true;
252 * Called when the user record is updated.
253 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
254 * compares information saved modified information to external db.
256 * @param mixed $olduser Userobject before modifications (without system magic quotes)
257 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
258 * @return boolean true if updated or update ignored; false if error
261 function user_update($olduser, $newuser) {
262 //override if needed
263 return true;
267 * User delete requested - internal user record is mared as deleted already, username not present anymore.
269 * Do any action in external database.
271 * @param object $user Userobject before delete (without system magic quotes)
272 * @return void
274 function user_delete($olduser) {
275 //override if needed
276 return;
280 * Returns true if plugin allows resetting of internal password.
282 * @return bool
284 function can_reset_password() {
285 //override if needed
286 return false;
290 * Returns true if plugin allows resetting of internal password.
292 * @return bool
294 function can_signup() {
295 //override if needed
296 return false;
300 * Sign up a new user ready for confirmation.
301 * Password is passed in plaintext.
303 * @param object $user new user object
304 * @param boolean $notify print notice with link and terminate
306 function user_signup($user, $notify=true) {
307 //override when can signup
308 print_error('mustbeoveride', 'debug', '', 'user_signup()' );
312 * Return a form to capture user details for account creation.
313 * This is used in /login/signup.php.
314 * @return moodle_form A form which edits a record from the user table.
316 function signup_form() {
317 global $CFG;
319 require_once($CFG->dirroot.'/login/signup_form.php');
320 return new login_signup_form(null, null, 'post', '', array('autocomplete'=>'on'));
324 * Returns true if plugin allows confirming of new users.
326 * @return bool
328 function can_confirm() {
329 //override if needed
330 return false;
334 * Confirm the new user as registered.
336 * @param string $username
337 * @param string $confirmsecret
339 function user_confirm($username, $confirmsecret) {
340 //override when can confirm
341 print_error('mustbeoveride', 'debug', '', 'user_confirm()' );
345 * Checks if user exists in external db
347 * @param string $username (with system magic quotes)
348 * @return bool
350 function user_exists($username) {
351 //override if needed
352 return false;
356 * return number of days to user password expires
358 * If userpassword does not expire it should return 0. If password is already expired
359 * it should return negative value.
361 * @param mixed $username username (with system magic quotes)
362 * @return integer
364 function password_expire($username) {
365 return 0;
368 * Sync roles for this user - usually creator
370 * @param $user object user object (without system magic quotes)
372 function sync_roles($user) {
373 //override if needed
377 * Read user information from external database and returns it as array().
378 * Function should return all information available. If you are saving
379 * this information to moodle user-table you should honour synchronisation flags
381 * @param string $username username
383 * @return mixed array with no magic quotes or false on error
385 function get_userinfo($username) {
386 //override if needed
387 return array();
391 * Prints a form for configuring this authentication plugin.
393 * This function is called from admin/auth.php, and outputs a full page with
394 * a form for configuring this plugin.
396 * @param object $config
397 * @param object $err
398 * @param array $user_fields
400 function config_form($config, $err, $user_fields) {
401 //override if needed
405 * A chance to validate form data, and last chance to
406 * do stuff before it is inserted in config_plugin
407 * @param object object with submitted configuration settings (without system magic quotes)
408 * @param array $err array of error messages
410 function validate_form($form, &$err) {
411 //override if needed
415 * Processes and stores configuration data for this authentication plugin.
417 * @param object object with submitted configuration settings (without system magic quotes)
419 function process_config($config) {
420 //override if needed
421 return true;
425 * Hook for overriding behaviour of login page.
426 * This method is called from login/index.php page for all enabled auth plugins.
428 * @global object
429 * @global object
431 function loginpage_hook() {
432 global $frm; // can be used to override submitted login form
433 global $user; // can be used to replace authenticate_user_login()
435 //override if needed
439 * Post authentication hook.
440 * This method is called from authenticate_user_login() for all enabled auth plugins.
442 * @param object $user user object, later used for $USER
443 * @param string $username (with system magic quotes)
444 * @param string $password plain text password (with system magic quotes)
446 function user_authenticated_hook(&$user, $username, $password) {
447 //override if needed
451 * Pre logout hook.
452 * This method is called from require_logout() for all enabled auth plugins,
454 * @global object
456 function prelogout_hook() {
457 global $USER; // use $USER->auth to find the plugin used for login
459 //override if needed
463 * Hook for overriding behaviour of logout page.
464 * This method is called from login/logout.php page for all enabled auth plugins.
466 * @global object
467 * @global string
469 function logoutpage_hook() {
470 global $USER; // use $USER->auth to find the plugin used for login
471 global $redirect; // can be used to override redirect after logout
473 //override if needed
477 * Hook called before timing out of database session.
478 * This is useful for SSO and MNET.
480 * @param object $user
481 * @param string $sid session id
482 * @param int $timecreated start of session
483 * @param int $timemodified user last seen
484 * @return bool true means do not timeout session yet
486 function ignore_timeout_hook($user, $sid, $timecreated, $timemodified) {
487 return false;
491 * Return the properly translated human-friendly title of this auth plugin
493 * @todo Document this function
495 function get_title() {
496 return get_string('pluginname', "auth_{$this->authtype}");
500 * Get the auth description (from core or own auth lang files)
502 * @return string The description
504 function get_description() {
505 $authdescription = get_string("auth_{$this->authtype}description", "auth_{$this->authtype}");
506 return $authdescription;
510 * Returns whether or not the captcha element is enabled, and the admin settings fulfil its requirements.
512 * @abstract Implement in child classes
513 * @return bool
515 function is_captcha_enabled() {
516 return false;
520 * Returns whether or not this authentication plugin can be manually set
521 * for users, for example, when bulk uploading users.
523 * This should be overriden by authentication plugins where setting the
524 * authentication method manually is allowed.
526 * @return bool
527 * @since Moodle 2.6
529 function can_be_manually_set() {
530 // Override if needed.
531 return false;
535 * Returns a list of potential IdPs that this authentication plugin supports.
536 * This is used to provide links on the login page.
538 * @param string $wantsurl the relative url fragment the user wants to get to. You can use this to compose a returnurl, for example
540 * @return array like:
541 * array(
542 * array(
543 * 'url' => 'http://someurl',
544 * 'icon' => new pix_icon(...),
545 * 'name' => get_string('somename', 'auth_yourplugin'),
546 * ),
549 function loginpage_idp_list($wantsurl) {
550 return array();
554 * Return custom user profile fields.
556 * @return array list of custom fields.
558 public function get_custom_user_profile_fields() {
559 global $DB;
560 // If already retrieved then return.
561 if (!is_null($this->customfields)) {
562 return $this->customfields;
565 $this->customfields = array();
566 if ($proffields = $DB->get_records('user_info_field')) {
567 foreach ($proffields as $proffield) {
568 $this->customfields[] = 'profile_field_'.$proffield->shortname;
571 unset($proffields);
573 return $this->customfields;
577 * Post logout hook.
579 * This method is used after moodle logout by auth classes to execute server logout.
581 * @param stdClass $user clone of USER object before the user session was terminated
583 public function postlogout_hook($user) {
588 * Verify if user is locked out.
590 * @param stdClass $user
591 * @return bool true if user locked out
593 function login_is_lockedout($user) {
594 global $CFG;
596 if ($user->mnethostid != $CFG->mnet_localhost_id) {
597 return false;
599 if (isguestuser($user)) {
600 return false;
603 if (empty($CFG->lockoutthreshold)) {
604 // Lockout not enabled.
605 return false;
608 if (get_user_preferences('login_lockout_ignored', 0, $user)) {
609 // This preference may be used for accounts that must not be locked out.
610 return false;
613 $locked = get_user_preferences('login_lockout', 0, $user);
614 if (!$locked) {
615 return false;
618 if (empty($CFG->lockoutduration)) {
619 // Locked out forever.
620 return true;
623 if (time() - $locked < $CFG->lockoutduration) {
624 return true;
627 login_unlock_account($user);
629 return false;
633 * To be called after valid user login.
634 * @param stdClass $user
636 function login_attempt_valid($user) {
637 global $CFG;
639 // Note: user_loggedin event is triggered in complete_user_login().
641 if ($user->mnethostid != $CFG->mnet_localhost_id) {
642 return;
644 if (isguestuser($user)) {
645 return;
648 // Always unlock here, there might be some race conditions or leftovers when switching threshold.
649 login_unlock_account($user);
653 * To be called after failed user login.
654 * @param stdClass $user
656 function login_attempt_failed($user) {
657 global $CFG;
659 if ($user->mnethostid != $CFG->mnet_localhost_id) {
660 return;
662 if (isguestuser($user)) {
663 return;
666 $count = get_user_preferences('login_failed_count', 0, $user);
667 $last = get_user_preferences('login_failed_last', 0, $user);
668 $sincescuccess = get_user_preferences('login_failed_count_since_success', $count, $user);
669 $sincescuccess = $sincescuccess + 1;
670 set_user_preference('login_failed_count_since_success', $sincescuccess, $user);
672 if (empty($CFG->lockoutthreshold)) {
673 // No threshold means no lockout.
674 // Always unlock here, there might be some race conditions or leftovers when switching threshold.
675 login_unlock_account($user);
676 return;
679 if (!empty($CFG->lockoutwindow) and time() - $last > $CFG->lockoutwindow) {
680 $count = 0;
683 $count = $count+1;
685 set_user_preference('login_failed_count', $count, $user);
686 set_user_preference('login_failed_last', time(), $user);
688 if ($count >= $CFG->lockoutthreshold) {
689 login_lock_account($user);
694 * Lockout user and send notification email.
696 * @param stdClass $user
698 function login_lock_account($user) {
699 global $CFG;
701 if ($user->mnethostid != $CFG->mnet_localhost_id) {
702 return;
704 if (isguestuser($user)) {
705 return;
708 if (get_user_preferences('login_lockout_ignored', 0, $user)) {
709 // This user can not be locked out.
710 return;
713 $alreadylockedout = get_user_preferences('login_lockout', 0, $user);
715 set_user_preference('login_lockout', time(), $user);
717 if ($alreadylockedout == 0) {
718 $secret = random_string(15);
719 set_user_preference('login_lockout_secret', $secret, $user);
721 $oldforcelang = force_current_language($user->lang);
723 $site = get_site();
724 $supportuser = core_user::get_support_user();
726 $data = new stdClass();
727 $data->firstname = $user->firstname;
728 $data->lastname = $user->lastname;
729 $data->username = $user->username;
730 $data->sitename = format_string($site->fullname);
731 $data->link = $CFG->wwwroot.'/login/unlock_account.php?u='.$user->id.'&s='.$secret;
732 $data->admin = generate_email_signoff();
734 $message = get_string('lockoutemailbody', 'admin', $data);
735 $subject = get_string('lockoutemailsubject', 'admin', format_string($site->fullname));
737 if ($message) {
738 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
739 email_to_user($user, $supportuser, $subject, $message);
742 force_current_language($oldforcelang);
747 * Unlock user account and reset timers.
749 * @param stdClass $user
751 function login_unlock_account($user) {
752 unset_user_preference('login_lockout', $user);
753 unset_user_preference('login_failed_count', $user);
754 unset_user_preference('login_failed_last', $user);
756 // Note: do not clear the lockout secret because user might click on the link repeatedly.