Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 310 and 311] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403] [Versions 39 and 311]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * Anobody can login with any password.
  19   *
  20   * @package auth_oauth2
  21   * @copyright 2017 Damyon Wiese
  22   * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  23   */
  24  
  25  namespace auth_oauth2;
  26  
  27  defined('MOODLE_INTERNAL') || die();
  28  
  29  use pix_icon;
  30  use moodle_url;
  31  use core_text;
  32  use context_system;
  33  use stdClass;
  34  use core\oauth2\issuer;
  35  use core\oauth2\client;
  36  
  37  require_once($CFG->libdir.'/authlib.php');
  38  require_once($CFG->dirroot.'/user/lib.php');
  39  require_once($CFG->dirroot.'/user/profile/lib.php');
  40  
  41  /**
  42   * Plugin for oauth2 authentication.
  43   *
  44   * @package auth_oauth2
  45   * @copyright 2017 Damyon Wiese
  46   * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  47   */
  48  class auth extends \auth_plugin_base {
  49  
  50      /**
  51       * @var stdClass $userinfo The set of user info returned from the oauth handshake
  52       */
  53      private static $userinfo;
  54  
  55      /**
  56       * @var stdClass $userpicture The url to a picture.
  57       */
  58      private static $userpicture;
  59  
  60      /**
  61       * Constructor.
  62       */
  63      public function __construct() {
  64          $this->authtype = 'oauth2';
  65          $this->config = get_config('auth_oauth2');
  66      }
  67  
  68      /**
  69       * Returns true if the username and password work or don't exist and false
  70       * if the user exists and the password is wrong.
  71       *
  72       * @param string $username The username
  73       * @param string $password The password
  74       * @return bool Authentication success or failure.
  75       */
  76      public function user_login($username, $password) {
  77          $cached = $this->get_static_user_info();
  78          if (empty($cached)) {
  79              // This means we were called as part of a normal login flow - without using oauth.
  80              return false;
  81          }
  82          $verifyusername = $cached['username'];
  83          if ($verifyusername == $username) {
  84              return true;
  85          }
  86          return false;
  87      }
  88  
  89      /**
  90       * We don't want to allow users setting an internal password.
  91       *
  92       * @return bool
  93       */
  94      public function prevent_local_passwords() {
  95          return true;
  96      }
  97  
  98      /**
  99       * Returns true if this authentication plugin is 'internal'.
 100       *
 101       * @return bool
 102       */
 103      public function is_internal() {
 104          return false;
 105      }
 106  
 107      /**
 108       * Indicates if moodle should automatically update internal user
 109       * records with data from external sources using the information
 110       * from auth_plugin_base::get_userinfo().
 111       *
 112       * @return bool true means automatically copy data from ext to user table
 113       */
 114      public function is_synchronised_with_external() {
 115          return true;
 116      }
 117  
 118      /**
 119       * Returns true if this authentication plugin can change the user's
 120       * password.
 121       *
 122       * @return bool
 123       */
 124      public function can_change_password() {
 125          return false;
 126      }
 127  
 128      /**
 129       * Returns the URL for changing the user's pw, or empty if the default can
 130       * be used.
 131       *
 132       * @return moodle_url
 133       */
 134      public function change_password_url() {
 135          return null;
 136      }
 137  
 138      /**
 139       * Returns true if plugin allows resetting of internal password.
 140       *
 141       * @return bool
 142       */
 143      public function can_reset_password() {
 144          return false;
 145      }
 146  
 147      /**
 148       * Returns true if plugin can be manually set.
 149       *
 150       * @return bool
 151       */
 152      public function can_be_manually_set() {
 153          return true;
 154      }
 155  
 156      /**
 157       * Return the userinfo from the oauth handshake. Will only be valid
 158       * for the logged in user.
 159       * @param string $username
 160       */
 161      public function get_userinfo($username) {
 162          $cached = $this->get_static_user_info();
 163          if (!empty($cached) && $cached['username'] == $username) {
 164              return $cached;
 165          }
 166          return false;
 167      }
 168  
 169      /**
 170       * Return a list of identity providers to display on the login page.
 171       *
 172       * @param string|moodle_url $wantsurl The requested URL.
 173       * @return array List of arrays with keys url, iconurl and name.
 174       */
 175      public function loginpage_idp_list($wantsurl) {
 176          $providers = \core\oauth2\api::get_all_issuers(true);
 177          $result = [];
 178          if (empty($wantsurl)) {
 179              $wantsurl = '/';
 180          }
 181          foreach ($providers as $idp) {
 182              if ($idp->is_available_for_login()) {
 183                  $params = ['id' => $idp->get('id'), 'wantsurl' => $wantsurl, 'sesskey' => sesskey()];
 184                  $url = new moodle_url('/auth/oauth2/login.php', $params);
 185                  $icon = $idp->get('image');
 186                  $result[] = ['url' => $url, 'iconurl' => $icon, 'name' => $idp->get_display_name()];
 187              }
 188          }
 189          return $result;
 190      }
 191  
 192      /**
 193       * Statically cache the user info from the oauth handshake
 194       * @param stdClass $userinfo
 195       */
 196      private function set_static_user_info($userinfo) {
 197          self::$userinfo = $userinfo;
 198      }
 199  
 200      /**
 201       * Get the static cached user info
 202       * @return stdClass
 203       */
 204      private function get_static_user_info() {
 205          return self::$userinfo;
 206      }
 207  
 208      /**
 209       * Statically cache the user picture from the oauth handshake
 210       * @param string $userpicture
 211       */
 212      private function set_static_user_picture($userpicture) {
 213          self::$userpicture = $userpicture;
 214      }
 215  
 216      /**
 217       * Get the static cached user picture
 218       * @return string
 219       */
 220      private function get_static_user_picture() {
 221          return self::$userpicture;
 222      }
 223  
 224      /**
 225       * If this user has no picture - but we got one from oauth - set it.
 226       * @param stdClass $user
 227       * @return boolean True if the image was updated.
 228       */
 229      private function update_picture($user) {
 230          global $CFG, $DB, $USER;
 231  
 232          require_once($CFG->libdir . '/filelib.php');
 233          require_once($CFG->libdir . '/gdlib.php');
 234          require_once($CFG->dirroot . '/user/lib.php');
 235  
 236          $fs = get_file_storage();
 237          $userid = $user->id;
 238          if (!empty($user->picture)) {
 239              return false;
 240          }
 241          if (!empty($CFG->enablegravatar)) {
 242              return false;
 243          }
 244  
 245          $picture = $this->get_static_user_picture();
 246          if (empty($picture)) {
 247              return false;
 248          }
 249  
 250          $context = \context_user::instance($userid, MUST_EXIST);
 251          $fs->delete_area_files($context->id, 'user', 'newicon');
 252  
 253          $filerecord = array(
 254              'contextid' => $context->id,
 255              'component' => 'user',
 256              'filearea' => 'newicon',
 257              'itemid' => 0,
 258              'filepath' => '/',
 259              'filename' => 'image'
 260          );
 261  
 262          try {
 263              $fs->create_file_from_string($filerecord, $picture);
 264          } catch (\file_exception $e) {
 265              return get_string($e->errorcode, $e->module, $e->a);
 266          }
 267  
 268          $iconfile = $fs->get_area_files($context->id, 'user', 'newicon', false, 'itemid', false);
 269  
 270          // There should only be one.
 271          $iconfile = reset($iconfile);
 272  
 273          // Something went wrong while creating temp file - remove the uploaded file.
 274          if (!$iconfile = $iconfile->copy_content_to_temp()) {
 275              $fs->delete_area_files($context->id, 'user', 'newicon');
 276              return false;
 277          }
 278  
 279          // Copy file to temporary location and the send it for processing icon.
 280          $newpicture = (int) process_new_icon($context, 'user', 'icon', 0, $iconfile);
 281          // Delete temporary file.
 282          @unlink($iconfile);
 283          // Remove uploaded file.
 284          $fs->delete_area_files($context->id, 'user', 'newicon');
 285          // Set the user's picture.
 286          $updateuser = new stdClass();
 287          $updateuser->id = $userid;
 288          $updateuser->picture = $newpicture;
 289          $USER->picture = $newpicture;
 290          user_update_user($updateuser);
 291          return true;
 292      }
 293  
 294      /**
 295       * Update user data according to data sent by authorization server.
 296       *
 297       * @param array $externaldata data from authorization server
 298       * @param stdClass $userdata Current data of the user to be updated
 299       * @return stdClass The updated user record, or the existing one if there's nothing to be updated.
 300       */
 301      private function update_user(array $externaldata, $userdata) {
 302          $user = (object) [
 303              'id' => $userdata->id,
 304          ];
 305  
 306          // We can only update if the default authentication type of the user is set to OAuth2 as well. Otherwise, we might mess
 307          // up the user data of other users that use different authentication mechanisms (e.g. linked logins).
 308          if ($userdata->auth !== $this->authtype) {
 309              return $userdata;
 310          }
 311  
 312          // Go through each field from the external data.
 313          foreach ($externaldata as $fieldname => $value) {
 314              if (!in_array($fieldname, $this->userfields)) {
 315                  // Skip if this field doesn't belong to the list of fields that can be synced with the OAuth2 issuer.
 316                  continue;
 317              }
 318  
 319              if (!property_exists($userdata, $fieldname)) {
 320                  // Just in case this field is on the list, but not part of the user data. This shouldn't happen though.
 321                  continue;
 322              }
 323  
 324              // Get the old value.
 325              $oldvalue = (string)$userdata->$fieldname;
 326  
 327              // Get the lock configuration of the field.
 328              $lockvalue = $this->config->{'field_lock_' . $fieldname};
 329  
 330              // We should update fields that meet the following criteria:
 331              // - Lock value set to 'unlocked'; or 'unlockedifempty', given the current value is empty.
 332              // - The value has changed.
 333              if ($lockvalue === 'unlocked' || ($lockvalue === 'unlockedifempty' && empty($oldvalue))) {
 334                  $value = (string)$value;
 335                  if ($oldvalue !== $value) {
 336                      $user->$fieldname = $value;
 337                  }
 338              }
 339          }
 340          // Update the user data.
 341          user_update_user($user, false);
 342  
 343          // Save user profile data.
 344          profile_save_data($user);
 345  
 346          // Refresh user for $USER variable.
 347          return get_complete_user_data('id', $user->id);
 348      }
 349  
 350      /**
 351       * Confirm the new user as registered.
 352       *
 353       * @param string $username
 354       * @param string $confirmsecret
 355       */
 356      public function user_confirm($username, $confirmsecret) {
 357          global $DB;
 358          $user = get_complete_user_data('username', $username);
 359  
 360          if (!empty($user)) {
 361              if ($user->auth != $this->authtype) {
 362                  return AUTH_CONFIRM_ERROR;
 363  
 364              } else if ($user->secret === $confirmsecret && $user->confirmed) {
 365                  return AUTH_CONFIRM_ALREADY;
 366  
 367              } else if ($user->secret === $confirmsecret) {   // They have provided the secret key to get in.
 368                  $DB->set_field("user", "confirmed", 1, array("id" => $user->id));
 369                  return AUTH_CONFIRM_OK;
 370              }
 371          } else {
 372              return AUTH_CONFIRM_ERROR;
 373          }
 374      }
 375  
 376      /**
 377       * Print a page showing that a confirm email was sent with instructions.
 378       *
 379       * @param string $title
 380       * @param string $message
 381       */
 382      public function print_confirm_required($title, $message) {
 383          global $PAGE, $OUTPUT, $CFG;
 384  
 385          $PAGE->navbar->add($title);
 386          $PAGE->set_title($title);
 387          $PAGE->set_heading($PAGE->course->fullname);
 388          echo $OUTPUT->header();
 389          notice($message, "$CFG->wwwroot/index.php");
 390      }
 391  
 392      /**
 393       * Complete the login process after oauth handshake is complete.
 394       * @param \core\oauth2\client $client
 395       * @param string $redirecturl
 396       * @return void Either redirects or throws an exception
 397       */
 398      public function complete_login(client $client, $redirecturl) {
 399          global $CFG, $SESSION, $PAGE;
 400  
 401          $userinfo = $client->get_userinfo();
 402  
 403          if (!$userinfo) {
 404              // Trigger login failed event.
 405              $failurereason = AUTH_LOGIN_NOUSER;
 406              $event = \core\event\user_login_failed::create(['other' => ['username' => 'unknown',
 407                                                                          'reason' => $failurereason]]);
 408              $event->trigger();
 409  
 410              $errormsg = get_string('loginerror_nouserinfo', 'auth_oauth2');
 411              $SESSION->loginerrormsg = $errormsg;
 412              $client->log_out();
 413              redirect(new moodle_url('/login/index.php'));
 414          }
 415          if (empty($userinfo['username']) || empty($userinfo['email'])) {
 416              // Trigger login failed event.
 417              $failurereason = AUTH_LOGIN_NOUSER;
 418              $event = \core\event\user_login_failed::create(['other' => ['username' => 'unknown',
 419                                                                          'reason' => $failurereason]]);
 420              $event->trigger();
 421  
 422              $errormsg = get_string('loginerror_userincomplete', 'auth_oauth2');
 423              $SESSION->loginerrormsg = $errormsg;
 424              $client->log_out();
 425              redirect(new moodle_url('/login/index.php'));
 426          }
 427  
 428          $userinfo['username'] = trim(core_text::strtolower($userinfo['username']));
 429          $oauthemail = $userinfo['email'];
 430  
 431          // Once we get here we have the user info from oauth.
 432          $userwasmapped = false;
 433  
 434          // Clean and remember the picture / lang.
 435          if (!empty($userinfo['picture'])) {
 436              $this->set_static_user_picture($userinfo['picture']);
 437              unset($userinfo['picture']);
 438          }
 439  
 440          if (!empty($userinfo['lang'])) {
 441              $userinfo['lang'] = str_replace('-', '_', trim(core_text::strtolower($userinfo['lang'])));
 442              if (!get_string_manager()->translation_exists($userinfo['lang'], false)) {
 443                  unset($userinfo['lang']);
 444              }
 445          }
 446  
 447          $issuer = $client->get_issuer();
 448          // First we try and find a defined mapping.
 449          $linkedlogin = api::match_username_to_user($userinfo['username'], $issuer);
 450  
 451          if (!empty($linkedlogin) && empty($linkedlogin->get('confirmtoken'))) {
 452              $mappeduser = get_complete_user_data('id', $linkedlogin->get('userid'));
 453  
 454              if ($mappeduser && $mappeduser->suspended) {
 455                  $failurereason = AUTH_LOGIN_SUSPENDED;
 456                  $event = \core\event\user_login_failed::create([
 457                      'userid' => $mappeduser->id,
 458                      'other' => [
 459                          'username' => $userinfo['username'],
 460                          'reason' => $failurereason
 461                      ]
 462                  ]);
 463                  $event->trigger();
 464                  $SESSION->loginerrormsg = get_string('invalidlogin');
 465                  $client->log_out();
 466                  redirect(new moodle_url('/login/index.php'));
 467              } else if ($mappeduser && ($mappeduser->confirmed || !$issuer->get('requireconfirmation'))) {
 468                  // Update user fields.
 469                  $userinfo = $this->update_user($userinfo, $mappeduser);
 470                  $userwasmapped = true;
 471              } else {
 472                  // Trigger login failed event.
 473                  $failurereason = AUTH_LOGIN_UNAUTHORISED;
 474                  $event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
 475                                                                              'reason' => $failurereason]]);
 476                  $event->trigger();
 477  
 478                  $errormsg = get_string('confirmationpending', 'auth_oauth2');
 479                  $SESSION->loginerrormsg = $errormsg;
 480                  $client->log_out();
 481                  redirect(new moodle_url('/login/index.php'));
 482              }
 483          } else if (!empty($linkedlogin)) {
 484              // Trigger login failed event.
 485              $failurereason = AUTH_LOGIN_UNAUTHORISED;
 486              $event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
 487                                                                          'reason' => $failurereason]]);
 488              $event->trigger();
 489  
 490              $errormsg = get_string('confirmationpending', 'auth_oauth2');
 491              $SESSION->loginerrormsg = $errormsg;
 492              $client->log_out();
 493              redirect(new moodle_url('/login/index.php'));
 494          }
 495  
 496  
 497          if (!$issuer->is_valid_login_domain($oauthemail)) {
 498              // Trigger login failed event.
 499              $failurereason = AUTH_LOGIN_UNAUTHORISED;
 500              $event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
 501                                                                          'reason' => $failurereason]]);
 502              $event->trigger();
 503  
 504              $errormsg = get_string('notloggedindebug', 'auth_oauth2', get_string('loginerror_invaliddomain', 'auth_oauth2'));
 505              $SESSION->loginerrormsg = $errormsg;
 506              $client->log_out();
 507              redirect(new moodle_url('/login/index.php'));
 508          }
 509  
 510          if (!$userwasmapped) {
 511              // No defined mapping - we need to see if there is an existing account with the same email.
 512  
 513              $moodleuser = \core_user::get_user_by_email($userinfo['email']);
 514              if (!empty($moodleuser)) {
 515                  if ($issuer->get('requireconfirmation')) {
 516                      $PAGE->set_url('/auth/oauth2/confirm-link-login.php');
 517                      $PAGE->set_context(context_system::instance());
 518  
 519                      \auth_oauth2\api::send_confirm_link_login_email($userinfo, $issuer, $moodleuser->id);
 520                      // Request to link to existing account.
 521                      $emailconfirm = get_string('emailconfirmlink', 'auth_oauth2');
 522                      $message = get_string('emailconfirmlinksent', 'auth_oauth2', $moodleuser->email);
 523                      $this->print_confirm_required($emailconfirm, $message);
 524                      exit();
 525                  } else {
 526                      \auth_oauth2\api::link_login($userinfo, $issuer, $moodleuser->id, true);
 527                      $userinfo = $this->update_user($userinfo, $moodleuser);
 528                      // No redirect, we will complete this login.
 529                  }
 530  
 531              } else {
 532                  // This is a new account.
 533                  $exists = \core_user::get_user_by_username($userinfo['username']);
 534                  // Creating a new user?
 535                  if ($exists) {
 536                      // Trigger login failed event.
 537                      $failurereason = AUTH_LOGIN_FAILED;
 538                      $event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
 539                                                                                  'reason' => $failurereason]]);
 540                      $event->trigger();
 541  
 542                      // The username exists but the emails don't match. Refuse to continue.
 543                      $errormsg = get_string('accountexists', 'auth_oauth2');
 544                      $SESSION->loginerrormsg = $errormsg;
 545                      $client->log_out();
 546                      redirect(new moodle_url('/login/index.php'));
 547                  }
 548  
 549                  if (email_is_not_allowed($userinfo['email'])) {
 550                      // Trigger login failed event.
 551                      $failurereason = AUTH_LOGIN_FAILED;
 552                      $event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
 553                                                                                  'reason' => $failurereason]]);
 554                      $event->trigger();
 555                      // The username exists but the emails don't match. Refuse to continue.
 556                      $reason = get_string('loginerror_invaliddomain', 'auth_oauth2');
 557                      $errormsg = get_string('notloggedindebug', 'auth_oauth2', $reason);
 558                      $SESSION->loginerrormsg = $errormsg;
 559                      $client->log_out();
 560                      redirect(new moodle_url('/login/index.php'));
 561                  }
 562  
 563                  if (!empty($CFG->authpreventaccountcreation)) {
 564                      // Trigger login failed event.
 565                      $failurereason = AUTH_LOGIN_UNAUTHORISED;
 566                      $event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
 567                                                                                  'reason' => $failurereason]]);
 568                      $event->trigger();
 569                      // The username does not exist and settings prevent creating new accounts.
 570                      $reason = get_string('loginerror_cannotcreateaccounts', 'auth_oauth2');
 571                      $errormsg = get_string('notloggedindebug', 'auth_oauth2', $reason);
 572                      $SESSION->loginerrormsg = $errormsg;
 573                      $client->log_out();
 574                      redirect(new moodle_url('/login/index.php'));
 575                  }
 576  
 577                  if ($issuer->get('requireconfirmation')) {
 578                      $PAGE->set_url('/auth/oauth2/confirm-account.php');
 579                      $PAGE->set_context(context_system::instance());
 580  
 581                      // Create a new (unconfirmed account) and send an email to confirm it.
 582                      $user = \auth_oauth2\api::send_confirm_account_email($userinfo, $issuer);
 583  
 584                      $this->update_picture($user);
 585                      $emailconfirm = get_string('emailconfirm');
 586                      $message = get_string('emailconfirmsent', '', $userinfo['email']);
 587                      $this->print_confirm_required($emailconfirm, $message);
 588                      exit();
 589                  } else {
 590                      // Create a new confirmed account.
 591                      $newuser = \auth_oauth2\api::create_new_confirmed_account($userinfo, $issuer);
 592                      $userinfo = get_complete_user_data('id', $newuser->id);
 593                      // No redirect, we will complete this login.
 594                  }
 595              }
 596          }
 597  
 598          // We used to call authenticate_user - but that won't work if the current user has a different default authentication
 599          // method. Since we now ALWAYS link a login - if we get to here we can directly allow the user in.
 600          $user = (object) $userinfo;
 601          complete_user_login($user);
 602          $this->update_picture($user);
 603          redirect($redirecturl);
 604      }
 605  
 606      /**
 607       * Returns information on how the specified user can change their password.
 608       * The password of the oauth2 accounts is not stored in Moodle.
 609       *
 610       * @param stdClass $user A user object
 611       * @return string[] An array of strings with keys subject and message
 612       */
 613      public function get_password_change_info(stdClass $user) : array {
 614          $site = get_site();
 615  
 616          $data = new stdClass();
 617          $data->firstname = $user->firstname;
 618          $data->lastname  = $user->lastname;
 619          $data->username  = $user->username;
 620          $data->sitename  = format_string($site->fullname);
 621          $data->admin     = generate_email_signoff();
 622  
 623          $message = get_string('emailpasswordchangeinfo', 'auth_oauth2', $data);
 624          $subject = get_string('emailpasswordchangeinfosubject', 'auth_oauth2', format_string($site->fullname));
 625  
 626          return [
 627              'subject' => $subject,
 628              'message' => $message
 629          ];
 630      }
 631  }