index.php 24.3 KB
Newer Older
1
<?php
2
3
4
5
6
/**
 *
 * @package    mahara
 * @subpackage auth-saml
 * @author     Piers Harding <piers@catalyst.net.nz>
7
8
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 *
 * This file incorporates work covered by the following copyright and
 * permission notice:
 *
 *    Moodle - Modular Object-Oriented Dynamic Learning Environment
 *             http://moodle.com
 *
 *    Copyright (C) 2001-3001 Martin Dougiamas        http://dougiamas.com
 *
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details:
 *
 *             http://www.gnu.org/copyleft/gpl.html
 */

define('INTERNAL', 1);
define('PUBLIC', 1);
33
global $CFG, $USER, $SESSION, $idp_entityid;
34
35
36
require(dirname(dirname(dirname(__FILE__))) . '/init.php');
require_once(get_config('docroot') .'auth/saml/lib.php');
require_once(get_config('libroot') .'institution.php');
37

38
39
40
41
// check that the plugin is active
if (get_field('auth_installed', 'active', 'name', 'saml') != 1) {
    redirect();
}
42
43
44
45
46

if (!extension_loaded('mcrypt')) {
    throw new AuthInstanceException(get_string('errornomcrypt','auth.saml'));
}

47
$sp = 'default-sp';
48

49
if (!file_exists(get_config('docroot') . 'auth/saml/extlib/simplesamlphp/vendor/autoload.php')) {
50
    throw new AuthInstanceException(get_string('errorbadlib', 'auth.saml', get_config('docroot') . 'auth/saml/extlib/simplesamlphp/vendor/autoload.php'));
51
}
52
53
require_once(get_config('docroot') . 'auth/saml/extlib/simplesamlphp/vendor/autoload.php');
require_once(get_config('docroot') . 'auth/saml/extlib/_autoload.php');
54

55
SimpleSAML_Configuration::init(get_config('docroot') . 'auth/saml/config');
56

57
58
59
60
61
62
63
// Check the SimpleSAMLphp config is compatible
$saml_config = SimpleSAML_Configuration::getInstance();
$session_handler = $saml_config->getString('session.handler', false);
$store_type = $saml_config->getString('store.type', false);
if ($store_type == 'phpsession' || $session_handler == 'phpsession' || (empty($store_type) && empty($session_handler))) {
    throw new AuthInstanceException(get_string('errorbadssphp', 'auth.saml'));
}
64
65

// do we have a logout request?
66
if (param_variable("logout", false)) {
67
    // logout the saml session
Piers Harding's avatar
Piers Harding committed
68
    $as = new SimpleSAML_Auth_Simple($sp);
69
70
    $as->logout($CFG->wwwroot);
}
71
72

// what is the session like?
73
74
$saml_session = SimpleSAML_Session::getSession();
$valid_saml_session = $saml_session ? $saml_session->isValid($sp) : false;
75

76
// figure out what the returnto URL should be
77
$wantsurl = param_variable("wantsurl", false);
78
79
80
81
if (!$wantsurl) {
    if (isset($_SESSION['wantsurl'])) {
        $wantsurl = $_SESSION['wantsurl'];
    }
82
    else if (! $saml_session || ! $valid_saml_session) {
83
84
85
86
87
        $wantsurl = array_key_exists('HTTP_REFERER',$_SERVER) ? $_SERVER['HTTP_REFERER'] : $CFG->wwwroot;
    }
    else {
        $wantsurl = $CFG->wwwroot;
    }
88
}
89
90
91
92
93
94
95
96
// taken from Moodle clean_param - make sure the wantsurl is correctly formed
include_once('validateurlsyntax.php');
if (!validateUrlSyntax($wantsurl, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
    $wantsurl = $CFG->wwwroot;
}

// trim off any reference to login and stash
$SESSION->wantsurl = preg_replace('/\&login$/', '', $wantsurl);
97

98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
$as = new SimpleSAML_Auth_Simple($sp);
$idp_entityid = null;
if (! $as->isAuthenticated()) {
    if (param_variable("idpentityid", false)) {
        $idp_entityid = param_variable("idpentityid", false);
    }
    else {
        if (class_exists('PluginAuthSaml_IdPDisco')) {
            $discoHandler = new PluginAuthSaml_IdPDisco(array('saml20-idp-remote', 'shib13-idp-remote'), 'saml');
            $disco = $discoHandler->getTheIdPs();
            if (count($disco['list']) == 0) {
                throw new AuthInstanceException(get_string('errorbadssphpmetadata', 'auth.saml'));
            }
            else if (count($disco['list']) == 1) {
                $idp_entityid = array_shift($disco['list']);
                $idp_entityid = $idp_entityid["entityid"];
            }
            else {
                auth_saml_disco_screen($disco['list'], $disco['preferred']);
            }
        }
        else {
            throw new AuthInstanceException(get_string('errorbadssphpmetadata', 'auth.saml'));
        }
    }
123
124
}

125
126
127
128
// reinitialise config to pickup idp entityID
SimpleSAML_Configuration::init(get_config('docroot') . 'auth/saml/config');
$as = new SimpleSAML_Auth_Simple('default-sp');
$as->requireAuth(array('ReturnTo' => get_config('wwwroot') . "auth/saml/index.php"));
129

130
// ensure that $_SESSION is cleared for simplesamlphp
131
if (isset($_SESSION['wantsurl'])) {
132
    unset($SESSION->wantsurl);
133
134
}

135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
$saml_attributes = $as->getAttributes();

// now - let's continue with the session handling that would normally be done
// by Maharas init.php
// the main thin is that it sets the session cookie name back to what it should be
// session_name(get_config('cookieprefix') . 'mahara');
// and starts the session again

// ***********************************************************************
// copied from original init.php
// ***********************************************************************
// Only do authentication once we know the page theme, so that the login form
// can have the correct theming.
require_once(dirname(dirname(dirname(__FILE__))) . '/auth/lib.php');
$SESSION = Session::singleton();
$USER    = new LiveUser();
$THEME   = new Theme($USER);
152
153
154
155
156
157
158
159
160
161
// ***********************************************************************
// END of copied stuff from original init.php
// ***********************************************************************

// now start the hunt for the associated authinstance for the organisation attached to the saml_attributes
global $instance;
$instance = auth_saml_find_authinstance($saml_attributes);

// if we don't have an auth instance then this is a serious failure
if (!$instance) {
162
    throw new UserNotFoundException(get_string('errorbadinstitution', 'auth.saml'));
163
164
}

165
166
167
// stash the existing logged in user - if we have one
$current_user = $USER;
$is_loggedin = $USER->is_logged_in();
168

169
170
171
172
173
174
175
// check the instance and do a test login
$can_login = false;
try {
    $auth = new AuthSaml($instance->id);
    $can_login = $auth->request_user_authorise($saml_attributes);
}
catch (AccessDeniedException $e) {
176
    throw new UserNotFoundException(get_string('errnosamluser', 'auth.saml'));
177
178
179
180
181
}
catch (XmlrpcClientException $e) {
    throw new AccessDeniedException($e->getMessage());
}
catch (AuthInstanceException $e) {
182
    throw new AccessDeniedException(get_string('errormissinguserattributes1', 'auth.saml', get_config('sitename')));
183
184
}

185
186
187
188
189
190
// if we can login with SAML - then let them go
if ($can_login) {
    // they are logged in, so they dont need to be here
    if ($SESSION->get('wantsurl')) {
        $wantsurl = $SESSION->get('wantsurl');
        $SESSION->set('wantsurl', null);
191
    }
192
193
194
195
196
    // sanity check the redirect - we don't want to loop
    if (preg_match('/\/auth\/saml\//', $wantsurl)) {
        $wantsurl = $CFG->wwwroot;
    }
    // must be within this domain
197
    if (!preg_match('/'.$_SERVER['HTTP_HOST'] . '/', $wantsurl)) {
198
199
        $wantsurl = $CFG->wwwroot;
    }
200
    @session_write_close();
201
    redirect($wantsurl);
202
203
}

204
205
206
// are we configured to allow testing of local login and linking?
$loginlink = get_field('auth_instance_config', 'value', 'field', 'loginlink', 'instance', $instance->id);
if (empty($loginlink)) {
207
    throw new UserNotFoundException(get_string('errnosamluser', 'auth.saml'));
208
}
209

210
211
212
213
// used in the submit callback for auth_saml_loginlink_screen()
global $remoteuser;
$user_attribute = get_field('auth_instance_config', 'value', 'field', 'user_attribute', 'instance', $instance->id);
$remoteuser = $saml_attributes[$user_attribute][0];
214

215
216
217
218
219
220
221
222
223
224
225
226
227
// is the local account already logged in or can the SAML auth succeed - if not try to get
// them to log in local/manual
if (!$is_loggedin) {
    // cannot match user account - so offer them the login-link/register page
    // if we can't login locally, and cant login via SAML then we should offer to register - but this should probably appear on the local login page anyway
    auth_saml_login_screen($remoteuser);
}
else {
    // if we can login locally, but can't login with SAML then we offer to link the accounts SAML -> local one
    auth_saml_loginlink_screen($remoteuser, $current_user->username);
}

exit(0);
228

229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247

/**
 * callback for linking local account with remote SAML account
 *
 * @param Pieform $form
 * @param array $values
 */
function auth_saml_loginlink_submit(Pieform $form, $values) {
    global $USER, $instance, $remoteuser;

    // create the new account linking
    db_begin();
    delete_records('auth_remote_user', 'authinstance', $instance->id, 'localusr', $USER->id);
    insert_record('auth_remote_user', (object) array(
        'authinstance'   => $instance->id,
        'remoteusername' => $remoteuser,
        'localusr'       => $USER->id,
    ));
    db_commit();
248
    @session_write_close();
249
    redirect('/auth/saml/index.php');
250
}
251

252
253

/**
254
 * Find the connected authinstance for the organisation attached to this SAML account
255
 *
256
257
258
 * @param array $saml_attributes
 *
 * @return object authinstance record
259
 */
260
261
262
263
function auth_saml_find_authinstance($saml_attributes) {
// find the one (it should be only one) that has the right field, and the right field value for institution
    $instance = false;
    $institutions = array();
264

265
    // find all the possible institutions/auth instances of type saml
266
    $instances = recordset_to_array(get_recordset_sql("SELECT * FROM {auth_instance_config} aic, {auth_instance} ai WHERE ai.id = aic.instance AND ai.authname = 'saml' AND ai.active = 1 AND aic.field = 'institutionattribute'"));
267
    foreach ($instances as $row) {
268
        $institutions[]= $row->instance . ':' . $row->institution . ':' . $row->value;
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
        if (isset($saml_attributes[$row->value])) {
            // does this institution use a regex match against the institution check value?
            if ($configvalue = get_record('auth_instance_config', 'instance', $row->instance, 'field', 'institutionregex')) {
                $is_regex = (boolean) $configvalue->value;
            }
            else {
                $is_regex = false;
            }
            if ($configvalue = get_record('auth_instance_config', 'instance', $row->instance, 'field', 'institutionvalue')) {
                $institution_value = $configvalue->value;
            }
            else {
                $institution_value = $row->institution;
            }

            if ($is_regex) {
                foreach ($saml_attributes[$row->value] as $attr) {
286
                    if (preg_match('/' . trim($institution_value) . '/', $attr)) {
287
288
                        $instance = $row;
                        break;
289
290
291
292
                    }
                }
            }
            else {
293
294
295
296
297
298
                foreach ($saml_attributes[$row->value] as $attr) {
                    if ($attr == $institution_value) {
                        $instance = $row;
                        break;
                    }
                }
299
300
301
            }
        }
    }
302
303
304
305
    return $instance;
}


306
307
308
309
310
311
312
313
/**
 * present the IdP discovery screen if there are more than one
 * available - user selects ...
 *
 * @param string $list
 * @param string $preferred
*/
function auth_saml_disco_screen($list, $preferred) {
314

315
316
    $idps = array();
    $lang = current_language();
317
318
    $lang = explode('.', $lang);
    $lang = strtolower(array_shift($lang));
319
    $haslogos = false;
320
    foreach ($list as $entityid => $value) {
321
        $desc = $name = $entityid;
322
323
324
        if (isset($value['description'][$lang])) {
            $desc = $value['description'][$lang];
        }
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
        if (isset($value['name'][$lang])) {
            $name = $value['name'][$lang];
        }
        $idplogo = array();
        if (isset($value['UIInfo']) && isset($value['UIInfo']['Logo'])) {
            $haslogos = true;
            // Fetch logo from provider if given
            $logos = $value['UIInfo']['Logo'];
            foreach ($logos as $logo) {
                if ($logo['lang'] == $lang) {
                    $idplogo = $logo;
                    break;
                }
            }
            // None matching the lang wanted so use the first one
            if (empty($idplogo)) {
                $idplogo = $logos[0];
            }
        }
        $idps[]= array('idpentityid' => $entityid, 'name' => $name, 'description' => $desc, 'logo' => $idplogo);
345
346
347
348
349
350
351
352
353
354
    }

    $idps = array(
        'count'   => count($idps),
        'limit'   => count($idps),
        'offset'  => 1,
        'data'    => $idps,
    );

    $cols = array(
355
356
357
358
            'logo' => array('name' => get_string('logo', 'auth.saml'),
                            'template' => 'auth:saml:idplogo.tpl',
                            'class' => 'short',
                            'sort' => 'false'),
359
360
361
362
            'idpentityid' => array('name' => get_string('idpentityid', 'auth.saml'),
                                   'template' => 'auth:saml:idpentityid.tpl',
                                   'class' => 'col-sm-3',
                                   'sort' => false),
363
            'description' => array('name' => get_string('idpprovider','auth.saml'),
364
365
                                   'sort' => false),
    );
366
367
368
    if ($haslogos === false) {
        unset($cols['logo']);
    }
369
370

    $smarty = smarty_core();
371
    $smarty->assign('results', $idps);
372
373
374
    $smarty->assign('cols', $cols);
    $smarty->assign('pagedescriptionhtml', get_string('selectidp', 'auth.saml'));
    $idps = $smarty->fetch('auth:saml:idptable.tpl');
375

376
    $smarty = smarty(array(), array(), array(), array('pagehelp' => false, 'sidebars' => false));
377
    $smarty->assign('columns', $cols);
378
379
380
381
382
383
384
385
    $smarty->assign('idps', $idps);
    $smarty->assign('preferred', $preferred);
    $smarty->assign('PAGEHEADING', get_string('disco', 'auth.saml'));
    $smarty->display('auth:saml:disco.tpl');
    exit;
}


386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
/**
 * present the login-link screen where users are asked if they want to link
 * the current loggedin local account to the remote saml one
 *
 * @param string $remoteuser
 * @param string $currentuser
 */
function auth_saml_loginlink_screen($remoteuser, $currentuser) {
    $form = array(
        'name'           => 'loginlink',
        'renderer'       => 'div',
        'successcallback'  => 'auth_saml_loginlink_submit',
        'method'         => 'post',
        'plugintype'     => 'auth',
        'pluginname'     => 'saml',
        'elements'       => array(
                    'linklogins' => array(
                        'value' => '<div><b>' . get_string('linkaccounts', 'auth.saml', $remoteuser, $currentuser) . '</b></div><br/>'
                    ),
                    'submit' => array(
                        'type'  => 'submitcancel',
                        'value' => array(get_string('link','auth.saml'), get_string('cancel')),
                        'goto'  => get_config('wwwroot'),
                    ),
                    'link_submitted' => array(
                        'type'  => 'hidden',
                        'value' => 1
                    ),
                ),
        'dieaftersubmit' => false,
        'iscancellable'  => true
    );
418
    $form = pieform_instance($form);
419
    define('TITLE', get_string('link', 'auth.saml'));
420
421
422
423
424
425
426
427
428
429
430
431
432
    $smarty = smarty(array(), array(), array(), array('pagehelp' => false, 'sidebars' => false));
    $smarty->assign('form', $form->build());
    $smarty->display('form.tpl');
    exit;
}


/**
 * present the login screen for login-linking
 *
 * @param string $remoteuser
 */
function auth_saml_login_screen($remoteuser) {
433
    define('TITLE', get_string('logintolink', 'auth.saml', get_config('sitename')));
434
435
    $smarty = smarty(array(), array(), array(), array('pagehelp' => false, 'sidebars' => false));
    $smarty->assign('pagedescriptionhtml', get_string('logintolinkdesc', 'auth.saml', $remoteuser, get_config('sitename')));
436
    $smarty->assign('form', '<div id="loginform_container"><noscript><p>{str tag="javascriptnotenabled"}</p></noscript>' . saml_auth_generate_login_form());
437
438
439
    $smarty->assign('LOGINPAGE', true);
    $smarty->display('form.tpl');
    exit;
440
}
441
442
443
444
445
446
447
448
449
450
451
452
453


/**
 * Generates the login form specifically independent of the core Mahara one
 * we want a custom submit callback here - which PHP doesn't let you do via overloading (sigh)
 * so - the only thing that is different here is the form name and the successcallback, and submit = true
 *
 */
function saml_auth_generate_login_form() {
    if (!get_config('installed')) {
        return;
    }
    if (count_records('institution', 'registerallowed', 1, 'suspended', 0)) {
Naomi Guyer's avatar
Naomi Guyer committed
454
        $registerlink = '<a class="btn btn-primary btn-xs" href="' . get_config('wwwroot') . 'register.php">' . get_string('register') . '</a>';
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
    }
    else {
        $registerlink = '';
    }
    $loginform = get_login_form_js(pieform(array(
        'name'       => 'auth_saml_login',
        'renderer'   => 'div',
        'submit'     => true,
        'successcallback'  => 'auth_saml_login_submit',
        'plugintype' => 'auth',
        'pluginname' => 'internal',
        'autofocus'  => false,
        'elements'   => array(
            'login_username' => array(
                'type'        => 'text',
                'title'       => get_string('username') . ':',
                'description' => get_string('usernamedescription'),
                'defaultvalue' => (isset($_POST['login_username'])) ? $_POST['login_username'] : '',
                'rules' => array(
                    'required'    => true
                )
            ),
            'login_password' => array(
                'type'        => 'password',
                'title'       => get_string('password') . ':',
                'description' => get_string('passworddescription'),
                'defaultvalue'       => '',
                'rules' => array(
                    'required'    => true
                )
            ),
            'submit' => array(
487
                'class' => 'btn-primary btn-block',
488
489
490
491
                'type'  => 'submit',
                'value' => get_string('login')
            ),
            'register' => array(
Naomi Guyer's avatar
Naomi Guyer committed
492
493
                'value' => '<div id="login-helplinks" class="panel-footer"><small>' . $registerlink
                    . '<a href="' . get_config('wwwroot') . 'forgotpass.php">' . get_string('lostusernamepassword') . '</a></small></div>'
494
495
            ),
            'loginsaml' => array(
496
                'value' => ((count_records('auth_instance', 'authname', 'saml') == 0) ? '' : '<a href="' . get_config('wwwroot') . 'auth/saml/index.php">' . get_string('login', 'auth.saml') . '</a>')
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
            ),
        )
    )));

    return $loginform;
}


/**
 * Take a username and password and try to authenticate the
 * user
 *
 * Copied and modified from core LiveUser->login()
 *
 * @param  string $username
 * @param  string $password
 * @return bool
 */
function login_test_all_user_authinstance($username, $password) {
    global $USER;

    // do the normal user lookup
    $sql = 'SELECT
                *,
                ' . db_format_tsfield('expiry') . ',
                ' . db_format_tsfield('lastlogin') . ',
                ' . db_format_tsfield('lastlastlogin') . ',
                ' . db_format_tsfield('lastaccess') . ',
                ' . db_format_tsfield('suspendedctime') . ',
                ' . db_format_tsfield('ctime') . '
            FROM
                {usr}
            WHERE
                LOWER(username) = ?';
    $user = get_record_sql($sql, array(strtolower($username)));

    // throw out unknown users
    if ($user == false) {
        throw new AuthUnknownUserException("\"$username\" is not known");
    }

    // stop right here if the site is closed for any reason
539
    if (get_config('siteclosedforupgrade')) {
540
541
542
543
        global $SESSION;
        $SESSION->add_error_msg(get_string('siteclosedlogindisabled', 'mahara', get_config('wwwroot') . 'admin/upgrade.php'), false);
        return false;
    }
544
    if (get_config('siteclosedbyadmin')) {
545
546
547
548
549
550
551
552
553
        global $SESSION;
        $SESSION->add_error_msg(get_string('siteclosed'));
        return false;
    }

    // Build up a list of authinstance that can be tried for this user - typically
    // internal, or ldap - definitely NOT none, saml, or xmlrpc
    $instances = array();

554
    // all other candidate auth_instances
555
556
    $sql = 'SELECT ai.* from {auth_instance} ai INNER JOIN {auth_remote_user} aru
                ON ai.id = aru.authinstance
557
                WHERE ai.active = 1 AND ai.authname NOT IN(\'saml\', \'xmlrpc\', \'none\') AND aru.localusr = ?';
558
559
560
561
562
563
564
    $authinstances = get_records_sql_array($sql, array($user->id));
    foreach ($authinstances as $authinstance) {
        $instances[]= $authinstance->id;
    }

    // determine the internal authinstance ID associated with the base 'mahara'
    // 'no institution' - use this is a default fallback login attempt
565
    $authinstance = get_record('auth_instance', 'institution', 'mahara', 'authname', 'internal', 'active', 1);
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
    $instances[]= $authinstance->id;

    // test each auth_instance candidate associated with this user
    foreach ($instances as $authinstanceid) {
        $auth = AuthFactory::create($authinstanceid);
        // catch the AuthInstanceException that allows authentication plugins to
        // fail but pass onto the next possible plugin
        try {
            if ($auth->authenticate_user_account($user, $password)) {
                $USER->reanimate($user->id, $auth->instanceid);
                // Check for a suspended institution - should never be for 'mahara'
                $authinstance = get_record_sql('
                    SELECT i.suspended, i.displayname
                    FROM {institution} i JOIN {auth_instance} a ON a.institution = i.name
                    WHERE a.id = ?', array($authinstanceid));
                if ($authinstance->suspended) {
                    continue;
                }
                // we havea winner
                return true;
            }
        }
        catch (AuthInstanceException $e) {
            // auth fail - try the next one
            continue;
        }
    }
    // all fail
    return false;
}


/**
 * Called when the auth_saml_login form is submitted. Validates the user and password, and
 * if they are valid, starts a new session for the user.
 *
 * Copied and modified from core login_submit
 *
 * @param object $form   The Pieform form object
 * @param array  $values The submitted values
 */
function auth_saml_login_submit(Pieform $form, $values) {
    global $SESSION, $USER;

    $username      = trim($values['login_username']);
    $password      = $values['login_password'];
    $authenticated = false;
    $oldlastlogin  = 0;

    try {
        $authenticated = login_test_all_user_authinstance($username, $password);
        if (empty($authenticated)) {
            $SESSION->add_error_msg(get_string('loginfailed'));
619
            redirect('/auth/saml/index.php');
620
621
622
623
624
        }

    }
    catch (AuthUnknownUserException $e) {
        $SESSION->add_error_msg(get_string('loginfailed'));
625
        redirect('/auth/saml/index.php');
626
627
    }

628
    auth_check_admin_section();
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661

    // Check if the user's account has been deleted
    if ($USER->deleted) {
        $USER->logout();
        die_info(get_string('accountdeleted'));
    }

    // Check if the user's account has expired
    if ($USER->expiry > 0 && time() > $USER->expiry) {
        $USER->logout();
        die_info(get_string('accountexpired'));
    }

    // Check if the user's account has become inactive
    $inactivetime = get_config('defaultaccountinactiveexpire');
    if ($inactivetime && $oldlastlogin > 0
        && $oldlastlogin + $inactivetime < time()) {
        $USER->logout();
        die_info(get_string('accountinactive'));
    }

    // Check if the user's account has been suspended
    if ($USER->suspendedcusr) {
        $suspendedctime  = strftime(get_string('strftimedaydate'), $USER->suspendedctime);
        $suspendedreason = $USER->suspendedreason;
        $USER->logout();
        die_info(get_string('accountsuspended', 'mahara', $suspendedctime, $suspendedreason));
    }

    // User is allowed to log in
    auth_check_required_fields();

    // all happy - carry on now
662
    redirect('/auth/saml/index.php');
663
}