Merge branch 'MDL-51998_master' of https://github.com/nadavkav/moodle
[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) {
7f158660 368 $errormsg = get_string('loginerror_nouserinfo', 'auth_oauth2');
60237253
DW
369 $SESSION->loginerrormsg = $errormsg;
370 redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
8445556b 371 }
28b592d5 372 if (empty($userinfo['username']) || empty($userinfo['email'])) {
7f158660 373 $errormsg = get_string('loginerror_userincomplete', 'auth_oauth2');
8445556b
DW
374 $SESSION->loginerrormsg = $errormsg;
375 redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
60237253
DW
376 }
377
378 $userinfo['username'] = trim(core_text::strtolower($userinfo['username']));
379
28b592d5 380 // Once we get here we have the user info from oauth.
1dca8d1a 381 $userwasmapped = false;
1dca8d1a 382
28b592d5
DW
383 // Clean and remember the picture / lang.
384 if (!empty($userinfo['picture'])) {
385 $this->set_static_user_picture($userinfo['picture']);
386 unset($userinfo['picture']);
387 }
388
389 if (!empty($userinfo['lang'])) {
390 $userinfo['lang'] = str_replace('-', '_', trim(core_text::strtolower($userinfo['lang'])));
391 if (!get_string_manager()->translation_exists($userinfo['lang'], false)) {
392 unset($userinfo['lang']);
393 }
394 }
395
396 // First we try and find a defined mapping.
397 $linkedlogin = api::match_username_to_user($userinfo['username'], $client->get_issuer());
398
399 if (!empty($linkedlogin) && empty($linkedlogin->get('confirmtoken'))) {
400 $mappeduser = get_complete_user_data('id', $linkedlogin->get('userid'));
401
402 if ($mappeduser && $mappeduser->confirmed) {
1dca8d1a
DW
403 $userinfo = (array) $mappeduser;
404 $userwasmapped = true;
28b592d5
DW
405 } else {
406 $errormsg = get_string('confirmationpending', 'auth_oauth2');
407 $SESSION->loginerrormsg = $errormsg;
408 redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
1dca8d1a 409 }
28b592d5
DW
410 } else if (!empty($linkedlogin)) {
411 $errormsg = get_string('confirmationpending', 'auth_oauth2');
412 $SESSION->loginerrormsg = $errormsg;
413 redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
414 }
415 $issuer = $client->get_issuer();
416 if (!$issuer->is_valid_login_domain($userinfo['email'])) {
7f158660 417 $errormsg = get_string('notloggedindebug', 'auth_oauth2', get_string('loginerror_invaliddomain', 'auth_oauth2'));
28b592d5
DW
418 $SESSION->loginerrormsg = $errormsg;
419 redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
60237253
DW
420 }
421
1dca8d1a 422 if (!$userwasmapped) {
28b592d5
DW
423 // No defined mapping - we need to see if there is an existing account with the same email.
424
425 $moodleuser = \core_user::get_user_by_email($userinfo['email']);
426 if (!empty($moodleuser)) {
427 $PAGE->set_url('/auth/oauth2/confirm-link-login.php');
428 $PAGE->set_context(context_system::instance());
429
430 \auth_oauth2\api::send_confirm_link_login_email($userinfo, $issuer, $moodleuser->id);
431 // Request to link to existing account.
432 $emailconfirm = get_string('emailconfirmlink', 'auth_oauth2');
433 $message = get_string('emailconfirmlinksent', 'auth_oauth2', $moodleuser->email);
434 $this->print_confirm_required($emailconfirm, $message);
435 exit();
436
437 } else {
438 // This is a new account.
439 $exists = \core_user::get_user_by_username($userinfo['username']);
440 // Creating a new user?
441 if ($exists) {
442
443 // The username exists but the emails don't match. Refuse to continue.
444 $errormsg = get_string('accountexists', 'auth_oauth2');
445 $SESSION->loginerrormsg = $errormsg;
446 redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
447 }
1dca8d1a 448
28b592d5
DW
449 if (email_is_not_allowed($userinfo['email'])) {
450 // The username exists but the emails don't match. Refuse to continue.
7f158660
DW
451 $reason = get_string('loginerror_invaliddomain', 'auth_oauth2');
452 $errormsg = get_string('notloggedindebug', 'auth_oauth2', $reason);
28b592d5
DW
453 $SESSION->loginerrormsg = $errormsg;
454 redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
1dca8d1a 455 }
1dca8d1a 456
28b592d5
DW
457 $PAGE->set_url('/auth/oauth2/confirm-account.php');
458 $PAGE->set_context(context_system::instance());
459
460 // Create a new (unconfirmed account) and send an email to confirm it.
461 $user = \auth_oauth2\api::send_confirm_account_email($userinfo, $issuer);
60237253 462
28b592d5
DW
463 $this->update_picture($user);
464 $emailconfirm = get_string('emailconfirm');
465 $message = get_string('emailconfirmsent', '', $userinfo['email']);
466 $this->print_confirm_required($emailconfirm, $message);
467 exit();
c21a66e4 468
28b592d5 469 }
c21a66e4 470 }
60237253 471
28b592d5
DW
472 // If we got to here - we must have found a real user account that is confirmed.
473 $this->set_static_user_info($userinfo);
474 $user = authenticate_user_login($userinfo['username'], '');
475
60237253
DW
476 if ($user) {
477 complete_user_login($user);
478 $this->update_picture($user);
479 redirect($redirecturl);
480 }
7f158660 481 $errormsg = get_string('notloggedindebug', 'auth_oauth2', get_string('loginerror_authenticationfailed', 'auth_oauth2'));
60237253
DW
482 $SESSION->loginerrormsg = $errormsg;
483 redirect(new moodle_url($CFG->httpswwwroot . '/login/index.php'));
484 }
485}
486
487