[ Index ]

PHP Cross Reference of moodle-2.8

title

Body

[close]

/lib/ -> authlib.php (source)

   1  <?php
   2  
   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.
  14  //
  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/>.
  17  
  18  /**
  19   * Multiple plugin authentication Support library
  20   *
  21   * 2006-08-28  File created, AUTH return values defined.
  22   *
  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
  27   */
  28  
  29  defined('MOODLE_INTERNAL') || die();
  30  
  31  /**
  32   * Returned when the login was successful.
  33   */
  34  define('AUTH_OK',     0);
  35  
  36  /**
  37   * Returned when the login was unsuccessful.
  38   */
  39  define('AUTH_FAIL',   1);
  40  
  41  /**
  42   * Returned when the login was denied (a reason for AUTH_FAIL).
  43   */
  44  define('AUTH_DENIED', 2);
  45  
  46  /**
  47   * Returned when some error occurred (a reason for AUTH_FAIL).
  48   */
  49  define('AUTH_ERROR',  4);
  50  
  51  /**
  52   * Authentication - error codes for user confirm
  53   */
  54  define('AUTH_CONFIRM_FAIL', 0);
  55  define('AUTH_CONFIRM_OK', 1);
  56  define('AUTH_CONFIRM_ALREADY', 2);
  57  define('AUTH_CONFIRM_ERROR', 3);
  58  
  59  # MDL-14055
  60  define('AUTH_REMOVEUSER_KEEP', 0);
  61  define('AUTH_REMOVEUSER_SUSPEND', 1);
  62  define('AUTH_REMOVEUSER_FULLDELETE', 2);
  63  
  64  /** Login attempt successful. */
  65  define('AUTH_LOGIN_OK', 0);
  66  
  67  /** Can not login because user does not exist. */
  68  define('AUTH_LOGIN_NOUSER', 1);
  69  
  70  /** Can not login because user is suspended. */
  71  define('AUTH_LOGIN_SUSPENDED', 2);
  72  
  73  /** Can not login, most probably password did not match. */
  74  define('AUTH_LOGIN_FAILED', 3);
  75  
  76  /** Can not login because user is locked out. */
  77  define('AUTH_LOGIN_LOCKOUT', 4);
  78  
  79  /** Can not login becauser user is not authorised. */
  80  define('AUTH_LOGIN_UNAUTHORISED', 5);
  81  
  82  /**
  83   * Abstract authentication plugin.
  84   *
  85   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  86   * @package moodlecore
  87   */
  88  class auth_plugin_base {
  89  
  90      /**
  91       * The configuration details for the plugin.
  92       * @var object
  93       */
  94      var $config;
  95  
  96      /**
  97       * Authentication plugin type - the same as db field.
  98       * @var string
  99       */
 100      var $authtype;
 101      /*
 102       * The fields we can lock and update from/to external authentication backends
 103       * @var array
 104       */
 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      );
 121  
 122      /**
 123       * Moodle custom fields to sync with.
 124       * @var array()
 125       */
 126      var $customfields = null;
 127  
 128      /**
 129       * This is the primary method that is used by the authenticate_user_login()
 130       * function in moodlelib.php.
 131       *
 132       * This method should return a boolean indicating
 133       * whether or not the username and password authenticate successfully.
 134       *
 135       * Returns true if the username and password work and false if they are
 136       * wrong or don't exist.
 137       *
 138       * @param string $username The username (with system magic quotes)
 139       * @param string $password The password (with system magic quotes)
 140       *
 141       * @return bool Authentication success or failure.
 142       */
 143      function user_login($username, $password) {
 144          print_error('mustbeoveride', 'debug', '', 'user_login()' );
 145      }
 146  
 147      /**
 148       * Returns true if this authentication plugin can change the users'
 149       * password.
 150       *
 151       * @return bool
 152       */
 153      function can_change_password() {
 154          //override if needed
 155          return false;
 156      }
 157  
 158      /**
 159       * Returns the URL for changing the users' passwords, or empty if the default
 160       * URL can be used.
 161       *
 162       * This method is used if can_change_password() returns true.
 163       * This method is called only when user is logged in, it may use global $USER.
 164       * If you are using a plugin config variable in this method, please make sure it is set before using it,
 165       * as this method can be called even if the plugin is disabled, in which case the config values won't be set.
 166       *
 167       * @return moodle_url url of the profile page or null if standard used
 168       */
 169      function change_password_url() {
 170          //override if needed
 171          return null;
 172      }
 173  
 174      /**
 175       * Returns true if this authentication plugin can edit the users'
 176       * profile.
 177       *
 178       * @return bool
 179       */
 180      function can_edit_profile() {
 181          //override if needed
 182          return true;
 183      }
 184  
 185      /**
 186       * Returns the URL for editing the users' profile, or empty if the default
 187       * URL can be used.
 188       *
 189       * This method is used if can_edit_profile() returns true.
 190       * This method is called only when user is logged in, it may use global $USER.
 191       *
 192       * @return moodle_url url of the profile page or null if standard used
 193       */
 194      function edit_profile_url() {
 195          //override if needed
 196          return null;
 197      }
 198  
 199      /**
 200       * Returns true if this authentication plugin is "internal".
 201       *
 202       * Internal plugins use password hashes from Moodle user table for authentication.
 203       *
 204       * @return bool
 205       */
 206      function is_internal() {
 207          //override if needed
 208          return true;
 209      }
 210  
 211      /**
 212       * Indicates if password hashes should be stored in local moodle database.
 213       * @return bool true means md5 password hash stored in user table, false means flag 'not_cached' stored there instead
 214       */
 215      function prevent_local_passwords() {
 216          return !$this->is_internal();
 217      }
 218  
 219      /**
 220       * Indicates if moodle should automatically update internal user
 221       * records with data from external sources using the information
 222       * from get_userinfo() method.
 223       *
 224       * @return bool true means automatically copy data from ext to user table
 225       */
 226      function is_synchronised_with_external() {
 227          return !$this->is_internal();
 228      }
 229  
 230      /**
 231       * Updates the user's password.
 232       *
 233       * In previous versions of Moodle, the function
 234       * auth_user_update_password accepted a username as the first parameter. The
 235       * revised function expects a user object.
 236       *
 237       * @param  object  $user        User table object
 238       * @param  string  $newpassword Plaintext password
 239       *
 240       * @return bool                  True on success
 241       */
 242      function user_update_password($user, $newpassword) {
 243          //override if needed
 244          return true;
 245      }
 246  
 247      /**
 248       * Called when the user record is updated.
 249       * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
 250       * compares information saved modified information to external db.
 251       *
 252       * @param mixed $olduser     Userobject before modifications    (without system magic quotes)
 253       * @param mixed $newuser     Userobject new modified userobject (without system magic quotes)
 254       * @return boolean true if updated or update ignored; false if error
 255       *
 256       */
 257      function user_update($olduser, $newuser) {
 258          //override if needed
 259          return true;
 260      }
 261  
 262      /**
 263       * User delete requested - internal user record is mared as deleted already, username not present anymore.
 264       *
 265       * Do any action in external database.
 266       *
 267       * @param object $user       Userobject before delete    (without system magic quotes)
 268       * @return void
 269       */
 270      function user_delete($olduser) {
 271          //override if needed
 272          return;
 273      }
 274  
 275      /**
 276       * Returns true if plugin allows resetting of internal password.
 277       *
 278       * @return bool
 279       */
 280      function can_reset_password() {
 281          //override if needed
 282          return false;
 283      }
 284  
 285      /**
 286       * Returns true if plugin allows resetting of internal password.
 287       *
 288       * @return bool
 289       */
 290      function can_signup() {
 291          //override if needed
 292          return false;
 293      }
 294  
 295      /**
 296       * Sign up a new user ready for confirmation.
 297       * Password is passed in plaintext.
 298       *
 299       * @param object $user new user object
 300       * @param boolean $notify print notice with link and terminate
 301       */
 302      function user_signup($user, $notify=true) {
 303          //override when can signup
 304          print_error('mustbeoveride', 'debug', '', 'user_signup()' );
 305      }
 306  
 307      /**
 308       * Return a form to capture user details for account creation.
 309       * This is used in /login/signup.php.
 310       * @return moodle_form A form which edits a record from the user table.
 311       */
 312      function signup_form() {
 313          global $CFG;
 314  
 315          require_once($CFG->dirroot.'/login/signup_form.php');
 316          return new login_signup_form(null, null, 'post', '', array('autocomplete'=>'on'));
 317      }
 318  
 319      /**
 320       * Returns true if plugin allows confirming of new users.
 321       *
 322       * @return bool
 323       */
 324      function can_confirm() {
 325          //override if needed
 326          return false;
 327      }
 328  
 329      /**
 330       * Confirm the new user as registered.
 331       *
 332       * @param string $username
 333       * @param string $confirmsecret
 334       */
 335      function user_confirm($username, $confirmsecret) {
 336          //override when can confirm
 337          print_error('mustbeoveride', 'debug', '', 'user_confirm()' );
 338      }
 339  
 340      /**
 341       * Checks if user exists in external db
 342       *
 343       * @param string $username (with system magic quotes)
 344       * @return bool
 345       */
 346      function user_exists($username) {
 347          //override if needed
 348          return false;
 349      }
 350  
 351      /**
 352       * return number of days to user password expires
 353       *
 354       * If userpassword does not expire it should return 0. If password is already expired
 355       * it should return negative value.
 356       *
 357       * @param mixed $username username (with system magic quotes)
 358       * @return integer
 359       */
 360      function password_expire($username) {
 361          return 0;
 362      }
 363      /**
 364       * Sync roles for this user - usually creator
 365       *
 366       * @param $user object user object (without system magic quotes)
 367       */
 368      function sync_roles($user) {
 369          //override if needed
 370      }
 371  
 372      /**
 373       * Read user information from external database and returns it as array().
 374       * Function should return all information available. If you are saving
 375       * this information to moodle user-table you should honour synchronisation flags
 376       *
 377       * @param string $username username
 378       *
 379       * @return mixed array with no magic quotes or false on error
 380       */
 381      function get_userinfo($username) {
 382          //override if needed
 383          return array();
 384      }
 385  
 386      /**
 387       * Prints a form for configuring this authentication plugin.
 388       *
 389       * This function is called from admin/auth.php, and outputs a full page with
 390       * a form for configuring this plugin.
 391       *
 392       * @param object $config
 393       * @param object $err
 394       * @param array $user_fields
 395       */
 396      function config_form($config, $err, $user_fields) {
 397          //override if needed
 398      }
 399  
 400      /**
 401       * A chance to validate form data, and last chance to
 402       * do stuff before it is inserted in config_plugin
 403       * @param object object with submitted configuration settings (without system magic quotes)
 404       * @param array $err array of error messages
 405       */
 406       function validate_form($form, &$err) {
 407          //override if needed
 408      }
 409  
 410      /**
 411       * Processes and stores configuration data for this authentication plugin.
 412       *
 413       * @param object object with submitted configuration settings (without system magic quotes)
 414       */
 415      function process_config($config) {
 416          //override if needed
 417          return true;
 418      }
 419  
 420      /**
 421       * Hook for overriding behaviour of login page.
 422       * This method is called from login/index.php page for all enabled auth plugins.
 423       *
 424       * @global object
 425       * @global object
 426       */
 427      function loginpage_hook() {
 428          global $frm;  // can be used to override submitted login form
 429          global $user; // can be used to replace authenticate_user_login()
 430  
 431          //override if needed
 432      }
 433  
 434      /**
 435       * Post authentication hook.
 436       * This method is called from authenticate_user_login() for all enabled auth plugins.
 437       *
 438       * @param object $user user object, later used for $USER
 439       * @param string $username (with system magic quotes)
 440       * @param string $password plain text password (with system magic quotes)
 441       */
 442      function user_authenticated_hook(&$user, $username, $password) {
 443          //override if needed
 444      }
 445  
 446      /**
 447       * Pre logout hook.
 448       * This method is called from require_logout() for all enabled auth plugins,
 449       *
 450       * @global object
 451       */
 452      function prelogout_hook() {
 453          global $USER; // use $USER->auth to find the plugin used for login
 454  
 455          //override if needed
 456      }
 457  
 458      /**
 459       * Hook for overriding behaviour of logout page.
 460       * This method is called from login/logout.php page for all enabled auth plugins.
 461       *
 462       * @global object
 463       * @global string
 464       */
 465      function logoutpage_hook() {
 466          global $USER;     // use $USER->auth to find the plugin used for login
 467          global $redirect; // can be used to override redirect after logout
 468  
 469          //override if needed
 470      }
 471  
 472      /**
 473       * Hook called before timing out of database session.
 474       * This is useful for SSO and MNET.
 475       *
 476       * @param object $user
 477       * @param string $sid session id
 478       * @param int $timecreated start of session
 479       * @param int $timemodified user last seen
 480       * @return bool true means do not timeout session yet
 481       */
 482      function ignore_timeout_hook($user, $sid, $timecreated, $timemodified) {
 483          return false;
 484      }
 485  
 486      /**
 487       * Return the properly translated human-friendly title of this auth plugin
 488       *
 489       * @todo Document this function
 490       */
 491      function get_title() {
 492          return get_string('pluginname', "auth_{$this->authtype}");
 493      }
 494  
 495      /**
 496       * Get the auth description (from core or own auth lang files)
 497       *
 498       * @return string The description
 499       */
 500      function get_description() {
 501          $authdescription = get_string("auth_{$this->authtype}description", "auth_{$this->authtype}");
 502          return $authdescription;
 503      }
 504  
 505      /**
 506       * Returns whether or not the captcha element is enabled, and the admin settings fulfil its requirements.
 507       *
 508       * @abstract Implement in child classes
 509       * @return bool
 510       */
 511      function is_captcha_enabled() {
 512          return false;
 513      }
 514  
 515      /**
 516       * Returns whether or not this authentication plugin can be manually set
 517       * for users, for example, when bulk uploading users.
 518       *
 519       * This should be overriden by authentication plugins where setting the
 520       * authentication method manually is allowed.
 521       *
 522       * @return bool
 523       * @since Moodle 2.6
 524       */
 525      function can_be_manually_set() {
 526          // Override if needed.
 527          return false;
 528      }
 529  
 530      /**
 531       * Returns a list of potential IdPs that this authentication plugin supports.
 532       * This is used to provide links on the login page.
 533       *
 534       * @param string $wantsurl the relative url fragment the user wants to get to.  You can use this to compose a returnurl, for example
 535       *
 536       * @return array like:
 537       *              array(
 538       *                  array(
 539       *                      'url' => 'http://someurl',
 540       *                      'icon' => new pix_icon(...),
 541       *                      'name' => get_string('somename', 'auth_yourplugin'),
 542       *                 ),
 543       *             )
 544       */
 545      function loginpage_idp_list($wantsurl) {
 546          return array();
 547      }
 548  
 549      /**
 550       * Return custom user profile fields.
 551       *
 552       * @return array list of custom fields.
 553       */
 554      public function get_custom_user_profile_fields() {
 555          global $DB;
 556          // If already retrieved then return.
 557          if (!is_null($this->customfields)) {
 558              return $this->customfields;
 559          }
 560  
 561          $this->customfields = array();
 562          if ($proffields = $DB->get_records('user_info_field')) {
 563              foreach ($proffields as $proffield) {
 564                  $this->customfields[] = 'profile_field_'.$proffield->shortname;
 565              }
 566          }
 567          unset($proffields);
 568  
 569          return $this->customfields;
 570      }
 571  
 572      /**
 573       * Post logout hook.
 574       *
 575       * This method is used after moodle logout by auth classes to execute server logout.
 576       *
 577       * @param stdClass $user clone of USER object before the user session was terminated
 578       */
 579      public function postlogout_hook($user) {
 580      }
 581  }
 582  
 583  /**
 584   * Verify if user is locked out.
 585   *
 586   * @param stdClass $user
 587   * @return bool true if user locked out
 588   */
 589  function login_is_lockedout($user) {
 590      global $CFG;
 591  
 592      if ($user->mnethostid != $CFG->mnet_localhost_id) {
 593          return false;
 594      }
 595      if (isguestuser($user)) {
 596          return false;
 597      }
 598  
 599      if (empty($CFG->lockoutthreshold)) {
 600          // Lockout not enabled.
 601          return false;
 602      }
 603  
 604      if (get_user_preferences('login_lockout_ignored', 0, $user)) {
 605          // This preference may be used for accounts that must not be locked out.
 606          return false;
 607      }
 608  
 609      $locked = get_user_preferences('login_lockout', 0, $user);
 610      if (!$locked) {
 611          return false;
 612      }
 613  
 614      if (empty($CFG->lockoutduration)) {
 615          // Locked out forever.
 616          return true;
 617      }
 618  
 619      if (time() - $locked < $CFG->lockoutduration) {
 620          return true;
 621      }
 622  
 623      login_unlock_account($user);
 624  
 625      return false;
 626  }
 627  
 628  /**
 629   * To be called after valid user login.
 630   * @param stdClass $user
 631   */
 632  function login_attempt_valid($user) {
 633      global $CFG;
 634  
 635      // Note: user_loggedin event is triggered in complete_user_login().
 636  
 637      if ($user->mnethostid != $CFG->mnet_localhost_id) {
 638          return;
 639      }
 640      if (isguestuser($user)) {
 641          return;
 642      }
 643  
 644      // Always unlock here, there might be some race conditions or leftovers when switching threshold.
 645      login_unlock_account($user);
 646  }
 647  
 648  /**
 649   * To be called after failed user login.
 650   * @param stdClass $user
 651   */
 652  function login_attempt_failed($user) {
 653      global $CFG;
 654  
 655      if ($user->mnethostid != $CFG->mnet_localhost_id) {
 656          return;
 657      }
 658      if (isguestuser($user)) {
 659          return;
 660      }
 661  
 662      $count = get_user_preferences('login_failed_count', 0, $user);
 663      $last = get_user_preferences('login_failed_last', 0, $user);
 664      $sincescuccess = get_user_preferences('login_failed_count_since_success', $count, $user);
 665      $sincescuccess = $sincescuccess + 1;
 666      set_user_preference('login_failed_count_since_success', $sincescuccess, $user);
 667  
 668      if (empty($CFG->lockoutthreshold)) {
 669          // No threshold means no lockout.
 670          // Always unlock here, there might be some race conditions or leftovers when switching threshold.
 671          login_unlock_account($user);
 672          return;
 673      }
 674  
 675      if (!empty($CFG->lockoutwindow) and time() - $last > $CFG->lockoutwindow) {
 676          $count = 0;
 677      }
 678  
 679      $count = $count+1;
 680  
 681      set_user_preference('login_failed_count', $count, $user);
 682      set_user_preference('login_failed_last', time(), $user);
 683  
 684      if ($count >= $CFG->lockoutthreshold) {
 685          login_lock_account($user);
 686      }
 687  }
 688  
 689  /**
 690   * Lockout user and send notification email.
 691   *
 692   * @param stdClass $user
 693   */
 694  function login_lock_account($user) {
 695      global $CFG;
 696  
 697      if ($user->mnethostid != $CFG->mnet_localhost_id) {
 698          return;
 699      }
 700      if (isguestuser($user)) {
 701          return;
 702      }
 703  
 704      if (get_user_preferences('login_lockout_ignored', 0, $user)) {
 705          // This user can not be locked out.
 706          return;
 707      }
 708  
 709      $alreadylockedout = get_user_preferences('login_lockout', 0, $user);
 710  
 711      set_user_preference('login_lockout', time(), $user);
 712  
 713      if ($alreadylockedout == 0) {
 714          $secret = random_string(15);
 715          set_user_preference('login_lockout_secret', $secret, $user);
 716  
 717          $oldforcelang = force_current_language($user->lang);
 718  
 719          $site = get_site();
 720          $supportuser = core_user::get_support_user();
 721  
 722          $data = new stdClass();
 723          $data->firstname = $user->firstname;
 724          $data->lastname  = $user->lastname;
 725          $data->username  = $user->username;
 726          $data->sitename  = format_string($site->fullname);
 727          $data->link      = $CFG->wwwroot.'/login/unlock_account.php?u='.$user->id.'&s='.$secret;
 728          $data->admin     = generate_email_signoff();
 729  
 730          $message = get_string('lockoutemailbody', 'admin', $data);
 731          $subject = get_string('lockoutemailsubject', 'admin', format_string($site->fullname));
 732  
 733          if ($message) {
 734              // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
 735              email_to_user($user, $supportuser, $subject, $message);
 736          }
 737  
 738          force_current_language($oldforcelang);
 739      }
 740  }
 741  
 742  /**
 743   * Unlock user account and reset timers.
 744   *
 745   * @param stdClass $user
 746   */
 747  function login_unlock_account($user) {
 748      unset_user_preference('login_lockout', $user);
 749      unset_user_preference('login_failed_count', $user);
 750      unset_user_preference('login_failed_last', $user);
 751  
 752      // Note: do not clear the lockout secret because user might click on the link repeatedly.
 753  }


Generated: Fri Nov 28 20:29:05 2014 Cross-referenced by PHPXref 0.7.1