summaryrefslogtreecommitdiff
path: root/lib/Kolab/DAV/Auth/HTTPBasic.php
blob: f152cc825bd36d26d2db8dd8dc9c8e65c725fdff (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
<?php

/**
 * SabreDAV Auth Backend implementation for Kolab.
 *
 * @author Thomas Bruederli <bruederli@kolabsys.com>
 *
 * Copyright (C) 2013, Kolab Systems AG <contact@kolabsys.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

namespace Kolab\DAV\Auth;

use \rcube;
use \rcube_imap_generic;
use \rcube_user;
use \rcube_utils;
use Sabre\DAV;

/**
 *
 */
class HTTPBasic extends DAV\Auth\Backend\AbstractBasic
{
    // Make the current user name available to all classes
    public static $current_user = null;
    public static $current_pass = null;

    /**
     * Validates a username and password
     *
     * This method should return true or false depending on if login
     * succeeded.
     *
     * @param string $username
     * @param string $password
     * @return bool
     */
    protected function validateUserPass($username, $password)
    {
        $rcube = rcube::get_instance();
        $host  = $this->_select_host($username);

        // use shared cache for kolab_auth plugin result (username canonification)
        $cache     = $rcube->get_cache_shared('kolabdav_auth');
        $cache_key = sha1($username . '::' . $host);

        if (!$cache || !($auth = $cache->get($cache_key))) {
            $auth = $rcube->plugins->exec_hook('authenticate', array(
                'host'  => $host,
                'user'  => $username,
                'pass'  => $password,
            ));

            if ($cache && !$auth['abort']) {
                $cache->set($cache_key, array(
                    'user'  => $auth['user'],
                    'host'  => $auth['host'],
                ));
            }

            // LDAP server failure... send 503 error
            if ($auth['kolab_ldap_error']) {
                throw new ServiceUnavailable('The service is temporarily unavailable (LDAP failure)');
            }
        }
        else {
            $auth['pass'] = $password;
        }

        // authenticate user against the IMAP server
        $user_id = $auth['abort'] ? 0 : $this->_login($auth['user'], $auth['pass'], $auth['host'], $error);

        if ($user_id) {
            self::$current_user = $auth['user'];
            self::$current_pass = $auth['pass'];

            return true;
        }

        // IMAP server failure... send 503 error
        if ($error == rcube_imap_generic::ERROR_BAD) {
            throw new ServiceUnavailable('The service is temporarily unavailable (Storage failure)');
        }

        return false;
    }

    /**
     * Returns information about the currently logged in username.
     *
     * If nobody is currently logged in, this method should return null.
     *
     * @return string|null
     */
    public function getCurrentUser()
    {
        // return the canonic user name
        return self::$current_user;
    }

    /**
     * Storage host selection
     */
    protected function _select_host($username)
    {
        // Get IMAP host
        $rcube = rcube::get_instance();
        $host  = $rcube->config->get('default_host', 'localhost');

        if (is_array($host)) {
            list($user, $domain) = explode('@', $username);

            // try to select host by mail domain
            if (!empty($domain)) {
                foreach ($host as $storage_host => $mail_domains) {
                    if (is_array($mail_domains) && in_array_nocase($domain, $mail_domains)) {
                        $host = $storage_host;
                        break;
                    }
                    else if (stripos($storage_host, $domain) !== false || stripos(strval($mail_domains), $domain) !== false) {
                        $host = is_numeric($storage_host) ? $mail_domains : $storage_host;
                        break;
                    }
                }
            }

            // take the first entry if $host is not found
            if (is_array($host)) {
                list($key, $val) = each($default_host);
                $host = is_numeric($key) ? $val : $key;
            }
        }

        return rcube_utils::parse_host($host);
    }

    /**
     * Authenticates a user in IMAP and returns Roundcube user ID.
     */
    protected function _login($username, $password, $host, &$error = null)
    {
        if (empty($username)) {
            return null;
        }

        $rcube        = rcube::get_instance();
        $storage      = $rcube->get_storage();
        $login_lc     = $rcube->config->get('login_lc');
        $default_port = $rcube->config->get('default_port', 143);

        // parse $host
        $a_host = parse_url($host);
        if ($a_host['host']) {
            $host = $a_host['host'];
            $ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
            if (!empty($a_host['port'])) {
                $port = $a_host['port'];
            }
            else if ($ssl && $ssl != 'tls' && (!$default_port || $default_port == 143)) {
                $port = 993;
            }
        }

        if (!$port) {
            $port = $default_port;
        }

        // Convert username to lowercase. If storage backend
        // is case-insensitive we need to store always the same username
        if ($login_lc) {
            if ($login_lc == 2 || $login_lc === true) {
                $username = mb_strtolower($username);
            }
            else if (strpos($username, '@')) {
                // lowercase domain name
                list($local, $domain) = explode('@', $username);
                $username = $local . '@' . mb_strtolower($domain);
            }
        }

        // Here we need IDNA ASCII
        // Only rcube_contacts class is using domain names in Unicode
        $host     = rcube_utils::idn_to_ascii($host);
        $username = rcube_utils::idn_to_ascii($username);

        // user already registered?
        if ($user = rcube_user::query($username, $host)) {
            $username = $user->data['username'];
        }

        // authenticate user in IMAP
        if (!$storage->connect($host, $username, $password, $port, $ssl)) {
            $error = $storage->get_error_code();
            return null;
        }

        // No user in database, but IMAP auth works
        if (!is_object($user)) {
            if ($rcube->config->get('auto_create_user')) {
                // create a new user record
                $user = rcube_user::create($username, $host);

                if (!$user) {
                    rcube::raise_error(array(
                        'code' => 620, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__,
                        'message' => "Failed to create a user record",
                    ), true, false);
                    return null;
                }
            }
            else {
                rcube::raise_error(array(
                    'code' => 620, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__,
                    'message' => "Access denied for new user $username. 'auto_create_user' is disabled",
                ), true, false);
                return null;
            }
        }

        // overwrite config with user preferences
        $rcube->user = $user;
        $rcube->config->set_user_prefs((array)$rcube->user->get_prefs());
        $rcube->password = $password;

        setlocale(LC_ALL, 'en_US.utf8', 'en_US.UTF-8');

        return $user->ID;
    }
}