MDL-68178 auth: CSRF protection for the resend confirmation email form
[moodle.git] / login / index.php
CommitLineData
8570cff0 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
c30949a9 19 * Main login page.
8570cff0 20 *
c30949a9
PS
21 * @package core
22 * @subpackage auth
23 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8570cff0 25 */
26
c30949a9 27require('../config.php');
f4491c2a 28require_once('lib.php');
8570cff0 29
30redirect_if_major_upgrade_required();
31
8a8f1c7c 32$testsession = optional_param('testsession', 0, PARAM_INT); // test session works properly
9bcc3571 33$anchor = optional_param('anchor', '', PARAM_RAW); // Used to restore hash anchor to wantsurl.
6dfe4283 34
08c69a14 35$resendconfirmemail = optional_param('resendconfirmemail', false, PARAM_BOOL);
3354eb8c 36
9bcc3571
TH
37// It might be safe to do this for non-Behat sites, or there might
38// be a security risk. For now we only allow it on Behat sites.
39// If you wants to do the analysis, you may be able to remove the
40// if (BEHAT_SITE_RUNNING).
41if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
42 $wantsurl = optional_param('wantsurl', '', PARAM_LOCALURL); // Overrides $SESSION->wantsurl if given.
43 if ($wantsurl !== '') {
44 $SESSION->wantsurl = (new moodle_url($wantsurl))->out(false);
45 }
46}
47
a689cd1d 48$context = context_system::instance();
672f4836 49$PAGE->set_url("$CFG->wwwroot/login/index.php");
c30949a9 50$PAGE->set_context($context);
191b267b 51$PAGE->set_pagelayout('login');
d529807a 52
f716d0dd 53/// Initialize variables
8570cff0 54$errormsg = '';
55$errorcode = 0;
3e5c8474 56
8a8f1c7c
PS
57// login page requested session test
58if ($testsession) {
59 if ($testsession == $USER->id) {
60 if (isset($SESSION->wantsurl)) {
61 $urltogo = $SESSION->wantsurl;
62 } else {
63 $urltogo = $CFG->wwwroot.'/';
64 }
65 unset($SESSION->wantsurl);
66 redirect($urltogo);
67 } else {
68 // TODO: try to find out what is the exact reason why sessions do not work
69 $errormsg = get_string("cookiesnotenabled");
70 $errorcode = 1;
71 }
72}
73
1c6932d8 74/// Check for timed out sessions
8570cff0 75if (!empty($SESSION->has_timed_out)) {
76 $session_has_timed_out = true;
77 unset($SESSION->has_timed_out);
78} else {
79 $session_has_timed_out = false;
80}
1c6932d8 81
8570cff0 82$frm = false;
83$user = false;
6bc1e5d5 84
8570cff0 85$authsequence = get_enabled_auth_plugins(true); // auths, in sequence
86foreach($authsequence as $authname) {
87 $authplugin = get_auth_plugin($authname);
667f564b 88 // The auth plugin's loginpage_hook() can eventually set $frm and/or $user.
8570cff0 89 $authplugin->loginpage_hook();
90}
6bc1e5d5 91
244a32c6 92
a718d872 93/// Define variables used in page
3f77c158 94$site = get_site();
8570cff0 95
aac8dfa8
SH
96// Ignore any active pages in the navigation/settings.
97// We do this because there won't be an active page there, and by ignoring the active pages the
98// navigation and settings won't be initialised unless something else needs them.
99$PAGE->navbar->ignore_active();
8570cff0 100$loginsite = get_string("loginsite");
101$PAGE->navbar->add($loginsite);
102
f23a1761
PS
103if ($user !== false or $frm !== false or $errormsg !== '') {
104 // some auth plugin already supplied full user, fake form data or prevented user login with error message
8570cff0 105
8570cff0 106} else if (!empty($SESSION->wantsurl) && file_exists($CFG->dirroot.'/login/weblinkauth.php')) {
107 // Handles the case of another Moodle site linking into a page on this site
108 //TODO: move weblink into own auth plugin
109 include($CFG->dirroot.'/login/weblinkauth.php');
110 if (function_exists('weblink_auth')) {
111 $user = weblink_auth($SESSION->wantsurl);
089b19f6 112 }
8570cff0 113 if ($user) {
114 $frm->username = $user->username;
d00377f5 115 } else {
294ce987 116 $frm = data_submitted();
d00377f5 117 }
a9b07c52 118
8570cff0 119} else {
120 $frm = data_submitted();
121}
122
e1d6edb3
BH
123// Restore the #anchor to the original wantsurl. Note that this
124// will only work for internal auth plugins, SSO plugins such as
125// SAML / CAS / OIDC will have to handle this correctly directly.
126if ($anchor && isset($SESSION->wantsurl) && strpos($SESSION->wantsurl, '#') === false) {
127 $wantsurl = new moodle_url($SESSION->wantsurl);
128 $wantsurl->set_anchor(substr($anchor, 1));
129 $SESSION->wantsurl = $wantsurl->out();
130}
131
a718d872 132/// Check if the user has actually submitted login data to us
133
8a8f1c7c 134if ($frm and isset($frm->username)) { // Login WITH cookies
792197b0 135
2f1e464a 136 $frm->username = trim(core_text::strtolower($frm->username));
cf5560fb 137
79604225 138 if (is_enabled_auth('none') ) {
ac9768fc 139 if ($frm->username !== core_user::clean_field($frm->username, 'username')) {
50256f9c 140 $errormsg = get_string('username').': '.get_string("invalidusername");
8570cff0 141 $errorcode = 2;
8570cff0 142 $user = null;
05b18caf 143 }
8570cff0 144 }
05b18caf 145
8570cff0 146 if ($user) {
667f564b 147 // The auth plugin has already provided the user via the loginpage_hook() called above.
8570cff0 148 } else if (($frm->username == 'guest') and empty($CFG->guestloginbutton)) {
149 $user = false; /// Can't log in as guest if guest button is disabled
150 $frm = false;
151 } else {
152 if (empty($errormsg)) {
e4a97a7a 153 $logintoken = isset($frm->logintoken) ? $frm->logintoken : '';
6dfe4283 154 $user = authenticate_user_login($frm->username, $frm->password, false, $errorcode, $logintoken);
cf5560fb 155 }
8570cff0 156 }
e58269e4
EL
157
158 // Intercept 'restored' users to provide them with info & reset password
159 if (!$user and $frm and is_restored_user($frm->username)) {
160 $PAGE->set_title(get_string('restoredaccount'));
161 $PAGE->set_heading($site->fullname);
162 echo $OUTPUT->header();
163 echo $OUTPUT->heading(get_string('restoredaccount'));
164 echo $OUTPUT->box(get_string('restoredaccountinfo'), 'generalbox boxaligncenter');
165 require_once('restored_password_form.php'); // Use our "supplanter" login_forgot_password_form. MDL-20846
166 $form = new login_forgot_password_form('forgot_password.php', array('username' => $frm->username));
167 $form->display();
168 echo $OUTPUT->footer();
169 die;
170 }
171
8570cff0 172 if ($user) {
a718d872 173
8570cff0 174 // language setup
b3df1764 175 if (isguestuser($user)) {
8570cff0 176 // no predefined language for guests - use existing session or default site lang
177 unset($user->lang);
18ceee5c 178
8570cff0 179 } else if (!empty($user->lang)) {
180 // unset previous session language - use user preference instead
181 unset($SESSION->lang);
182 }
18ceee5c 183
8570cff0 184 if (empty($user->confirmed)) { // This account was never confirmed
185 $PAGE->set_title(get_string("mustconfirm"));
e58269e4 186 $PAGE->set_heading($site->fullname);
8570cff0 187 echo $OUTPUT->header();
188 echo $OUTPUT->heading(get_string("mustconfirm"));
08c69a14
MN
189 if ($resendconfirmemail) {
190 if (!send_confirmation_email($user)) {
191 echo $OUTPUT->notification(get_string('emailconfirmsentfailure'), \core\output\notification::NOTIFY_ERROR);
192 } else {
193 echo $OUTPUT->notification(get_string('emailconfirmsentsuccess'), \core\output\notification::NOTIFY_SUCCESS);
194 }
195 }
7455b741 196 echo $OUTPUT->box(get_string("emailconfirmsent", "", s($user->email)), "generalbox boxaligncenter");
08c69a14
MN
197 $resendconfirmurl = new moodle_url('/login/index.php',
198 [
199 'username' => $frm->username,
200 'password' => $frm->password,
c39bc627
MG
201 'resendconfirmemail' => true,
202 'logintoken' => \core\session\manager::get_login_token()
08c69a14
MN
203 ]
204 );
205 echo $OUTPUT->single_button($resendconfirmurl, get_string('emailconfirmationresend'));
8570cff0 206 echo $OUTPUT->footer();
207 die;
208 }
c21c671d 209
8570cff0 210 /// Let's get them all set up.
0342fc36
PS
211 complete_user_login($user);
212
89e9321f
PS
213 \core\session\manager::apply_concurrent_login_limit($user->id, session_id());
214
0342fc36
PS
215 // sets the username cookie
216 if (!empty($CFG->nolastloggedin)) {
217 // do not store last logged in user in cookie
218 // auth plugins can temporarily override this from loginpage_hook()
219 // do not save $CFG->nolastloggedin in database!
220
221 } else if (empty($CFG->rememberusername) or ($CFG->rememberusername == 2 and empty($frm->rememberusername))) {
222 // no permanent cookies, delete old one if exists
223 set_moodle_cookie('');
224
225 } else {
226 set_moodle_cookie($USER->username);
227 }
e06f15ae 228
2f0dd8d5 229 $urltogo = core_login_get_return_url();
089b19f6 230
8570cff0 231 /// check if user password has expired
232 /// Currently supported only for ldap-authentication module
233 $userauth = get_auth_plugin($USER->auth);
7a89772c 234 if (!isguestuser() and !empty($userauth->config->expiration) and $userauth->config->expiration == 1) {
44565f5c 235 $externalchangepassword = false;
8570cff0 236 if ($userauth->can_change_password()) {
237 $passwordchangeurl = $userauth->change_password_url();
99f9f85f 238 if (!$passwordchangeurl) {
672f4836 239 $passwordchangeurl = $CFG->wwwroot.'/login/change_password.php';
44565f5c
DW
240 } else {
241 $externalchangepassword = true;
e6d4c2f8 242 }
8570cff0 243 } else {
672f4836 244 $passwordchangeurl = $CFG->wwwroot.'/login/change_password.php';
8570cff0 245 }
246 $days2expire = $userauth->password_expire($USER->username);
247 $PAGE->set_title("$site->fullname: $loginsite");
248 $PAGE->set_heading("$site->fullname");
8570cff0 249 if (intval($days2expire) > 0 && intval($days2expire) < intval($userauth->config->expiration_warning)) {
250 echo $OUTPUT->header();
251 echo $OUTPUT->confirm(get_string('auth_passwordwillexpire', 'auth', $days2expire), $passwordchangeurl, $urltogo);
252 echo $OUTPUT->footer();
253 exit;
254 } elseif (intval($days2expire) < 0 ) {
44565f5c
DW
255 if ($externalchangepassword) {
256 // We end the session if the change password form is external. This prevents access to the site
257 // until the password is correctly changed.
258 require_logout();
259 } else {
260 // If we use the standard change password form, this user preference will be reset when the password
261 // is changed. Until then it will prevent access to the site.
262 set_user_preference('auth_forcepasswordchange', 1, $USER);
263 }
8570cff0 264 echo $OUTPUT->header();
265 echo $OUTPUT->confirm(get_string('auth_passwordisexpired', 'auth'), $passwordchangeurl, $urltogo);
266 echo $OUTPUT->footer();
267 exit;
089b19f6 268 }
8570cff0 269 }
089b19f6 270
17ccd3aa
PS
271 // Discard any errors before the last redirect.
272 unset($SESSION->loginerrormsg);
273
8a8f1c7c
PS
274 // test the session actually works by redirecting to self
275 $SESSION->wantsurl = $urltogo;
276 redirect(new moodle_url(get_login_url(), array('testsession'=>$USER->id)));
f3d3f3e8 277
8570cff0 278 } else {
279 if (empty($errormsg)) {
65d7932c
CF
280 if ($errorcode == AUTH_LOGIN_UNAUTHORISED) {
281 $errormsg = get_string("unauthorisedlogin", "", $frm->username);
282 } else {
283 $errormsg = get_string("invalidlogin");
284 $errorcode = 3;
285 }
8570cff0 286 }
f9903ed0 287 }
8570cff0 288}
8223d271 289
4acffa49 290/// Detect problems with timedout sessions
8570cff0 291if ($session_has_timed_out and !data_submitted()) {
292 $errormsg = get_string('sessionerroruser', 'error');
293 $errorcode = 4;
294}
d9969553 295
296/// First, let's remember where the user was trying to get to before they got here
9c9f7d77 297
8570cff0 298if (empty($SESSION->wantsurl)) {
dcee0b94
SL
299 $SESSION->wantsurl = null;
300 $referer = get_local_referer(false);
301 if ($referer &&
302 $referer != $CFG->wwwroot &&
303 $referer != $CFG->wwwroot . '/' &&
672f4836
JO
304 $referer != $CFG->wwwroot . '/login/' &&
305 strpos($referer, $CFG->wwwroot . '/login/?') !== 0 &&
306 strpos($referer, $CFG->wwwroot . '/login/index.php') !== 0) { // There might be some extra params such as ?lang=.
dcee0b94
SL
307 $SESSION->wantsurl = $referer;
308 }
8570cff0 309}
792197b0 310
4acffa49 311/// Redirect to alternative login URL if needed
8570cff0 312if (!empty($CFG->alternateloginurl)) {
234e1449 313 $loginurl = new moodle_url($CFG->alternateloginurl);
4acffa49 314
234e1449
RT
315 $loginurlstr = $loginurl->out(false);
316
317 if (strpos($SESSION->wantsurl, $loginurlstr) === 0) {
318 // We do not want to return to alternate url.
319 $SESSION->wantsurl = null;
792197b0 320 }
f3d3f3e8 321
234e1449 322 // If error code then add that to url.
8570cff0 323 if ($errorcode) {
234e1449 324 $loginurl->param('errorcode', $errorcode);
9c9f7d77 325 }
f3d3f3e8 326
234e1449 327 redirect($loginurl->out(false));
8570cff0 328}
3fe6b721 329
8570cff0 330/// Generate the login page with forms
d9969553 331
b85b25eb
PS
332if (!isset($frm) or !is_object($frm)) {
333 $frm = new stdClass();
334}
335
8570cff0 336if (empty($frm->username) && $authsequence[0] != 'shibboleth') { // See bug 5184
337 if (!empty($_GET["username"])) {
ac9768fc 338 // we do not want data from _POST here
78fcdb5f 339 $frm->username = clean_param($_GET["username"], PARAM_RAW); // we do not want data from _POST here
8570cff0 340 } else {
0342fc36 341 $frm->username = get_moodle_cookie();
8570cff0 342 }
f9903ed0 343
8570cff0 344 $frm->password = "";
345}
346
17ccd3aa
PS
347if (!empty($SESSION->loginerrormsg)) {
348 // We had some errors before redirect, show them now.
349 $errormsg = $SESSION->loginerrormsg;
350 unset($SESSION->loginerrormsg);
351
352} else if ($testsession) {
353 // No need to redirect here.
354 unset($SESSION->loginerrormsg);
355
356} else if ($errormsg or !empty($frm->password)) {
357 // We must redirect after every password submission.
358 if ($errormsg) {
359 $SESSION->loginerrormsg = $errormsg;
360 }
7eb50b32 361 redirect(new moodle_url('/login/index.php'));
17ccd3aa
PS
362}
363
8570cff0 364$PAGE->set_title("$site->fullname: $loginsite");
365$PAGE->set_heading("$site->fullname");
8570cff0 366
367echo $OUTPUT->header();
e81fb5ef
PS
368
369if (isloggedin() and !isguestuser()) {
370 // prevent logging when already logged in, we do not want them to relogin by accident because sesskey would be changed
371 echo $OUTPUT->box_start();
7eb50b32 372 $logout = new single_button(new moodle_url('/login/logout.php', array('sesskey'=>sesskey(),'loginpage'=>1)), get_string('logout'), 'post');
672f4836 373 $continue = new single_button(new moodle_url('/'), get_string('cancel'), 'get');
e81fb5ef
PS
374 echo $OUTPUT->confirm(get_string('alreadyloggedin', 'error', fullname($USER)), $logout, $continue);
375 echo $OUTPUT->box_end();
376} else {
13075628 377 $loginform = new \core_auth\output\login($authsequence, $frm->username);
1fe8e35f
FM
378 $loginform->set_error($errormsg);
379 echo $OUTPUT->render($loginform);
e81fb5ef
PS
380}
381
6c3ef410 382echo $OUTPUT->footer();