xref: /plugin/authdjango/auth.php (revision 1e8dcca0d9d2cea8d6afede29685d62a7ebf1993)
1<?php
2/**
3 * django auth backend
4 *
5 * @author    Andreas Gohr <andi@splitbrain.org>
6 * @author    Michael Luggen <michael.luggen at unifr.ch>
7 * @author    Robert Czechowski <zgtm at zgtm.de>
8 */
9
10define('DOKU_AUTH', dirname(__FILE__));
11define('AUTH_USERFILE',DOKU_CONF.'users.auth.php');
12
13class auth_plugin_authdjango extends DokuWiki_Auth_Plugin  {
14
15    var $dbh = null; // db handle
16
17    /**
18     * Constructor.
19     *
20     * Sets additional capabilities and config strings
21     * @author    Michael Luggen <michael.luggen at rhone.ch>
22     * @author    Robert Czechowski <zgtm at zgtm.de>
23     */
24    public function __construct()
25    {
26        parent::__construct();
27
28        global $config_cascade;
29        global $dbh;
30
31        $this->cando['external'] = true;
32        $this->cando['getGroups'] = true;
33
34        if (!empty($this->getConf('logoff_uri'))) {
35            $this->cando['logout'] = true;
36        }
37
38        try {
39            // Connecting, selecting database
40            if ($this->getConf('protocol') == 'sqlite') {
41                $this->dbh = new PDO('sqlite:' . $this->getConf('server'));
42            }
43            else {
44                $this->dbh = new PDO($this->getConf('protocol') . ':host=' . $this->getConf('server') . ';dbname=' . $this->getConf('db'), $this->getConf('user'), $this->getConf('password'));
45            }
46        } catch (PDOException $e) {
47            msg("Can not connect to database!", -1);
48            dbg($e);
49            $this->success = false;
50        }
51        $this->success = true;
52    }
53
54    function trustExternal($user,$pass,$sticky=false){
55        global $USERINFO;
56        global $conf;
57        global $dbh;
58
59        $sticky ? $sticky = true : $sticky = false; //sanity check
60
61        /**
62         * Just checks against the django sessionid variable,
63         * gets user info from django-database
64         */
65
66        if (isset($_COOKIE['sessionid']) && $this->dbh) {
67
68            $s_id =  $_COOKIE['sessionid'];
69
70            // Look the cookie up in the db
71            $query = 'SELECT session_data FROM django_session WHERE session_key=' . $this->dbh->quote($s_id) . ' LIMIT 1;';
72            $result = $this->dbh->query($query) or die('Query failed1: ' . $this->dbh->errorInfo());
73            $ar = $result->fetch(PDO::FETCH_ASSOC);
74            $session_data = $ar['session_data'];
75
76            // TODO: $session_data can now be empty if the session does not exist in database, handle correctly instead of just dying
77            if (strlen($session_data) == 0) {
78                return false;
79            }
80
81            $compressed = false;
82
83            if (str_contains($session_data, ":")) {
84                // New django session encoding since django 4
85                if ($session_data[0] == '.') {
86                    $compressed = true;
87                    $session_data = substr($session_data, 1);
88                }
89
90                $session_json = base64_decode(strtr(preg_split('/:/', $session_data, 2)[0], "-_", "+/"), true);
91
92                if ($compressed) {
93                       $session_json = zlib_decode($session_json);
94                }
95
96            } else {
97                // Old django session enconding until django 3
98                // Decoding the session data:
99
100                $session_json = preg_split('/:/', base64_decode($session_data), 2)[1];
101            }
102            $userid = json_decode($session_json, true)['_auth_user_id'];
103            $query2 = 'SELECT username, first_name, last_name, email is_superuser, is_staff FROM auth_user WHERE id=' . $this->dbh->quote($userid) . ' LIMIT 1;';
104
105            $result2 = $this->dbh->query($query2) or die('Query failed2: ' . print_r($this->dbh->errorInfo()));
106            $user = $result2->fetch(PDO::FETCH_ASSOC);
107
108            $username =  $user['username'];
109            $userfullname = $user['first_name'] . " " . $user['last_name'];
110            $useremail = $user['email'];
111
112            // okay we're logged in - set the globals
113            $groups = $this->_getUserGroups($username);
114
115            $USERINFO['name'] = $username;
116            $USERINFO['pass'] = '';
117            $USERINFO['mail'] = $useremail;
118
119            if (($user['is_superuser'] && $this->getConf('admin_admin') == 1)
120                || ($user['is_staff'] && $this->getConf('staff_admin') == 1))
121            {
122                $groups[] = 'admin';
123            }
124            $USERINFO['grps'] = $groups;
125
126            $_SERVER['REMOTE_USER'] = $username;
127
128            $_SESSION[DOKU_COOKIE]['auth']['user'] = $username;
129            $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
130
131            return true;
132        }
133        return false;
134    }
135
136    function _getUserGroups($user){
137        $query = 'SELECT auth_group.name FROM auth_user, auth_user_groups, auth_group where auth_user.username = ' . $this->dbh->quote($user) . ' AND auth_user.id = auth_user_groups.user_id AND auth_user_groups.group_id = auth_group.id;';
138
139        $result = $this->dbh->query($query) or die('Query failed3: ' . $this->dbh->errorInfo());
140
141        $groups = [];
142        foreach ($result as $row) {
143            $groups[] = $row[0];
144        };
145
146        if (!in_array("user", $groups)) {
147            $groups[] = "user";
148        }
149
150        return $groups;
151    }
152
153    function retrieveGroups($start=0,$limit=0){
154        $query = 'SELECT auth_group.name FROM auth_group';
155
156        $result = $this->dbh->query($query) or die('Query failed4: ' . $this->dbh->errorInfo());
157
158        $groups = [];
159        foreach ($result as $row) {
160            $groups[] = $row[0];
161        };
162
163        if (!in_array("user", $groups)) {
164            $groups[] = "user";
165        }
166
167        if (!in_array("admin", $groups)) {
168            $groups[] = "admin";
169        }
170
171        return $groups;
172    }
173
174    function logOff() {
175        header("Location: " . $this->getConf('logoff_uri'));
176        die();
177    }
178
179
180    function __destruct() {
181        $this->dbh = null;
182    }
183}
184