MDL-58220 oauth2: Fix account linking
[moodle.git] / auth / oauth2 / classes / auth.php
CommitLineData
60237253
DW
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
25namespace auth_oauth2;
26
27defined('MOODLE_INTERNAL') || die();
28
29use pix_icon;
30use moodle_url;
31use core_text;
28b592d5 32use context_system;
60237253
DW
33use stdClass;
34use core\oauth2\issuer;
35use core\oauth2\client;
36
37require_once($CFG->libdir.'/authlib.php');
38
39/**
40 * Plugin for oauth2 authentication.
41 *
42 * @package auth_oauth2
43 * @copyright 2017 Damyon Wiese
44 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
45 */
46class auth extends \auth_plugin_base {
47
48 /**
49 * @var stdClass $userinfo The set of user info returned from the oauth handshake
50 */
51 private static $userinfo;
52
53 /**
54 * @var stdClass $userpicture The url to a picture.
55 */
56 private static $userpicture;
57
58 /**
59 * Constructor.
60 */
61 public function __construct() {
62 $this->authtype = 'oauth2';
63 $this->config = get_config('auth_oauth2');
64 }
65
66 /**
67 * Returns true if the username and password work or don't exist and false
68 * if the user exists and the password is wrong.
69 *
70 * @param string $username The username
71 * @param string $password The password
72 * @return bool Authentication success or failure.
73 */
74 public function user_login($username, $password) {
75 $cached = $this->get_static_user_info();
bfc60d38
DW
76 if (empty($cached)) {
77 // This means we were called as part of a normal login flow - without using oauth.
78 return false;
79 }
60237253
DW
80 $verifyusername = $cached['username'];
81 if ($verifyusername == $username) {
82 return true;
83 }
979d1f66 84 return false;
60237253
DW
85 }
86
87 /**
88 * We don't want to allow users setting an internal password.
89 *
90 * @return bool
91 */
92 public function prevent_local_passwords() {
93 return true;
94 }
95
96 /**
97 * Returns true if this authentication plugin is 'internal'.
98 *
99 * @return bool
100 */
101 public function is_internal() {
102 return false;
103 }
104
105 /**
106 * Indicates if moodle should automatically update internal user
107 * records with data from external sources using the information
108 * from auth_plugin_base::get_userinfo().
109 *
110 * @return bool true means automatically copy data from ext to user table
111 */
112 public function is_synchronised_with_external() {
28b592d5 113 return false;
60237253
DW
114 }
115
116 /**
117 * Returns true if this authentication plugin can change the user's
118 * password.
119 *
120 * @return bool
121 */
122 public function can_change_password() {
123 return false;
124 }
125
126 /**
127 * Returns the URL for changing the user's pw, or empty if the default can
128 * be used.
129 *
130 * @return moodle_url
131 */
132 public function change_password_url() {
133 return null;
134 }
135
136 /**
137 * Returns true if plugin allows resetting of internal password.
138 *
139 * @return bool
140 */
141 public function can_reset_password() {
142 return false;
143 }
144
145 /**
146 * Returns true if plugin can be manually set.
147 *
148 * @return bool
149 */
150 public function can_be_manually_set() {
151 return true;
152 }
153
154 /**
155 * Prints a form for configuring this authentication plugin.
156 *
157 * This function is called from admin/auth.php, and outputs a full page with
158 * a form for configuring this plugin.
159 *
160 * @param stdClass $config
161 * @param string $err
29911249 162 * @param array $userfields
60237253
DW
163 */
164 public function config_form($config, $err, $userfields) {
1dca8d1a 165 include(__DIR__ . "/../config.html");
60237253 166
60237253
DW
167 return;
168 }
169
170 /**
171 * Return the userinfo from the oauth handshake. Will only be valid
172 * for the logged in user.
72fd103a 173 * @param string $username
60237253
DW
174 */
175 public function get_userinfo($username) {
176 $cached = $this->get_static_user_info();
177 if (!empty($cached) && $cached['username'] == $username) {
178 return $cached;
179 }
180 return false;
181 }
182
f9f243f9
DW
183 /**
184 * Do some checks on the identity provider before showing it on the login page.
29911249 185 * @param core\oauth2\issuer $issuer
f9f243f9
DW
186 * @return boolean
187 */
188 private function is_ready_for_login_page(\core\oauth2\issuer $issuer) {
eca128bf 189 return $issuer->get('enabled') &&
5b0b35c0 190 $issuer->is_configured() &&
60237253
DW
191 !empty($issuer->get('showonloginpage'));
192 }
193
194 /**
195 * Return a list of identity providers to display on the login page.
f9f243f9
DW
196 *
197 * @param string|moodle_url $wantsurl The requested URL.
198 * @return array (containing url, iconurl and name).
60237253
DW
199 */
200 public function loginpage_idp_list($wantsurl) {
201 $providers = \core\oauth2\api::get_all_issuers();
202 $result = [];
203 if (empty($wantsurl)) {
204 $wantsurl = '/';
205 }
206 foreach ($providers as $idp) {
207 if ($this->is_ready_for_login_page($idp)) {
208 $params = ['id' => $idp->get('id'), 'wantsurl' => $wantsurl, 'sesskey' => sesskey()];
209 $url = new moodle_url('/auth/oauth2/login.php', $params);
210 $icon = $idp->get('image');
211 $result[] = ['url' => $url, 'iconurl' => $icon, 'name' => $idp->get('name')];
212 }
213 }
214 return $result;
215 }
216
217 /**
218 * Statically cache the user info from the oauth handshake
219 * @param stdClass $userinfo
220 */
221 private function set_static_user_info($userinfo) {
222 self::$userinfo = $userinfo;
223 }
224
225 /**
226 * Get the static cached user info
227 * @return stdClass
228 */
229 private function get_static_user_info() {
230 return self::$userinfo;
231 }
232
233 /**
234 * Statically cache the user picture from the oauth handshake
235 * @param string $userpicture
236 */
237 private function set_static_user_picture($userpicture) {
238 self::$userpicture = $userpicture;
239 }
240
241 /**
242 * Get the static cached user picture
243 * @return string
244 */
245 private function get_static_user_picture() {
246 return self::$userpicture;
247 }
248
249 /**
250 * If this user has no picture - but we got one from oauth - set it.
29911249 251 * @param stdClass $user
60237253
DW
252 * @return boolean True if the image was updated.
253 */
254 private function update_picture($user) {
255 global $CFG, $DB, $USER;
256
257 require_once($CFG->libdir . '/filelib.php');
258 require_once($CFG->libdir . '/gdlib.php');
259
260 $fs = get_file_storage();
261 $userid = $user->id;
262 if (!empty($user->picture)) {
263 return false;
264 }
265 $picture = $this->get_static_user_picture();
266 if (empty($picture)) {
267 return false;
268 }
269
270 $context = \context_user::instance($userid, MUST_EXIST);
271 $fs->delete_area_files($context->id, 'user', 'newicon');
272
273 $filerecord = array(
274 'contextid' => $context->id,
275 'component' => 'user',
276 'filearea' => 'newicon',
277 'itemid' => 0,
278 'filepath' => '/',
279 'filename' => 'image'
280 );
281
282 try {
283 $fs->create_file_from_string($filerecord, $picture);
284 } catch (\file_exception $e) {
285 return get_string($e->errorcode, $e->module, $e->a);
286 }
287
288 $iconfile = $fs->get_area_files($context->id, 'user', 'newicon', false, 'itemid', false);
289
290 // There should only be one.
291 $iconfile = reset($iconfile);
292
293 // Something went wrong while creating temp file - remove the uploaded file.
294 if (!$iconfile = $iconfile->copy_content_to_temp()) {
295 $fs->delete_area_files($context->id, 'user', 'newicon');
296 return false;
297 }
298
299 // Copy file to temporary location and the send it for processing icon.
300 $newpicture = (int) process_new_icon($context, 'user', 'icon', 0, $iconfile);
301 // Delete temporary file.
302 @unlink($iconfile);
303 // Remove uploaded file.
304 $fs->delete_area_files($context->id, 'user', 'newicon');
305 // Set the user's picture.
306 $updateuser = new stdClass();
307 $updateuser->id = $userid;
308 $updateuser->picture = $newpicture;
309 $USER->picture = $newpicture;
310 user_update_user($updateuser);
311 return true;
312 }
313
72fd103a 314 /**
28b592d5
DW
315 * Confirm the new user as registered.
316 *
317 * @param string $username
318 * @param string $confirmsecret
72fd103a 319 */
13b449f4 320 public function user_confirm($username, $confirmsecret) {
28b592d5
DW
321 global $DB;
322 $user = get_complete_user_data('username', $username);
323
324 if (!empty($user)) {
325 if ($user->auth != $this->authtype) {
326 return AUTH_CONFIRM_ERROR;
327
328 } else if ($user->secret == $confirmsecret && $user->confirmed) {
329 return AUTH_CONFIRM_ALREADY;
330
13b449f4
DW
331 } else if ($user->secret == $confirmsecret) { // They have provided the secret key to get in.
332 $DB->set_field("user", "confirmed", 1, array("id" => $user->id));
28b592d5
DW
333 return AUTH_CONFIRM_OK;
334 }
335 } else {
336 return AUTH_CONFIRM_ERROR;
1dca8d1a 337 }
28b592d5
DW
338 }
339
340 /**
341 * Print a page showing that a confirm email was sent with instructions.
342 *
13b449f4
DW
343 * @param string $title
344 * @param string $message
28b592d5
DW
345 */
346 public function print_confirm_required($title, $message) {
347 global $PAGE, $OUTPUT, $CFG;
348
349 $PAGE->navbar->add($title);
350 $PAGE->set_title($title);
351 $PAGE->set_heading($PAGE->course->fullname);
352 echo $OUTPUT->header();
353 notice($message, "$CFG->httpswwwroot/index.php");
1dca8d1a
DW
354 }
355
60237253
DW
356 /**
357 * Complete the login process after oauth handshake is complete.
358 * @param \core\oauth2\client $client
359 * @param string $redirecturl
360 * @return none Either redirects or throws an exception
361 */
362 public function complete_login(client $client, $redirecturl) {
28b592d5 363 global $CFG, $SESSION, $PAGE;
60237253
DW
364
365 $userinfo = $client->get_userinfo();
366
367 if (!$userinfo) {
6cee96c8
DW
368 // Trigger login failed event.
369 $failurereason = AUTH_LOGIN_NOUSER;
370 $event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
371 'reason' => $failurereason]]);
372 $event->trigger();
373
7f158660 374 $errormsg = get_string('loginerror_nouserinfo', 'auth_oauth2');
60237253
DW
375 $SESSION->loginerrormsg = $errormsg;
376 redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
8445556b 377 }
28b592d5 378 if (empty($userinfo['username']) || empty($userinfo['email'])) {
6cee96c8
DW
379 // Trigger login failed event.
380 $failurereason = AUTH_LOGIN_NOUSER;
381 $event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
382 'reason' => $failurereason]]);
383 $event->trigger();
384
7f158660 385 $errormsg = get_string('loginerror_userincomplete', 'auth_oauth2');
8445556b
DW
386 $SESSION->loginerrormsg = $errormsg;
387 redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
60237253
DW
388 }
389
390 $userinfo['username'] = trim(core_text::strtolower($userinfo['username']));
391
28b592d5 392 // Once we get here we have the user info from oauth.
1dca8d1a 393 $userwasmapped = false;
1dca8d1a 394
28b592d5
DW
395 // Clean and remember the picture / lang.
396 if (!empty($userinfo['picture'])) {
397 $this->set_static_user_picture($userinfo['picture']);
398 unset($userinfo['picture']);
399 }
400
401 if (!empty($userinfo['lang'])) {
402 $userinfo['lang'] = str_replace('-', '_', trim(core_text::strtolower($userinfo['lang'])));
403 if (!get_string_manager()->translation_exists($userinfo['lang'], false)) {
404 unset($userinfo['lang']);
405 }
406 }
407
408 // First we try and find a defined mapping.
409 $linkedlogin = api::match_username_to_user($userinfo['username'], $client->get_issuer());
410
411 if (!empty($linkedlogin) && empty($linkedlogin->get('confirmtoken'))) {
412 $mappeduser = get_complete_user_data('id', $linkedlogin->get('userid'));
413
414 if ($mappeduser && $mappeduser->confirmed) {
1dca8d1a
DW
415 $userinfo = (array) $mappeduser;
416 $userwasmapped = true;
28b592d5 417 } else {
6cee96c8
DW
418 // Trigger login failed event.
419 $failurereason = AUTH_LOGIN_UNAUTHORISED;
420 $event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
421 'reason' => $failurereason]]);
422 $event->trigger();
423
28b592d5
DW
424 $errormsg = get_string('confirmationpending', 'auth_oauth2');
425 $SESSION->loginerrormsg = $errormsg;
426 redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
1dca8d1a 427 }
28b592d5 428 } else if (!empty($linkedlogin)) {
6cee96c8
DW
429 // Trigger login failed event.
430 $failurereason = AUTH_LOGIN_UNAUTHORISED;
431 $event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
432 'reason' => $failurereason]]);
433 $event->trigger();
434
28b592d5
DW
435 $errormsg = get_string('confirmationpending', 'auth_oauth2');
436 $SESSION->loginerrormsg = $errormsg;
437 redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
438 }
439 $issuer = $client->get_issuer();
440 if (!$issuer->is_valid_login_domain($userinfo['email'])) {
6cee96c8
DW
441 // Trigger login failed event.
442 $failurereason = AUTH_LOGIN_UNAUTHORISED;
443 $event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
444 'reason' => $failurereason]]);
445 $event->trigger();
446
7f158660 447 $errormsg = get_string('notloggedindebug', 'auth_oauth2', get_string('loginerror_invaliddomain', 'auth_oauth2'));
28b592d5
DW
448 $SESSION->loginerrormsg = $errormsg;
449 redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
60237253
DW
450 }
451
1dca8d1a 452 if (!$userwasmapped) {
28b592d5
DW
453 // No defined mapping - we need to see if there is an existing account with the same email.
454
455 $moodleuser = \core_user::get_user_by_email($userinfo['email']);
456 if (!empty($moodleuser)) {
457 $PAGE->set_url('/auth/oauth2/confirm-link-login.php');
458 $PAGE->set_context(context_system::instance());
459
460 \auth_oauth2\api::send_confirm_link_login_email($userinfo, $issuer, $moodleuser->id);
461 // Request to link to existing account.
462 $emailconfirm = get_string('emailconfirmlink', 'auth_oauth2');
463 $message = get_string('emailconfirmlinksent', 'auth_oauth2', $moodleuser->email);
464 $this->print_confirm_required($emailconfirm, $message);
465 exit();
466
467 } else {
468 // This is a new account.
469 $exists = \core_user::get_user_by_username($userinfo['username']);
470 // Creating a new user?
471 if ($exists) {
6cee96c8
DW
472 // Trigger login failed event.
473 $failurereason = AUTH_LOGIN_FAILED;
474 $event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
475 'reason' => $failurereason]]);
476 $event->trigger();
28b592d5
DW
477
478 // The username exists but the emails don't match. Refuse to continue.
479 $errormsg = get_string('accountexists', 'auth_oauth2');
480 $SESSION->loginerrormsg = $errormsg;
481 redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
482 }
1dca8d1a 483
28b592d5 484 if (email_is_not_allowed($userinfo['email'])) {
6cee96c8
DW
485 // Trigger login failed event.
486 $failurereason = AUTH_LOGIN_FAILED;
487 $event = \core\event\user_login_failed::create(['other' => ['username' => $userinfo['username'],
488 'reason' => $failurereason]]);
489 $event->trigger();
28b592d5 490 // The username exists but the emails don't match. Refuse to continue.
7f158660
DW
491 $reason = get_string('loginerror_invaliddomain', 'auth_oauth2');
492 $errormsg = get_string('notloggedindebug', 'auth_oauth2', $reason);
28b592d5
DW
493 $SESSION->loginerrormsg = $errormsg;
494 redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
1dca8d1a 495 }
1dca8d1a 496
6cee96c8
DW
497 if (!empty($CFG->authpreventaccountcreation)) {
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 // The username does not exist and settings prevent creating new accounts.
504 $reason = get_string('loginerror_cannotcreateaccounts', 'auth_oauth2');
505 $errormsg = get_string('notloggedindebug', 'auth_oauth2', $reason);
506 $SESSION->loginerrormsg = $errormsg;
507 redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
508 }
509
28b592d5
DW
510 $PAGE->set_url('/auth/oauth2/confirm-account.php');
511 $PAGE->set_context(context_system::instance());
512
513 // Create a new (unconfirmed account) and send an email to confirm it.
514 $user = \auth_oauth2\api::send_confirm_account_email($userinfo, $issuer);
60237253 515
28b592d5
DW
516 $this->update_picture($user);
517 $emailconfirm = get_string('emailconfirm');
518 $message = get_string('emailconfirmsent', '', $userinfo['email']);
519 $this->print_confirm_required($emailconfirm, $message);
520 exit();
28b592d5 521 }
c21a66e4 522 }
60237253 523
f3315133
DW
524 // We used to call authenticate_user - but that won't work if the current user has a different default authentication
525 // method. Since we now ALWAYS link a login - if we get to here we can directly allow the user in.
526 $user = (object) $userinfo;
527 complete_user_login($user);
528 $this->update_picture($user);
529 redirect($redirecturl);
60237253
DW
530 }
531}
532
533