first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
+428
View File
@@ -0,0 +1,428 @@
<?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/>.
/**
* Class for loading/storing oauth2 linked logins from the DB.
*
* @package auth_oauth2
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace auth_oauth2;
use context_user;
use stdClass;
use moodle_exception;
use moodle_url;
defined('MOODLE_INTERNAL') || die();
/**
* Static list of api methods for auth oauth2 configuration.
*
* @package auth_oauth2
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class api {
/**
* Remove all linked logins that are using issuers that have been deleted.
*
* @param int $issuerid The issuer id of the issuer to check, or false to check all (defaults to all)
* @return boolean
*/
public static function clean_orphaned_linked_logins($issuerid = false) {
return linked_login::delete_orphaned($issuerid);
}
/**
* List linked logins
*
* Requires auth/oauth2:managelinkedlogins capability at the user context.
*
* @param int $userid (defaults to $USER->id)
* @return boolean
*/
public static function get_linked_logins($userid = false) {
global $USER;
if ($userid === false) {
$userid = $USER->id;
}
if (\core\session\manager::is_loggedinas()) {
throw new moodle_exception('notwhileloggedinas', 'auth_oauth2');
}
$context = context_user::instance($userid);
require_capability('auth/oauth2:managelinkedlogins', $context);
return linked_login::get_records(['userid' => $userid, 'confirmtoken' => '']);
}
/**
* See if there is a match for this username and issuer in the linked_login table.
*
* @param string $username as returned from an oauth client.
* @param \core\oauth2\issuer $issuer
* @return stdClass User record if found.
*/
public static function match_username_to_user($username, $issuer) {
$params = [
'issuerid' => $issuer->get('id'),
'username' => $username
];
$result = linked_login::get_record($params);
if ($result) {
$user = \core_user::get_user($result->get('userid'));
if (!empty($user) && !$user->deleted) {
return $result;
}
}
return false;
}
/**
* Link a login to this account.
*
* Requires auth/oauth2:managelinkedlogins capability at the user context.
*
* @param array $userinfo as returned from an oauth client.
* @param \core\oauth2\issuer $issuer
* @param int $userid (defaults to $USER->id)
* @param bool $skippermissions During signup we need to set this before the user is setup for capability checks.
* @return bool
*/
public static function link_login($userinfo, $issuer, $userid = false, $skippermissions = false) {
global $USER;
if ($userid === false) {
$userid = $USER->id;
}
if (linked_login::has_existing_issuer_match($issuer, $userinfo['username'])) {
throw new moodle_exception('alreadylinked', 'auth_oauth2');
}
if (\core\session\manager::is_loggedinas()) {
throw new moodle_exception('notwhileloggedinas', 'auth_oauth2');
}
$context = context_user::instance($userid);
if (!$skippermissions) {
require_capability('auth/oauth2:managelinkedlogins', $context);
}
$record = new stdClass();
$record->issuerid = $issuer->get('id');
$record->username = $userinfo['username'];
$record->userid = $userid;
$existing = linked_login::get_record((array)$record);
if ($existing) {
$existing->set('confirmtoken', '');
$existing->update();
return $existing;
}
$record->email = $userinfo['email'];
$record->confirmtoken = '';
$record->confirmtokenexpires = 0;
$linkedlogin = new linked_login(0, $record);
return $linkedlogin->create();
}
/**
* Send an email with a link to confirm linking this account.
*
* @param array $userinfo as returned from an oauth client.
* @param \core\oauth2\issuer $issuer
* @param int $userid (defaults to $USER->id)
* @return bool
*/
public static function send_confirm_link_login_email($userinfo, $issuer, $userid) {
$record = new stdClass();
$record->issuerid = $issuer->get('id');
$record->username = $userinfo['username'];
$record->userid = $userid;
if (linked_login::has_existing_issuer_match($issuer, $userinfo['username'])) {
throw new moodle_exception('alreadylinked', 'auth_oauth2');
}
$record->email = $userinfo['email'];
$record->confirmtoken = random_string(32);
$expires = new \DateTime('NOW');
$expires->add(new \DateInterval('PT30M'));
$record->confirmtokenexpires = $expires->getTimestamp();
$linkedlogin = new linked_login(0, $record);
$linkedlogin->create();
// Construct the email.
$site = get_site();
$supportuser = \core_user::get_support_user();
$user = get_complete_user_data('id', $userid);
$data = new stdClass();
$data->fullname = fullname($user);
$data->sitename = format_string($site->fullname);
$data->admin = generate_email_signoff();
$data->issuername = format_string($issuer->get('name'));
$data->linkedemail = format_string($linkedlogin->get('email'));
$subject = get_string('confirmlinkedloginemailsubject', 'auth_oauth2', format_string($site->fullname));
$params = [
'token' => $linkedlogin->get('confirmtoken'),
'userid' => $userid,
'username' => $userinfo['username'],
'issuerid' => $issuer->get('id'),
];
$confirmationurl = new moodle_url('/auth/oauth2/confirm-linkedlogin.php', $params);
$data->link = $confirmationurl->out(false);
$message = get_string('confirmlinkedloginemail', 'auth_oauth2', $data);
$data->link = $confirmationurl->out();
$messagehtml = text_to_html(get_string('confirmlinkedloginemail', 'auth_oauth2', $data), false, false, true);
$user->mailformat = 1; // Always send HTML version as well.
// Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
}
/**
* Look for a waiting confirmation token, and if we find a match - confirm it.
*
* @param int $userid
* @param string $username
* @param int $issuerid
* @param string $token
* @return boolean True if we linked.
*/
public static function confirm_link_login($userid, $username, $issuerid, $token) {
if (empty($token) || empty($userid) || empty($issuerid) || empty($username)) {
return false;
}
$params = [
'userid' => $userid,
'username' => $username,
'issuerid' => $issuerid,
'confirmtoken' => $token,
];
$login = linked_login::get_record($params);
if (empty($login)) {
return false;
}
$expires = $login->get('confirmtokenexpires');
if (time() > $expires) {
$login->delete();
return;
}
$login->set('confirmtokenexpires', 0);
$login->set('confirmtoken', '');
$login->update();
return true;
}
/**
* Create an account with a linked login that is already confirmed.
*
* @param array $userinfo as returned from an oauth client.
* @param \core\oauth2\issuer $issuer
* @return bool
*/
public static function create_new_confirmed_account($userinfo, $issuer) {
global $CFG, $DB;
require_once($CFG->dirroot.'/user/profile/lib.php');
require_once($CFG->dirroot.'/user/lib.php');
$user = new stdClass();
$user->auth = 'oauth2';
$user->mnethostid = $CFG->mnet_localhost_id;
$user->secret = random_string(15);
$user->password = '';
$user->confirmed = 1; // Set the user to confirmed.
$user = self::save_user($userinfo, $user);
// The linked account is pre-confirmed.
$record = new stdClass();
$record->issuerid = $issuer->get('id');
$record->username = $userinfo['username'];
$record->userid = $user->id;
$record->email = $userinfo['email'];
$record->confirmtoken = '';
$record->confirmtokenexpires = 0;
$linkedlogin = new linked_login(0, $record);
$linkedlogin->create();
return $user;
}
/**
* Send an email with a link to confirm creating this account.
*
* @param array $userinfo as returned from an oauth client.
* @param \core\oauth2\issuer $issuer
* @param int $userid (defaults to $USER->id)
* @return bool
*/
public static function send_confirm_account_email($userinfo, $issuer) {
global $CFG, $DB;
require_once($CFG->dirroot.'/user/profile/lib.php');
require_once($CFG->dirroot.'/user/lib.php');
if (linked_login::has_existing_issuer_match($issuer, $userinfo['username'])) {
throw new moodle_exception('alreadylinked', 'auth_oauth2');
}
$user = new stdClass();
$user->auth = 'oauth2';
$user->mnethostid = $CFG->mnet_localhost_id;
$user->secret = random_string(15);
$user->password = '';
$user->confirmed = 0; // The user is not yet confirmed.
$user = self::save_user($userinfo, $user);
// The linked account is pre-confirmed.
$record = new stdClass();
$record->issuerid = $issuer->get('id');
$record->username = $userinfo['username'];
$record->userid = $user->id;
$record->email = $userinfo['email'];
$record->confirmtoken = '';
$record->confirmtokenexpires = 0;
$linkedlogin = new linked_login(0, $record);
$linkedlogin->create();
// Construct the email.
$site = get_site();
$supportuser = \core_user::get_support_user();
$user = get_complete_user_data('id', $user->id);
$data = new stdClass();
$data->fullname = fullname($user);
$data->sitename = format_string($site->fullname);
$data->admin = generate_email_signoff();
$subject = get_string('confirmaccountemailsubject', 'auth_oauth2', format_string($site->fullname));
$params = [
'token' => $user->secret,
'username' => $userinfo['username']
];
$confirmationurl = new moodle_url('/auth/oauth2/confirm-account.php', $params);
$data->link = $confirmationurl->out(false);
$message = get_string('confirmaccountemail', 'auth_oauth2', $data);
$data->link = $confirmationurl->out();
$messagehtml = text_to_html(get_string('confirmaccountemail', 'auth_oauth2', $data), false, false, true);
$user->mailformat = 1; // Always send HTML version as well.
// 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, $messagehtml);
return $user;
}
/**
* Delete a users own linked login
*
* Requires auth/oauth2:managelinkedlogins capability at the user context.
*
* @param int $linkedloginid
* @return boolean
*/
public static function delete_linked_login($linkedloginid) {
global $USER;
if (\core\session\manager::is_loggedinas()) {
throw new moodle_exception('notwhileloggedinas', 'auth_oauth2');
}
$login = linked_login::get_record([
'id' => $linkedloginid,
'userid' => $USER->id,
'confirmtoken' => '',
], MUST_EXIST);
$context = context_user::instance($login->get('userid'));
require_capability('auth/oauth2:managelinkedlogins', $context);
$login->delete();
}
/**
* Delete linked logins for a user.
*
* @param \core\event\user_deleted $event
* @return boolean
*/
public static function user_deleted(\core\event\user_deleted $event) {
global $DB;
$userid = $event->objectid;
return $DB->delete_records(linked_login::TABLE, ['userid' => $userid]);
}
/**
* Is the plugin enabled.
*
* @return bool
*/
public static function is_enabled() {
return is_enabled_auth('oauth2');
}
/**
* Create a new user & update the profile fields
*
* @param array $userinfo
* @param object $user
* @return object
*/
private static function save_user(array $userinfo, object $user): object {
// Map supplied issuer user info to Moodle user fields.
$userfieldmapping = new \core\oauth2\user_field_mapping();
$userfieldlist = $userfieldmapping->get_internalfields();
$hasprofilefield = false;
foreach ($userfieldlist as $field) {
if (isset($userinfo[$field]) && $userinfo[$field]) {
$user->$field = $userinfo[$field];
// Check whether the profile fields exist or not.
$hasprofilefield = $hasprofilefield || strpos($field, \core_user\fields::PROFILE_FIELD_PREFIX) === 0;
}
}
// Create a new user.
$user->id = user_create_user($user, false, true);
// If profile fields exist then save custom profile fields data.
if ($hasprofilefield) {
profile_save_data($user);
}
return $user;
}
}
+651
View File
@@ -0,0 +1,651 @@
<?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/>.
/**
* Anobody can login with any password.
*
* @package auth_oauth2
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
namespace auth_oauth2;
defined('MOODLE_INTERNAL') || die();
use pix_icon;
use moodle_url;
use core_text;
use context_system;
use stdClass;
use core\oauth2\issuer;
use core\oauth2\client;
require_once($CFG->libdir.'/authlib.php');
require_once($CFG->dirroot.'/user/lib.php');
require_once($CFG->dirroot.'/user/profile/lib.php');
/**
* Plugin for oauth2 authentication.
*
* @package auth_oauth2
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
class auth extends \auth_plugin_base {
/**
* @var stdClass $userinfo The set of user info returned from the oauth handshake
*/
private static $userinfo;
/**
* @var stdClass $userpicture The url to a picture.
*/
private static $userpicture;
/**
* Constructor.
*/
public function __construct() {
$this->authtype = 'oauth2';
$this->config = get_config('auth_oauth2');
}
/**
* Returns true if the username and password work or don't exist and false
* if the user exists and the password is wrong.
*
* @param string $username The username
* @param string $password The password
* @return bool Authentication success or failure.
*/
public function user_login($username, $password) {
$cached = $this->get_static_user_info();
if (empty($cached)) {
// This means we were called as part of a normal login flow - without using oauth.
return false;
}
$verifyusername = $cached['username'];
if ($verifyusername == $username) {
return true;
}
return false;
}
/**
* We don't want to allow users setting an internal password.
*
* @return bool
*/
public function prevent_local_passwords() {
return true;
}
/**
* Returns true if this authentication plugin is 'internal'.
*
* @return bool
*/
public function is_internal() {
return false;
}
/**
* Indicates if moodle should automatically update internal user
* records with data from external sources using the information
* from auth_plugin_base::get_userinfo().
*
* @return bool true means automatically copy data from ext to user table
*/
public function is_synchronised_with_external() {
return true;
}
/**
* Returns true if this authentication plugin can change the user's
* password.
*
* @return bool
*/
public function can_change_password() {
return false;
}
/**
* Returns the URL for changing the user's pw, or empty if the default can
* be used.
*
* @return moodle_url
*/
public function change_password_url() {
return null;
}
/**
* Returns true if plugin allows resetting of internal password.
*
* @return bool
*/
public function can_reset_password() {
return false;
}
/**
* Returns true if plugin can be manually set.
*
* @return bool
*/
public function can_be_manually_set() {
return true;
}
/**
* Return the userinfo from the oauth handshake. Will only be valid
* for the logged in user.
* @param string $username
*/
public function get_userinfo($username) {
$cached = $this->get_static_user_info();
if (!empty($cached) && $cached['username'] == $username) {
return $cached;
}
return false;
}
/**
* Return a list of identity providers to display on the login page.
*
* @param string|moodle_url $wantsurl The requested URL.
* @return array List of arrays with keys url, iconurl and name.
*/
public function loginpage_idp_list($wantsurl) {
$providers = \core\oauth2\api::get_all_issuers(true);
$result = [];
if (empty($wantsurl)) {
$wantsurl = '/';
}
foreach ($providers as $idp) {
if ($idp->is_available_for_login()) {
$params = ['id' => $idp->get('id'), 'wantsurl' => $wantsurl, 'sesskey' => sesskey()];
$url = new moodle_url('/auth/oauth2/login.php', $params);
$icon = $idp->get('image');
$result[] = ['url' => $url, 'iconurl' => $icon, 'name' => $idp->get_display_name()];
}
}
return $result;
}
/**
* Statically cache the user info from the oauth handshake
* @param stdClass $userinfo
*/
private function set_static_user_info($userinfo) {
self::$userinfo = $userinfo;
}
/**
* Get the static cached user info
* @return stdClass
*/
private function get_static_user_info() {
return self::$userinfo;
}
/**
* Statically cache the user picture from the oauth handshake
* @param string $userpicture
*/
private function set_static_user_picture($userpicture) {
self::$userpicture = $userpicture;
}
/**
* Get the static cached user picture
* @return string
*/
private function get_static_user_picture() {
return self::$userpicture;
}
/**
* If this user has no picture - but we got one from oauth - set it.
* @param stdClass $user
* @return boolean True if the image was updated.
*/
private function update_picture($user) {
global $CFG, $DB, $USER;
require_once($CFG->libdir . '/filelib.php');
require_once($CFG->libdir . '/gdlib.php');
require_once($CFG->dirroot . '/user/lib.php');
$fs = get_file_storage();
$userid = $user->id;
if (!empty($user->picture)) {
return false;
}
if (!empty($CFG->enablegravatar)) {
return false;
}
$picture = $this->get_static_user_picture();
if (empty($picture)) {
return false;
}
$context = \context_user::instance($userid, MUST_EXIST);
$fs->delete_area_files($context->id, 'user', 'newicon');
$filerecord = array(
'contextid' => $context->id,
'component' => 'user',
'filearea' => 'newicon',
'itemid' => 0,
'filepath' => '/',
'filename' => 'image'
);
try {
$fs->create_file_from_string($filerecord, $picture);
} catch (\file_exception $e) {
return get_string($e->errorcode, $e->module, $e->a);
}
$iconfile = $fs->get_area_files($context->id, 'user', 'newicon', false, 'itemid', false);
// There should only be one.
$iconfile = reset($iconfile);
// Something went wrong while creating temp file - remove the uploaded file.
if (!$iconfile = $iconfile->copy_content_to_temp()) {
$fs->delete_area_files($context->id, 'user', 'newicon');
return false;
}
// Copy file to temporary location and the send it for processing icon.
$newpicture = (int) process_new_icon($context, 'user', 'icon', 0, $iconfile);
// Delete temporary file.
@unlink($iconfile);
// Remove uploaded file.
$fs->delete_area_files($context->id, 'user', 'newicon');
// Set the user's picture.
$updateuser = new stdClass();
$updateuser->id = $userid;
$updateuser->picture = $newpicture;
$USER->picture = $newpicture;
user_update_user($updateuser);
return true;
}
/**
* Update user data according to data sent by authorization server.
*
* @param array $externaldata data from authorization server
* @param stdClass $userdata Current data of the user to be updated
* @return stdClass The updated user record, or the existing one if there's nothing to be updated.
*/
private function update_user(array $externaldata, $userdata) {
$user = (object) [
'id' => $userdata->id,
];
// We can only update if the default authentication type of the user is set to OAuth2 as well. Otherwise, we might mess
// up the user data of other users that use different authentication mechanisms (e.g. linked logins).
if ($userdata->auth !== $this->authtype) {
return $userdata;
}
$allfields = array_merge($this->userfields, $this->get_custom_user_profile_fields());
// Go through each field from the external data.
foreach ($externaldata as $fieldname => $value) {
if (!in_array($fieldname, $allfields)) {
// Skip if this field doesn't belong to the list of fields that can be synced with the OAuth2 issuer.
continue;
}
$userhasfield = property_exists($userdata, $fieldname);
// Find out if it is a profile field.
$isprofilefield = strpos($fieldname, 'profile_field_') === 0;
$profilefieldname = str_replace('profile_field_', '', $fieldname);
$userhasprofilefield = $isprofilefield && array_key_exists($profilefieldname, $userdata->profile);
// Just in case this field is on the list, but not part of the user data. This shouldn't happen though.
if (!($userhasfield || $userhasprofilefield)) {
continue;
}
// Get the old value.
$oldvalue = $isprofilefield ? (string) $userdata->profile[$profilefieldname] : (string) $userdata->$fieldname;
// Get the lock configuration of the field.
if (!empty($this->config->{'field_lock_' . $fieldname})) {
$lockvalue = $this->config->{'field_lock_' . $fieldname};
} else {
$lockvalue = 'unlocked';
}
// We should update fields that meet the following criteria:
// - Lock value set to 'unlocked'; or 'unlockedifempty', given the current value is empty.
// - The value has changed.
if ($lockvalue === 'unlocked' || ($lockvalue === 'unlockedifempty' && empty($oldvalue))) {
$value = (string)$value;
if ($oldvalue !== $value) {
$user->$fieldname = $value;
}
}
}
// Update the user data.
user_update_user($user, false);
// Save user profile data.
profile_save_data($user);
// Refresh user for $USER variable.
return get_complete_user_data('id', $user->id);
}
/**
* Confirm the new user as registered.
*
* @param string $username
* @param string $confirmsecret
*/
public function user_confirm($username, $confirmsecret) {
global $DB;
$user = get_complete_user_data('username', $username);
if (!empty($user)) {
if ($user->auth != $this->authtype) {
return AUTH_CONFIRM_ERROR;
} else if ($user->secret === $confirmsecret && $user->confirmed) {
return AUTH_CONFIRM_ALREADY;
} else if ($user->secret === $confirmsecret) { // They have provided the secret key to get in.
$DB->set_field("user", "confirmed", 1, array("id" => $user->id));
return AUTH_CONFIRM_OK;
}
} else {
return AUTH_CONFIRM_ERROR;
}
}
/**
* Print a page showing that a confirm email was sent with instructions.
*
* @param string $title
* @param string $message
*/
public function print_confirm_required($title, $message) {
global $PAGE, $OUTPUT, $CFG;
$PAGE->navbar->add($title);
$PAGE->set_title($title);
$PAGE->set_heading($PAGE->course->fullname);
echo $OUTPUT->header();
notice($message, "$CFG->wwwroot/index.php");
}
/**
* Complete the login process after oauth handshake is complete.
* @param \core\oauth2\client $client
* @param string $redirecturl
* @return void Either redirects or throws an exception
*/
public function complete_login(client $client, $redirecturl) {
global $CFG, $SESSION, $PAGE;
$rawuserinfo = $client->get_raw_userinfo();
$userinfo = $client->get_userinfo();
if (!$userinfo) {
// Trigger login failed event.
$failurereason = AUTH_LOGIN_NOUSER;
$event = \core\event\user_login_failed::create(['other' => ['username' => 'unknown',
'reason' => $failurereason]]);
$event->trigger();
$errormsg = get_string('loginerror_nouserinfo', 'auth_oauth2');
$SESSION->loginerrormsg = $errormsg;
$client->log_out();
redirect(new moodle_url('/login/index.php'));
}
if (empty($userinfo['username']) || empty($userinfo['email'])) {
// Trigger login failed event.
$failurereason = AUTH_LOGIN_NOUSER;
$event = \core\event\user_login_failed::create(['other' => ['username' => 'unknown',
'reason' => $failurereason]]);
$event->trigger();
$errormsg = get_string('loginerror_userincomplete', 'auth_oauth2');
$SESSION->loginerrormsg = $errormsg;
$client->log_out();
redirect(new moodle_url('/login/index.php'));
}
$userinfo['username'] = trim(core_text::strtolower($userinfo['username']));
$oauthemail = $userinfo['email'];
// Once we get here we have the user info from oauth.
$userwasmapped = false;
// Clean and remember the picture / lang.
if (!empty($userinfo['picture'])) {
$this->set_static_user_picture($userinfo['picture']);
unset($userinfo['picture']);
}
if (!empty($userinfo['lang'])) {
$userinfo['lang'] = str_replace('-', '_', trim(core_text::strtolower($userinfo['lang'])));
if (!get_string_manager()->translation_exists($userinfo['lang'], false)) {
unset($userinfo['lang']);
}
}
$issuer = $client->get_issuer();
// First we try and find a defined mapping.
$linkedlogin = api::match_username_to_user($userinfo['username'], $issuer);
if (!empty($linkedlogin) && empty($linkedlogin->get('confirmtoken'))) {
$mappeduser = get_complete_user_data('id', $linkedlogin->get('userid'));
if ($mappeduser && $mappeduser->suspended) {
$failurereason = AUTH_LOGIN_SUSPENDED;
$event = \core\event\user_login_failed::create([
'userid' => $mappeduser->id,
'other' => [
'username' => $userinfo['username'],
'reason' => $failurereason
]
]);
$event->trigger();
$SESSION->loginerrormsg = get_string('invalidlogin');
$client->log_out();
redirect(new moodle_url('/login/index.php'));
} else if ($mappeduser && ($mappeduser->confirmed || !$issuer->get('requireconfirmation'))) {
// Update user fields.
$userinfo = $this->update_user($userinfo, $mappeduser);
$userwasmapped = true;
} else {
// Trigger login failed event.
$failurereason = AUTH_LOGIN_UNAUTHORISED;
$event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
'reason' => $failurereason]]);
$event->trigger();
$errormsg = get_string('confirmationpending', 'auth_oauth2');
$SESSION->loginerrormsg = $errormsg;
$client->log_out();
redirect(new moodle_url('/login/index.php'));
}
} else if (!empty($linkedlogin)) {
// Trigger login failed event.
$failurereason = AUTH_LOGIN_UNAUTHORISED;
$event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
'reason' => $failurereason]]);
$event->trigger();
$errormsg = get_string('confirmationpending', 'auth_oauth2');
$SESSION->loginerrormsg = $errormsg;
$client->log_out();
redirect(new moodle_url('/login/index.php'));
}
if (!$issuer->is_valid_login_domain($oauthemail)) {
// Trigger login failed event.
$failurereason = AUTH_LOGIN_UNAUTHORISED;
$event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
'reason' => $failurereason]]);
$event->trigger();
$errormsg = get_string('notloggedindebug', 'auth_oauth2', get_string('loginerror_invaliddomain', 'auth_oauth2'));
$SESSION->loginerrormsg = $errormsg;
$client->log_out();
redirect(new moodle_url('/login/index.php'));
}
if (!$userwasmapped) {
// No defined mapping - we need to see if there is an existing account with the same email.
$moodleuser = \core_user::get_user_by_email($userinfo['email']);
if (!empty($moodleuser)) {
if ($issuer->get('requireconfirmation')) {
$PAGE->set_url('/auth/oauth2/confirm-link-login.php');
$PAGE->set_context(context_system::instance());
\auth_oauth2\api::send_confirm_link_login_email($userinfo, $issuer, $moodleuser->id);
// Request to link to existing account.
$emailconfirm = get_string('emailconfirmlink', 'auth_oauth2');
$message = get_string('emailconfirmlinksent', 'auth_oauth2', $moodleuser->email);
$this->print_confirm_required($emailconfirm, $message);
exit();
} else {
\auth_oauth2\api::link_login($userinfo, $issuer, $moodleuser->id, true);
// We dont have profile loaded on $moodleuser, so load it.
require_once($CFG->dirroot.'/user/profile/lib.php');
profile_load_custom_fields($moodleuser);
$userinfo = $this->update_user($userinfo, $moodleuser);
// No redirect, we will complete this login.
}
} else {
// This is a new account.
$exists = \core_user::get_user_by_username($userinfo['username']);
// Creating a new user?
if ($exists) {
// Trigger login failed event.
$failurereason = AUTH_LOGIN_FAILED;
$event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
'reason' => $failurereason]]);
$event->trigger();
// The username exists but the emails don't match. Refuse to continue.
$errormsg = get_string('accountexists', 'auth_oauth2');
$SESSION->loginerrormsg = $errormsg;
$client->log_out();
redirect(new moodle_url('/login/index.php'));
}
if (email_is_not_allowed($userinfo['email'])) {
// Trigger login failed event.
$failurereason = AUTH_LOGIN_FAILED;
$event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
'reason' => $failurereason]]);
$event->trigger();
// The username exists but the emails don't match. Refuse to continue.
$reason = get_string('loginerror_invaliddomain', 'auth_oauth2');
$errormsg = get_string('notloggedindebug', 'auth_oauth2', $reason);
$SESSION->loginerrormsg = $errormsg;
$client->log_out();
redirect(new moodle_url('/login/index.php'));
}
if (!empty($CFG->authpreventaccountcreation)) {
// Trigger login failed event.
$failurereason = AUTH_LOGIN_UNAUTHORISED;
$event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
'reason' => $failurereason]]);
$event->trigger();
// The username does not exist and settings prevent creating new accounts.
$reason = get_string('loginerror_cannotcreateaccounts', 'auth_oauth2');
$errormsg = get_string('notloggedindebug', 'auth_oauth2', $reason);
$SESSION->loginerrormsg = $errormsg;
$client->log_out();
redirect(new moodle_url('/login/index.php'));
}
if ($issuer->get('requireconfirmation')) {
$PAGE->set_url('/auth/oauth2/confirm-account.php');
$PAGE->set_context(context_system::instance());
// Create a new (unconfirmed account) and send an email to confirm it.
$user = \auth_oauth2\api::send_confirm_account_email($userinfo, $issuer);
$this->update_picture($user);
$emailconfirm = get_string('emailconfirm');
$message = get_string('emailconfirmsent', '', $userinfo['email']);
$this->print_confirm_required($emailconfirm, $message);
exit();
} else {
// Create a new confirmed account.
$newuser = \auth_oauth2\api::create_new_confirmed_account($userinfo, $issuer);
$userinfo = get_complete_user_data('id', $newuser->id);
// No redirect, we will complete this login.
}
}
}
// We used to call authenticate_user - but that won't work if the current user has a different default authentication
// method. Since we now ALWAYS link a login - if we get to here we can directly allow the user in.
$user = (object) $userinfo;
// Add extra loggedin info.
$this->set_extrauserinfo((array)$rawuserinfo);
complete_user_login($user, $this->get_extrauserinfo());
$this->update_picture($user);
redirect($redirecturl);
}
/**
* Returns information on how the specified user can change their password.
* The password of the oauth2 accounts is not stored in Moodle.
*
* @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 {
$site = get_site();
$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();
$message = get_string('emailpasswordchangeinfo', 'auth_oauth2', $data);
$subject = get_string('emailpasswordchangeinfosubject', 'auth_oauth2', format_string($site->fullname));
return [
'subject' => $subject,
'message' => $message
];
}
}
+113
View File
@@ -0,0 +1,113 @@
<?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/>.
/**
* Class for loading/storing issuers from the DB.
*
* @package auth_oauth2
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace auth_oauth2;
defined('MOODLE_INTERNAL') || die();
use core\persistent;
/**
* Class for loading/storing issuer from the DB
*
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class linked_login extends persistent {
const TABLE = 'auth_oauth2_linked_login';
/**
* Return the definition of the properties of this model.
*
* @return array
*/
protected static function define_properties() {
return array(
'issuerid' => array(
'type' => PARAM_INT
),
'userid' => array(
'type' => PARAM_INT
),
'username' => array(
'type' => PARAM_RAW
),
'email' => array(
'type' => PARAM_RAW
),
'confirmtoken' => array(
'type' => PARAM_RAW
),
'confirmtokenexpires' => array(
'type' => PARAM_INT
)
);
}
/**
* Check whether there are any valid linked accounts for this issuer
* and username combination.
*
* @param \core\oauth2\issuer $issuer The issuer
* @param string $username The username to check
*/
public static function has_existing_issuer_match(\core\oauth2\issuer $issuer, $username) {
global $DB;
$where = "issuerid = :issuerid
AND username = :username
AND (confirmtokenexpires = 0 OR confirmtokenexpires > :maxexpiry)";
$count = $DB->count_records_select(static::TABLE, $where, [
'issuerid' => $issuer->get('id'),
'username' => $username,
'maxexpiry' => (new \DateTime('NOW'))->getTimestamp(),
]);
return $count > 0;
}
/**
* Remove all linked logins that are using issuers that have been deleted.
*
* @param int $issuerid The issuer id of the issuer to check, or false to check all (defaults to all)
* @return boolean
*/
public static function delete_orphaned($issuerid = false) {
global $DB;
// Delete any linked_login entries with a issuerid
// which does not exist in the issuer table.
// In the left join, the issuer id will be null
// where a match linked_login.issuerid is not found.
$sql = "DELETE FROM {" . self::TABLE . "}
WHERE issuerid NOT IN (SELECT id FROM {" . \core\oauth2\issuer::TABLE . "})";
$params = [];
if (!empty($issuerid)) {
$sql .= ' AND issuerid = ?';
$params['issuerid'] = $issuerid;
}
return $DB->execute($sql, $params);
}
}
+96
View File
@@ -0,0 +1,96 @@
<?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/>.
/**
* Output rendering for the plugin.
*
* @package auth_oauth2
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace auth_oauth2\output;
use plugin_renderer_base;
use html_table;
use html_table_cell;
use html_table_row;
use html_writer;
use auth_oauth2\linked_login;
use moodle_url;
defined('MOODLE_INTERNAL') || die();
/**
* Implements the plugin renderer
*
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class renderer extends plugin_renderer_base {
/**
* This function will render one beautiful table with all the linked_logins.
*
* @param linked_login[] $linkedlogins - list of all linked logins.
* @return string HTML to output.
*/
public function linked_logins_table($linkedlogins) {
global $CFG;
$table = new html_table();
$table->head = [
get_string('issuer', 'auth_oauth2'),
get_string('info', 'auth_oauth2'),
get_string('edit'),
];
$table->attributes['class'] = 'admintable generaltable';
$data = [];
$index = 0;
foreach ($linkedlogins as $linkedlogin) {
// Issuer.
$issuerid = $linkedlogin->get('issuerid');
$issuer = \core\oauth2\api::get_issuer($issuerid);
$issuercell = new html_table_cell(s($issuer->get('name')));
// Issuer.
$username = $linkedlogin->get('username');
$email = $linkedlogin->get('email');
$usernamecell = new html_table_cell(s($email) . ', (' . s($username) . ')');
$links = '';
// Delete.
$deleteparams = ['linkedloginid' => $linkedlogin->get('id'), 'action' => 'delete', 'sesskey' => sesskey()];
$deleteurl = new moodle_url('/auth/oauth2/linkedlogins.php', $deleteparams);
$deletelink = html_writer::link($deleteurl, $this->pix_icon('t/delete', get_string('delete')));
$links .= ' ' . $deletelink;
$editcell = new html_table_cell($links);
$row = new html_table_row([
$issuercell,
$usernamecell,
$editcell,
]);
$data[] = $row;
$index++;
}
$table->data = $data;
return html_writer::table($table);
}
}
+210
View File
@@ -0,0 +1,210 @@
<?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/>.
/**
* Privacy class for requesting user data for auth_oauth2.
*
* @package auth_oauth2
* @copyright 2018 Carlos Escobedo <carlos@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace auth_oauth2\privacy;
defined('MOODLE_INTERNAL') || die();
use core_privacy\local\metadata\collection;
use core_privacy\local\request\contextlist;
use core_privacy\local\request\approved_contextlist;
use core_privacy\local\request\transform;
use core_privacy\local\request\writer;
use core_privacy\local\request\userlist;
use core_privacy\local\request\approved_userlist;
/**
* Privacy provider for auth_oauth2
*
* @package auth_oauth2
* @copyright 2018 Carlos Escobedo <carlos@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements
\core_privacy\local\metadata\provider,
\core_privacy\local\request\core_userlist_provider,
\core_privacy\local\request\plugin\provider {
/**
* Get information about the user data stored by this plugin.
*
* @param collection $collection An object for storing metadata.
* @return collection The metadata.
*/
public static function get_metadata(collection $collection): collection {
$authfields = [
'timecreated' => 'privacy:metadata:auth_oauth2:timecreated',
'timemodified' => 'privacy:metadata:auth_oauth2:timemodified',
'usermodified' => 'privacy:metadata:auth_oauth2:usermodified',
'userid' => 'privacy:metadata:auth_oauth2:userid',
'issuerid' => 'privacy:metadata:auth_oauth2:issuerid',
'username' => 'privacy:metadata:auth_oauth2:username',
'email' => 'privacy:metadata:auth_oauth2:email',
'confirmtoken' => 'privacy:metadata:auth_oauth2:confirmtoken',
'confirmtokenexpires' => 'privacy:metadata:auth_oauth2:confirmtokenexpires'
];
$collection->add_database_table('auth_oauth2_linked_login', $authfields, 'privacy:metadata:auth_oauth2:tableexplanation');
// Regarding this block, we are unable to export or purge this data, as
// it would damage the oauth2 data across the whole site.
foreach ([
'oauth2_endpoint',
'oauth2_user_field_mapping',
'oauth2_access_token',
'oauth2_system_account',
] as $tablename) {
$collection->add_database_table($tablename, [
'usermodified' => 'privacy:metadata:auth_oauth2:usermodified',
], 'privacy:metadata:auth_oauth2:tableexplanation');
}
$collection->link_subsystem('core_auth', 'privacy:metadata:auth_oauth2:authsubsystem');
return $collection;
}
/**
* Return all contexts for this userid. In this situation the user context.
*
* @param int $userid The user ID.
* @return contextlist The list of context IDs.
*/
public static function get_contexts_for_userid(int $userid): contextlist {
$sql = "SELECT ctx.id
FROM {auth_oauth2_linked_login} ao
JOIN {context} ctx ON ctx.instanceid = ao.userid AND ctx.contextlevel = :contextlevel
WHERE ao.userid = :userid";
$params = ['userid' => $userid, 'contextlevel' => CONTEXT_USER];
$contextlist = new contextlist();
$contextlist->add_from_sql($sql, $params);
return $contextlist;
}
/**
* Get the list of users within a specific context.
*
* @param userlist $userlist The userlist containing the list of users who have data in this context/plugin combination.
*/
public static function get_users_in_context(userlist $userlist) {
$context = $userlist->get_context();
if (!$context instanceof \context_user) {
return;
}
$sql = "SELECT userid
FROM {auth_oauth2_linked_login}
WHERE userid = ?";
$params = [$context->instanceid];
$userlist->add_from_sql('userid', $sql, $params);
}
/**
* Export all oauth2 information for the list of contexts and this user.
*
* @param approved_contextlist $contextlist The list of approved contexts for a user.
*/
public static function export_user_data(approved_contextlist $contextlist) {
global $DB;
// Export oauth2 linked accounts.
$context = \context_user::instance($contextlist->get_user()->id);
$sql = "SELECT ll.id, ll.username, ll.email, ll.timecreated, ll.timemodified, oi.name as issuername
FROM {auth_oauth2_linked_login} ll JOIN {oauth2_issuer} oi ON oi.id = ll.issuerid
WHERE ll.userid = :userid";
if ($oauth2accounts = $DB->get_records_sql($sql, ['userid' => $contextlist->get_user()->id])) {
foreach ($oauth2accounts as $oauth2account) {
$data = (object)[
'timecreated' => transform::datetime($oauth2account->timecreated),
'timemodified' => transform::datetime($oauth2account->timemodified),
'issuerid' => $oauth2account->issuername,
'username' => $oauth2account->username,
'email' => $oauth2account->email
];
writer::with_context($context)->export_data([
get_string('privacy:metadata:auth_oauth2', 'auth_oauth2'),
$oauth2account->issuername
], $data);
}
}
}
/**
* Delete all user data for this context.
*
* @param \context $context The context to delete data for.
*/
public static function delete_data_for_all_users_in_context(\context $context) {
if ($context->contextlevel != CONTEXT_USER) {
return;
}
static::delete_user_data($context->instanceid);
}
/**
* Delete multiple users within a single context.
*
* @param approved_userlist $userlist The approved context and user information to delete information for.
*/
public static function delete_data_for_users(approved_userlist $userlist) {
$context = $userlist->get_context();
if ($context instanceof \context_user) {
static::delete_user_data($context->instanceid);
}
}
/**
* Delete all user data for this user only.
*
* @param approved_contextlist $contextlist The list of approved contexts for a user.
*/
public static function delete_data_for_user(approved_contextlist $contextlist) {
if (empty($contextlist->count())) {
return;
}
$userid = $contextlist->get_user()->id;
foreach ($contextlist->get_contexts() as $context) {
if ($context->contextlevel != CONTEXT_USER) {
continue;
}
if ($context->instanceid == $userid) {
// Because we only use user contexts the instance ID is the user ID.
static::delete_user_data($context->instanceid);
}
}
}
/**
* This does the deletion of user data for the auth_oauth2.
*
* @param int $userid The user ID
*/
protected static function delete_user_data(int $userid) {
global $DB;
// Because we only use user contexts the instance ID is the user ID.
$DB->delete_records('auth_oauth2_linked_login', ['userid' => $userid]);
}
}