summaryrefslogtreecommitdiffstats
path: root/lib/SimpleSAML/Utils/Auth.php
blob: 68a72129534056d9a4131728ccf18036c646a7e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
namespace SimpleSAML\Utils;

use SimpleSAML\Module;

/**
 * Auth-related utility methods.
 *
 * @package SimpleSAMLphp
 */
class Auth
{

    /**
     * Retrieve a admin login URL.
     *
     * @param string|NULL $returnTo The URL the user should arrive on after admin authentication. Defaults to null.
     *
     * @return string A URL which can be used for admin authentication.
     * @throws \InvalidArgumentException If $returnTo is neither a string nor null.
     */
    public static function getAdminLoginURL($returnTo = null)
    {
        if (!(is_string($returnTo) || is_null($returnTo))) {
            throw new \InvalidArgumentException('Invalid input parameters.');
        }

        if ($returnTo === null) {
            $returnTo = HTTP::getSelfURL();
        }

        return Module::getModuleURL('core/login-admin.php', array('ReturnTo' => $returnTo));
    }

    /**
     * Check whether the current user is admin.
     *
     * @return boolean True if the current user is an admin user, false otherwise.
     *
     * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
     */
    public static function isAdmin()
    {
        $session = \SimpleSAML_Session::getSessionFromRequest();
        return $session->isValid('admin') || $session->isValid('login-admin');
    }

    /**
     * Require admin access to the current page.
     *
     * This is a helper function for limiting a page to those with administrative access. It will redirect the user to
     * a login page if the current user doesn't have admin access.
     *
     * @return void This function will only return if the user is admin.
     * @throws \SimpleSAML_Error_Exception If no "admin" authentication source was configured.
     *
     * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
     * @author Jaime Perez, UNINETT AS <jaime.perez@uninett.no>
     */
    public static function requireAdmin()
    {
        if (self::isAdmin()) {
            return;
        }

        // not authenticated as admin user, start authentication
        if (\SimpleSAML_Auth_Source::getById('admin') !== null) {
            $as = new \SimpleSAML_Auth_Simple('admin');
            $as->login();
        } else {
            throw new \SimpleSAML_Error_Exception(
                'Cannot find "admin" auth source, and admin privileges are required.'
            );
        }
    }
}