Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

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