Moodle release 4.4beta
[moodle.git] / auth / lti / auth.php
blobc5e13fd5b459d90109b8ac3328c177f3810ec846
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.
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/>.
17 use auth_lti\local\ltiadvantage\entity\user_migration_claim;
19 defined('MOODLE_INTERNAL') || die();
21 require_once($CFG->libdir.'/authlib.php');
22 require_once($CFG->libdir.'/accesslib.php');
24 /**
25 * LTI Authentication plugin.
27 * @package auth_lti
28 * @copyright 2016 Mark Nelson <markn@moodle.com>
29 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 class auth_plugin_lti extends \auth_plugin_base {
33 /**
34 * @var int constant representing the automatic account provisioning mode.
35 * On first launch, for a previously unbound user, this mode dictates that a new Moodle account will be created automatically
36 * for the user and bound to their platform credentials {iss, sub}.
38 public const PROVISIONING_MODE_AUTO_ONLY = 1;
40 /**
41 * @var int constant representing the prompt for new or existing provisioning mode.
42 * On first launch, for a previously unbound user, the mode dictates that the launch user will be presented with an options
43 * view, allowing them to select either 'link an existing account' or 'create a new account for me'.
45 public const PROVISIONING_MODE_PROMPT_NEW_EXISTING = 2;
47 /**
48 * @var int constant representing the prompt for existing only provisioning mode.
49 * On first launch, for a previously unbound user, the mode dictates that the launch user will be presented with a view allowing
50 * them to link an existing account only. This is useful for situations like deep linking, where an existing account is needed.
52 public const PROVISIONING_MODE_PROMPT_EXISTING_ONLY = 3;
54 /**
55 * Constructor.
57 public function __construct() {
58 $this->authtype = 'lti';
61 /**
62 * Users can not log in via the traditional login form.
64 * @param string $username The username
65 * @param string $password The password
66 * @return bool Authentication success or failure
68 public function user_login($username, $password) {
69 return false;
72 /**
73 * Authenticate the user based on the unique {iss, sub} tuple present in the OIDC JWT.
75 * This method ensures a Moodle user account has been found or is created, that the user is linked to the relevant
76 * LTI Advantage credentials (iss, sub) and that the user account is logged in.
78 * Launch code can therefore rely on this method to get a session before doing things like calling require_login().
80 * This method supports two workflows:
81 * 1. Automatic account provisioning - where the complete_login() call will ALWAYS create/find a user and return to
82 * calling code directly. No user interaction is required.
84 * 2. Manual account provisioning - where the complete_login() call will redirect ONLY ONCE to a login page,
85 * where the user can decide whether to use an automatically provisioned account, or bind an existing user account.
86 * When the decision has been made, the relevant account is bound and the user is redirected back to $returnurl.
87 * Once an account has been bound via this selection process, subsequent calls to complete_login() will return to
88 * calling code directly. Any calling code must provide its $returnurl to support the return from the account
89 * selection process and must also take care to cache any JWT data appropriately, since the return will not inlude
90 * that information.
92 * Which workflow is chosen depends on the roles present in the JWT.
93 * For teachers/admins, manual provisioning will take place. These user type are likely to have existing accounts.
94 * For learners, automatic provisioning will take place.
96 * Migration of legacy users is supported, however, only for the Learner role (automatic provisioning). Admins and
97 * teachers are likely to have existing accounts and we want them to be able to select and bind these, rather than
98 * binding an automatically provisioned legacy account which doesn't represent their real user account.
100 * The JWT data must be verified elsewhere. The code here assumes its integrity/authenticity.
102 * @param array $launchdata the JWT data provided in the link launch.
103 * @param moodle_url $returnurl the local URL to return to if authentication workflows are required.
104 * @param int $provisioningmode the desired account provisioning mode, which controls the auth flow for unbound users.
105 * @param array $legacyconsumersecrets an array of secrets used by the legacy consumer if a migration claim exists.
106 * @throws coding_exception if the specified provisioning mode is invalid.
108 public function complete_login(array $launchdata, moodle_url $returnurl, int $provisioningmode,
109 array $legacyconsumersecrets = []): void {
111 // The platform user is already linked with a user account.
112 if ($this->get_user_binding($launchdata['iss'], $launchdata['sub'])) {
113 $user = $this->find_or_create_user_from_launch($launchdata);
115 if (isloggedin()) {
116 // If a different user is currently logged in, authenticate the linked user instead.
117 global $USER;
118 if ($USER->id !== $user->id) {
119 complete_user_login($user);
121 // If the linked user is already logged in, skip the call to complete_user_login() because this affects deep linking
122 // workflows on sites publishing and consuming resources on the same site, due to the regenerated sesskey.
123 } else {
124 complete_user_login($user);
127 // Always sync the PII, regardless of whether we're already authenticated as this user or not.
128 $this->update_user_account($user, $launchdata, $launchdata['iss']);
129 return;
132 // The platform user is not bound to a user account, check provisioning mode now.
133 if (!$this->is_valid_provisioning_mode($provisioningmode)) {
134 throw new coding_exception('Invalid account provisioning mode provided to complete_login().');
137 switch ($provisioningmode) {
138 case self::PROVISIONING_MODE_AUTO_ONLY:
139 // Automatic provisioning - this will create/migrate a user account and log the user in.
140 $user = $this->find_or_create_user_from_launch($launchdata, $legacyconsumersecrets);
141 complete_user_login($user);
142 $this->update_user_account($user, $launchdata, $launchdata['iss']);
143 break;
144 case self::PROVISIONING_MODE_PROMPT_NEW_EXISTING:
145 case self::PROVISIONING_MODE_PROMPT_EXISTING_ONLY:
146 default:
147 // Allow linking an existing account or creation of a new account via an intermediate account options page.
148 // Cache the relevant data and take the user to the account options page.
149 // Note: This mode also depends on the global auth config 'authpreventaccountcreation'. If set, only existing
150 // accounts can be bound in this provisioning mode.
151 global $SESSION;
152 $SESSION->auth_lti = (object)[
153 'launchdata' => $launchdata,
154 'returnurl' => $returnurl,
155 'provisioningmode' => $provisioningmode
157 redirect(new moodle_url('/auth/lti/login.php', [
158 'sesskey' => sesskey(),
159 ]));
160 break;
165 * Get a Moodle user account for the LTI user based on the user details returned by a NRPS 2 membership call.
167 * This method expects a single member structure, in array format, as defined here:
168 * See: https://www.imsglobal.org/spec/lti-nrps/v2p0#membership-container-media-type.
170 * This method supports migration of user accounts used in legacy launches, provided the legacy consumerkey corresponding to
171 * to the legacy consumer is provided. Calling code will have verified the migration claim during initial launches and should
172 * have the consumer key mapped to the deployment, ready to pass in.
174 * @param array $member the member data, in array format.
175 * @param string $iss the issuer to which the member relates.
176 * @param string $legacyconsumerkey optional consumer key mapped to the deployment to facilitate user migration.
177 * @return stdClass a Moodle user record.
179 public function find_or_create_user_from_membership(array $member, string $iss,
180 string $legacyconsumerkey = ''): stdClass {
182 // Picture is not synced with membership-based auths because sync tasks may wish to perform slow operations like this a
183 // different way.
184 unset($member['picture']);
186 if ($binduser = $this->get_user_binding($iss, $member['user_id'])) {
187 $user = \core_user::get_user($binduser);
188 $this->update_user_account($user, $member, $iss);
189 return \core_user::get_user($user->id);
190 } else {
191 if (!empty($legacyconsumerkey)) {
192 // Consumer key is required to attempt user migration because legacy users were identified by a
193 // username consisting of the consumer key and user id.
194 // See the legacy \enrol_lti\helper::create_username() for details.
195 $legacyuserid = $member['lti11_legacy_user_id'] ?? $member['user_id'];
196 $username = 'enrol_lti' .
197 sha1($legacyconsumerkey . '::' . $legacyconsumerkey . ':' . $legacyuserid);
198 if ($user = \core_user::get_user_by_username($username)) {
199 $this->create_user_binding($iss, $member['user_id'], $user->id);
200 $this->update_user_account($user, $member, $iss);
201 return \core_user::get_user($user->id);
204 $user = $this->create_new_account($member, $iss);
205 return \core_user::get_user($user->id);
210 * Get a Moodle user account for the LTI user corresponding to the user defined in a link launch.
212 * This method supports migration of user accounts used in legacy launches, provided the legacy consumer secrets corresponding
213 * to the legacy consumer are provided. If calling code wishes migration to be role-specific, it should check roles accordingly
214 * itself and pass relevant data in - as auth_plugin_lti::complete_login() does.
216 * @param array $launchdata all data in the decoded JWT including iss and sub.
217 * @param array $legacyconsumersecrets all secrets found for the legacy consumer, facilitating user migration.
218 * @return stdClass the Moodle user who is mapped to the platform user identified in the JWT data.
220 public function find_or_create_user_from_launch(array $launchdata, array $legacyconsumersecrets = []): stdClass {
222 if ($binduser = $this->get_user_binding($launchdata['iss'], $launchdata['sub'])) {
223 return \core_user::get_user($binduser);
224 } else {
225 // Is the intent to migrate a user account used in legacy launches?
226 if (!empty($legacyconsumersecrets)) {
227 try {
228 // Validate the migration claim and try to find a legacy user.
229 $usermigrationclaim = new user_migration_claim($launchdata, $legacyconsumersecrets);
230 $username = 'enrol_lti' .
231 sha1($usermigrationclaim->get_consumer_key() . '::' .
232 $usermigrationclaim->get_consumer_key() . ':' . $usermigrationclaim->get_user_id());
233 if ($user = core_user::get_user_by_username($username)) {
234 $this->create_user_binding($launchdata['iss'], $launchdata['sub'], $user->id);
235 return core_user::get_user($user->id);
237 } catch (Exception $e) {
238 // There was an issue validating the user migration claim. We don't want to fail auth entirely though.
239 // Rather, we want to fall back to new account creation and log the attempt.
240 debugging("There was a problem migrating the LTI user '{$launchdata['sub']}' on the platform " .
241 "'{$launchdata['iss']}'. The migration claim could not be validated. A new account will be created.");
244 // At the point of the creation, to ensure the user_created event correctly reflects the creating user of '0' (the user
245 // performing the action), ensure any active session is terminated and an empty session initialised.
246 $this->empty_session();
248 $user = $this->create_new_account($launchdata, $launchdata['iss']);
249 return core_user::get_user($user->id);
254 * Create a binding between the LTI user, as identified by {iss, sub} tuple and the user id.
256 * @param string $iss the issuer URL identifying the platform to which to user belongs.
257 * @param string $sub the sub string identifying the user on the platform.
258 * @param int $userid the id of the Moodle user account to bind.
260 public function create_user_binding(string $iss, string $sub, int $userid): void {
261 global $DB;
263 $timenow = time();
264 $issuer256 = hash('sha256', $iss);
265 $sub256 = hash('sha256', $sub);
266 if ($DB->record_exists('auth_lti_linked_login', ['issuer256' => $issuer256, 'sub256' => $sub256])) {
267 return;
269 $rec = [
270 'userid' => $userid,
271 'issuer' => $iss,
272 'issuer256' => $issuer256,
273 'sub' => $sub,
274 'sub256' => $sub256,
275 'timecreated' => $timenow,
276 'timemodified' => $timenow
278 $DB->insert_record('auth_lti_linked_login', $rec);
282 * Gets the id of the linked Moodle user account for an LTI user, or null if not found.
284 * @param string $issuer the issuer to which the user belongs.
285 * @param string $sub the sub string identifying the user on the issuer.
286 * @return int|null the id of the corresponding Moodle user record, or null if not found.
288 public function get_user_binding(string $issuer, string $sub): ?int {
289 global $DB;
290 $issuer256 = hash('sha256', $issuer);
291 $sub256 = hash('sha256', $sub);
292 try {
293 $binduser = $DB->get_field('auth_lti_linked_login', 'userid',
294 ['issuer256' => $issuer256, 'sub256' => $sub256], MUST_EXIST);
295 } catch (\dml_exception $e) {
296 $binduser = null;
298 return $binduser;
302 * If there's an existing session, inits an empty session.
304 * @return void
306 protected function empty_session(): void {
307 if (isloggedin()) {
308 \core\session\manager::init_empty_session();
313 * Check whether a provisioning mode is valid or not.
315 * @param int $mode the mode
316 * @return bool true if valid for use, false otherwise.
318 protected function is_valid_provisioning_mode(int $mode): bool {
319 $validmodes = [
320 self::PROVISIONING_MODE_AUTO_ONLY,
321 self::PROVISIONING_MODE_PROMPT_NEW_EXISTING,
322 self::PROVISIONING_MODE_PROMPT_EXISTING_ONLY
324 return in_array($mode, $validmodes);
328 * Create a new user account based on the user data either in the launch JWT or from a membership call.
330 * @param array $userdata the user data coming from either a launch or membership service call.
331 * @param string $iss the issuer to which the user belongs.
332 * @return stdClass a complete Moodle user record.
334 protected function create_new_account(array $userdata, string $iss): stdClass {
336 global $CFG;
337 require_once($CFG->dirroot.'/user/lib.php');
339 // Launches and membership calls handle the user id differently.
340 // Launch uses 'sub', whereas member uses 'user_id'.
341 $userid = !empty($userdata['sub']) ? $userdata['sub'] : $userdata['user_id'];
343 $user = new stdClass();
344 $user->username = 'enrol_lti_13_' . sha1($iss . '_' . $userid);
345 // If the email was stripped/not set then fill it with a default one.
346 // This stops the user from being redirected to edit their profile page.
347 $email = !empty($userdata['email']) ? $userdata['email'] :
348 'enrol_lti_13_' . sha1($iss . '_' . $userid) . "@example.com";
349 $email = \core_user::clean_field($email, 'email');
350 $user->email = $email;
351 $user->auth = 'lti';
352 $user->mnethostid = $CFG->mnet_localhost_id;
353 $user->firstname = $userdata['given_name'] ?? $userid;
354 $user->lastname = $userdata['family_name'] ?? $iss;
355 $user->password = '';
356 $user->confirmed = 1;
357 $user->id = user_create_user($user, false);
359 // Link this user with the LTI credentials for future use.
360 $this->create_user_binding($iss, $userid, $user->id);
362 return (object) get_complete_user_data('id', $user->id);
366 * Update the personal fields of the user account, based on data present in either a launch of member sync call.
368 * @param stdClass $user the Moodle user account to update.
369 * @param array $userdata the user data coming from either a launch or membership service call.
370 * @param string $iss the issuer to which the user belongs.
372 public function update_user_account(stdClass $user, array $userdata, string $iss): void {
373 global $CFG;
374 require_once($CFG->dirroot.'/user/lib.php');
375 if ($user->auth !== 'lti') {
376 return;
379 // Launches and membership calls handle the user id differently.
380 // Launch uses 'sub', whereas member uses 'user_id'.
381 $platformuserid = !empty($userdata['sub']) ? $userdata['sub'] : $userdata['user_id'];
382 $email = !empty($userdata['email']) ? $userdata['email'] :
383 'enrol_lti_13_' . sha1($iss . '_' . $platformuserid) . "@example.com";
384 $email = \core_user::clean_field($email, 'email');
385 $update = [
386 'id' => $user->id,
387 'firstname' => $userdata['given_name'] ?? $platformuserid,
388 'lastname' => $userdata['family_name'] ?? $iss,
389 'email' => $email
391 $userfieldstocompare = array_intersect_key((array) $user, $update);
393 if (!empty(array_diff($update, $userfieldstocompare))) {
394 user_update_user($update); // Only update if there's a change.
397 if (!empty($userdata['picture'])) {
398 try {
399 $this->update_user_picture($user->id, $userdata['picture']);
400 } catch (Exception $e) {
401 debugging("Error syncing the profile picture for user '$user->id' during LTI authentication.");
407 * Update the user's picture with the image stored at $url.
409 * @param int $userid the id of the user to update.
410 * @param string $url the string URL where the new image can be found.
411 * @throws moodle_exception if there were any problems updating the picture.
413 protected function update_user_picture(int $userid, string $url): void {
414 global $CFG, $DB;
416 require_once($CFG->libdir . '/filelib.php');
417 require_once($CFG->libdir . '/gdlib.php');
419 $fs = get_file_storage();
421 $context = \context_user::instance($userid, MUST_EXIST);
422 $fs->delete_area_files($context->id, 'user', 'newicon');
424 $filerecord = array(
425 'contextid' => $context->id,
426 'component' => 'user',
427 'filearea' => 'newicon',
428 'itemid' => 0,
429 'filepath' => '/'
432 $urlparams = array(
433 'calctimeout' => false,
434 'timeout' => 5,
435 'skipcertverify' => true,
436 'connecttimeout' => 5
439 try {
440 $fs->create_file_from_url($filerecord, $url, $urlparams);
441 } catch (\file_exception $e) {
442 throw new moodle_exception(get_string($e->errorcode, $e->module, $e->a));
445 $iconfile = $fs->get_area_files($context->id, 'user', 'newicon', false, 'itemid', false);
447 // There should only be one.
448 $iconfile = reset($iconfile);
450 // Something went wrong while creating temp file - remove the uploaded file.
451 if (!$iconfile = $iconfile->copy_content_to_temp()) {
452 $fs->delete_area_files($context->id, 'user', 'newicon');
453 throw new moodle_exception('There was a problem copying the profile picture to temp.');
456 // Copy file to temporary location and the send it for processing icon.
457 $newpicture = (int) process_new_icon($context, 'user', 'icon', 0, $iconfile);
458 // Delete temporary file.
459 @unlink($iconfile);
460 // Remove uploaded file.
461 $fs->delete_area_files($context->id, 'user', 'newicon');
462 // Set the user's picture.
463 $DB->set_field('user', 'picture', $newpicture, array('id' => $userid));