index.php 23.9 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

if (!extension_loaded('mcrypt')) {
44
    throw new AuthInstanceException(get_string_php_version('errornomcrypt','auth.saml'));
45
46
}

47
$sp = 'default-sp';
48

49
PluginAuthSaml::init_simplesamlphp();
50

51
52
53
54
55
56
57
// 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'));
}
58
59

// do we have a logout request?
60
if (param_variable("logout", false)) {
61
    // logout the saml session
Piers Harding's avatar
Piers Harding committed
62
    $as = new SimpleSAML_Auth_Simple($sp);
63
64
    $as->logout($CFG->wwwroot);
}
65
66

// what is the session like?
67
68
$saml_session = SimpleSAML_Session::getSession();
$valid_saml_session = $saml_session ? $saml_session->isValid($sp) : false;
69

70
// figure out what the returnto URL should be
71
$wantsurl = param_variable("wantsurl", false);
72
73
74
75
if (!$wantsurl) {
    if (isset($_SESSION['wantsurl'])) {
        $wantsurl = $_SESSION['wantsurl'];
    }
76
    else if (! $saml_session || ! $valid_saml_session) {
77
78
79
80
81
        $wantsurl = array_key_exists('HTTP_REFERER',$_SERVER) ? $_SERVER['HTTP_REFERER'] : $CFG->wwwroot;
    }
    else {
        $wantsurl = $CFG->wwwroot;
    }
82
}
83
84
85
86
87
88
89
90
// 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);
91

92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
$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'));
        }
    }
117
118
}

119
120
121
122
// 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"));
123

124
// ensure that $_SESSION is cleared for simplesamlphp
125
if (isset($_SESSION['wantsurl'])) {
126
    unset($SESSION->wantsurl);
127
128
}

129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
$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);
146
147
148
149
150
151
152
153
154
155
// ***********************************************************************
// 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) {
156
    throw new UserNotFoundException(get_string('errorbadinstitution', 'auth.saml'));
157
158
}

159
160
161
// stash the existing logged in user - if we have one
$current_user = $USER;
$is_loggedin = $USER->is_logged_in();
162

163
164
165
166
167
168
169
// 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) {
170
    throw new UserNotFoundException(get_string('errnosamluser', 'auth.saml'));
171
172
173
174
175
}
catch (XmlrpcClientException $e) {
    throw new AccessDeniedException($e->getMessage());
}
catch (AuthInstanceException $e) {
176
    throw new AccessDeniedException(get_string('errormissinguserattributes1', 'auth.saml', get_config('sitename')));
177
178
}

179
180
181
182
183
184
// 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);
185
    }
186
187
188
189
190
    // sanity check the redirect - we don't want to loop
    if (preg_match('/\/auth\/saml\//', $wantsurl)) {
        $wantsurl = $CFG->wwwroot;
    }
    // must be within this domain
191
    if (!preg_match('/'.$_SERVER['HTTP_HOST'] . '/', $wantsurl)) {
192
193
        $wantsurl = $CFG->wwwroot;
    }
194
    @session_write_close();
195
    redirect($wantsurl);
196
197
}

198
199
200
// 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)) {
201
    throw new UserNotFoundException(get_string('errnosamluser', 'auth.saml'));
202
}
203

204
205
206
207
// 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];
208

209
210
211
212
213
214
215
216
217
218
219
220
221
// 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);
222

223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241

/**
 * 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();
242
    @session_write_close();
243
    redirect('/auth/saml/index.php');
244
}
245

246
247

/**
248
 * Find the connected authinstance for the organisation attached to this SAML account
249
 *
250
251
252
 * @param array $saml_attributes
 *
 * @return object authinstance record
253
 */
254
255
256
257
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();
258

259
    // find all the possible institutions/auth instances of type saml
260
    $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'"));
261
    foreach ($instances as $row) {
262
        $institutions[]= $row->instance . ':' . $row->institution . ':' . $row->value;
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
        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) {
280
                    if (preg_match('/' . trim($institution_value) . '/', $attr)) {
281
282
                        $instance = $row;
                        break;
283
284
285
286
                    }
                }
            }
            else {
287
288
289
290
291
292
                foreach ($saml_attributes[$row->value] as $attr) {
                    if ($attr == $institution_value) {
                        $instance = $row;
                        break;
                    }
                }
293
294
295
            }
        }
    }
296
297
298
299
    return $instance;
}


300
301
302
303
304
305
306
307
/**
 * 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) {
308

309
310
    $idps = array();
    $lang = current_language();
311
312
    $lang = explode('.', $lang);
    $lang = strtolower(array_shift($lang));
313
    $haslogos = false;
314
    foreach ($list as $entityid => $value) {
315
        $desc = $name = $entityid;
316
317
318
        if (isset($value['description'][$lang])) {
            $desc = $value['description'][$lang];
        }
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
        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);
339
340
    }

341
342
343
    usort($idps, function($a, $b) {
        return $a['name'] > $b['name'];
    });
344
345
346
347
348
349
350
351
    $idps = array(
        'count'   => count($idps),
        'limit'   => count($idps),
        'offset'  => 1,
        'data'    => $idps,
    );

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

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

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


383
384
385
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
/**
 * 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
    );
415
    $form = pieform_instance($form);
416
    define('TITLE', get_string('link', 'auth.saml'));
417
418
419
420
421
422
423
424
425
426
427
428
429
    $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) {
430
    define('TITLE', get_string('logintolink', 'auth.saml', get_config('sitename')));
431
432
    $smarty = smarty(array(), array(), array(), array('pagehelp' => false, 'sidebars' => false));
    $smarty->assign('pagedescriptionhtml', get_string('logintolinkdesc', 'auth.saml', $remoteuser, get_config('sitename')));
433
    $smarty->assign('form', '<div id="loginform_container"><noscript><p>{str tag="javascriptnotenabled"}</p></noscript>' . saml_auth_generate_login_form());
434
435
436
    $smarty->assign('LOGINPAGE', true);
    $smarty->display('form.tpl');
    exit;
437
}
438
439
440
441
442
443
444
445
446
447
448
449
450


/**
 * 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
451
        $registerlink = '<a class="btn btn-primary btn-xs" href="' . get_config('wwwroot') . 'register.php">' . get_string('register') . '</a>';
452
453
454
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
    }
    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(
484
                'class' => 'btn-primary btn-block',
485
486
487
488
                'type'  => 'submit',
                'value' => get_string('login')
            ),
            'register' => array(
Naomi Guyer's avatar
Naomi Guyer committed
489
490
                'value' => '<div id="login-helplinks" class="panel-footer"><small>' . $registerlink
                    . '<a href="' . get_config('wwwroot') . 'forgotpass.php">' . get_string('lostusernamepassword') . '</a></small></div>'
491
492
            ),
            'loginsaml' => array(
493
                'value' => ((count_records('auth_instance', 'authname', 'saml') == 0) ? '' : '<a href="' . get_config('wwwroot') . 'auth/saml/index.php">' . get_string('login', 'auth.saml') . '</a>')
494
495
496
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
            ),
        )
    )));

    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
536
    if (get_config('siteclosedforupgrade')) {
537
538
539
540
        global $SESSION;
        $SESSION->add_error_msg(get_string('siteclosedlogindisabled', 'mahara', get_config('wwwroot') . 'admin/upgrade.php'), false);
        return false;
    }
541
    if (get_config('siteclosedbyadmin')) {
542
543
544
545
546
547
548
549
550
        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();

551
    // all other candidate auth_instances
552
553
    $sql = 'SELECT ai.* from {auth_instance} ai INNER JOIN {auth_remote_user} aru
                ON ai.id = aru.authinstance
554
                WHERE ai.active = 1 AND ai.authname NOT IN(\'saml\', \'xmlrpc\', \'none\') AND aru.localusr = ?';
555
556
557
558
559
560
561
    $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
562
    $authinstance = get_record('auth_instance', 'institution', 'mahara', 'authname', 'internal', 'active', 1);
563
564
565
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
    $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'));
616
            redirect('/auth/saml/index.php');
617
618
619
620
621
        }

    }
    catch (AuthUnknownUserException $e) {
        $SESSION->add_error_msg(get_string('loginfailed'));
622
        redirect('/auth/saml/index.php');
623
624
    }

625
    auth_check_admin_section();
626
627
628
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

    // 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
659
    redirect('/auth/saml/index.php');
660
}