source: trunk/lib/Auth_File.inc.php @ 334

Last change on this file since 334 was 334, checked in by quinn, 16 years ago

Fixed lots of misplings. I'm so embarrassed! ;P

File size: 13.7 KB
Line 
1<?php
2/**
3 * Auth_File.inc.php
4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
5 *
6 * The Auth_File class provides a htpasswd file implementation for
7 * authentication.
8 *
9 * @author  Quinn Comendant <quinn@strangecode.com>
10 * @version 1.2
11 */
12 
13// Usage example:
14// $auth = new Auth_File();
15// $auth->setParam(array(
16//     'htpasswd_file' => COMMON_BASE . '/global/site_users.htpasswd',
17//     'login_timeout' => 21600,
18//     'idle_timeout' => 3600,
19//     'login_url' => '/login.php'
20// ));
21
22// Available encryption types for class Auth_SQL.
23define('AUTH_ENCRYPT_MD5', 'md5');
24define('AUTH_ENCRYPT_CRYPT', 'crypt');
25define('AUTH_ENCRYPT_SHA1', 'sha1');
26define('AUTH_ENCRYPT_PLAINTEXT', 'plaintext');
27
28class Auth_File {
29   
30    // Namespace of this auth object.
31    var $_ns;
32   
33    // Parameters to be specified by setParam().
34    var $_params = array();
35    var $_default_params = array(
36       
37        // Full path to htpasswd file.
38        'htpasswd_file' => null,
39
40        // The type of encryption to use for passwords stored in the db_table. Use one of the AUTH_ENCRYPT_* types specified above.
41        'encryption_type' => AUTH_ENCRYPT_CRYPT,
42
43        // The URL to the login script.
44        'login_url' => '/',
45
46        // The maximum amount of time a user is allowed to be logged in. They will be forced to login again if they expire.
47        // This applies to admins and users. In seconds. 21600 seconds = 6 hours.
48        'login_timeout' => 21600,
49
50        // The maximum amount of time a user is allowed to be idle before their session expires. They will be forced to login again if they expire.
51        // This applies to admins and users. In seconds. 3600 seconds = 1 hour.
52        'idle_timeout' => 3600,
53
54        // An array of IP blocks that are bypass the remote_ip comparison check. Useful for dynamic IPs or those behind proxy servers.
55        'trusted_networks' => array(),
56    );
57
58    // Associative array of usernames to hashed passwords.
59    var $_users = array();
60
61    /**
62     * Constructs a new htpasswd authentication object.
63     *
64     * @access public
65     *
66     * @param optional array $params  A hash containing parameters.
67     */
68    function Auth_File($namespace='')
69    {
70        $this->_ns = $namespace;
71
72        // Initialize default parameters.
73        $this->setParam($this->_default_params);
74    }
75
76    /**
77     * Set the params of an auth object.
78     *
79     * @param  array $params   Array of parameter keys and value to set.
80     * @return bool true on success, false on failure
81     */
82    function setParam($params)
83    {
84        if (isset($params) && is_array($params)) {
85            // Merge new parameters with old overriding only those passed.
86            $this->_params = array_merge($this->_params, $params);
87        }
88    }
89
90    /**
91     * Return the value of a parameter, if it exists.
92     *
93     * @access public
94     * @param string $param        Which parameter to return.
95     * @return mixed               Configured parameter value.
96     */
97    function getParam($param)
98    {
99        $app =& App::getInstance();
100   
101        if (isset($this->_params[$param])) {
102            return $this->_params[$param];
103        } else {
104            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
105            return null;
106        }
107    }
108
109    /**
110     * Clear any authentication tokens in the current session. A.K.A. logout.
111     *
112     * @access public
113     */
114    function clear()
115    {
116        $_SESSION['_auth_file'][$this->_ns] = array('authenticated' => false);
117    }
118
119
120    /**
121     * Sets a variable into a registered auth session.
122     *
123     * @access public
124     * @param mixed $key      Which value to set.
125     * @param mixed $val      Value to set variable to.
126     */
127    function set($key, $val)
128    {
129        if (!isset($_SESSION['_auth_file'][$this->_ns]['user_data'])) {
130            $_SESSION['_auth_file'][$this->_ns]['user_data'] = array();
131        }
132        $_SESSION['_auth_file'][$this->_ns]['user_data'][$key] = $val;
133    }
134
135    /**
136     * Returns a specified value from a registered auth session.
137     *
138     * @access public
139     * @param mixed $key      Which value to return.
140     * @param mixed $default  Value to return if key not found in user_data.
141     * @return mixed          Value stored in session.
142     */
143    function get($key, $default='')
144    {
145        if (isset($_SESSION['_auth_file'][$this->_ns][$key])) {
146            return $_SESSION['_auth_file'][$this->_ns][$key];
147        } else if (isset($_SESSION['_auth_file'][$this->_ns]['user_data'][$key])) {
148            return $_SESSION['_auth_file'][$this->_ns]['user_data'][$key];
149        } else {
150            return $default;
151        }
152    }
153    /**
154     * Find out if a set of login credentials are valid. Only supports
155     * htpasswd files with DES passwords right now.
156     *
157     * @access public
158     *
159     * @param string $username      The username to check.
160     * @param array $password      The password to compare to username.
161     *
162     * @return boolean  Whether or not the credentials are valid.
163     */
164    function authenticate($username, $password)
165    {
166        $app =& App::getInstance();
167   
168        if ('' == trim($password)) {
169            $app->logMsg(_("No password provided for authentication."), LOG_INFO, __FILE__, __LINE__);
170            return false;
171        }
172       
173        // Load users file.
174        $this->_loadHTPasswdFile();
175
176        if (!isset($this->_users[$username])) {
177            $app->logMsg(_("User ID provided does not exist."), LOG_INFO, __FILE__, __LINE__);
178            return false;
179        }
180
181        if ($this->_encrypt($password, $this->_users[$username]) != $this->_users[$username]) {
182            $app->logMsg(sprintf('Authentication failed for user %s', $username), LOG_INFO, __FILE__, __LINE__);
183            return false;
184        }
185       
186        // Authentication successful!
187        return true;
188    }
189
190    /**
191     * If user passes authentication create authenticated session.
192     *
193     * @access public
194     *
195     * @param string $username     The username to check.
196     * @param array $password     The password to compare to username.
197     *
198     * @return boolean  Whether or not the credentials are valid.
199     */
200    function login($username, $password)
201    {
202        $username = mb_strtolower(trim($username));
203
204        $this->clear();
205
206        if (!$this->authenticate($username, $password)) {
207            // No login: failed authentication!
208            return false;
209        }
210       
211        $_SESSION['_auth_file'][$this->_ns] = array(
212            'authenticated' => true,
213            'username' => $username,
214            'login_datetime' => date('Y-m-d H:i:s'),
215            'last_access_datetime' => date('Y-m-d H:i:s'),
216            'remote_ip' => getRemoteAddr()
217        );
218
219        // We're logged-in!
220        return true;
221    }
222
223    /**
224     * Test if user has a currently logged-in session.
225     *  - authentication flag set to true
226     *  - username not empty
227     *  - total logged-in time is not greater than login_timeout
228     *  - idle time is not greater than idle_timeout
229     *  - remote address is the same as the login remote address.
230     *
231     * @access public
232     */
233    function isLoggedIn()
234    {
235        $app =& App::getInstance();
236   
237        // Some users will access from networks with a changing IP number (i.e. behind a proxy server). These users must be allowed entry by adding their IP to the list of trusted_networks.
238        if ($trusted_net = ipInRange(getRemoteAddr(), $this->_params['trusted_networks'])) {
239            $user_in_trusted_network = true;
240            $app->logMsg(sprintf('User %s accessing from trusted network %s', $_SESSION['_auth_file'][$this->_ns]['username'], $trusted_net), LOG_DEBUG, __FILE__, __LINE__);
241        } else if (preg_match('/proxy.aol.com$/i', getRemoteAddr(true))) {
242            $user_in_trusted_network = true;
243            $app->logMsg(sprintf('User %s accessing from trusted network proxy.aol.com', $_SESSION['_auth_file'][$this->_ns]['username']), LOG_DEBUG, __FILE__, __LINE__);
244        } else {
245            $user_in_trusted_network = false;
246        }
247
248        // Test login with information stored in session. Skip IP matching for users from trusted networks.
249        if (isset($_SESSION['_auth_file'][$this->_ns])
250            && true === $_SESSION['_auth_file'][$this->_ns]['authenticated']
251            && !empty($_SESSION['_auth_file'][$this->_ns]['username'])
252            && strtotime($_SESSION['_auth_file'][$this->_ns]['login_datetime']) > time() - $this->_params['login_timeout']
253            && strtotime($_SESSION['_auth_file'][$this->_ns]['last_access_datetime']) > time() - $this->_params['idle_timeout']
254            && ($_SESSION['_auth_file'][$this->_ns]['remote_ip'] == getRemoteAddr() || $user_in_trusted_network)
255        ) {
256            // User is authenticated!
257            $_SESSION['_auth_file'][$this->_ns]['last_access_datetime'] = date('Y-m-d H:i:s');
258            return true;
259        } else if (isset($_SESSION['_auth_file'][$this->_ns]) && true === $_SESSION['_auth_file'][$this->_ns]['authenticated']) {
260            if (strtotime($_SESSION['_auth_file'][$this->_ns]['last_access_datetime']) > time() - 43200) {
261                // Only raise message if last session is less than 12 hours old.
262                $app->raiseMsg(_("Your session has closed. You need to log-in again."), MSG_NOTICE, __FILE__, __LINE__);
263            }
264
265            // Log the reason for login expiration.
266            $expire_reasons = array();
267            if (empty($_SESSION['_auth_file'][$this->_ns]['username'])) {
268                $expire_reasons[] = 'username not found';
269            }
270            if (strtotime($_SESSION['_auth_file'][$this->_ns]['login_datetime']) <= time() - $this->_params['login_timeout']) {
271                $expire_reasons[] = 'login_timeout expired';
272            }
273            if (strtotime($_SESSION['_auth_file'][$this->_ns]['last_access_datetime']) <= time() - $this->_params['idle_timeout']) {
274                $expire_reasons[] = 'idle_timeout expired';
275            }
276            if ($_SESSION['_auth_file'][$this->_ns]['remote_ip'] != getRemoteAddr() && !$user_in_trusted_network) {
277                $expire_reasons[] = sprintf('remote_ip not matched (%s != %s)', $_SESSION['_auth_file'][$this->_ns]['remote_ip'], getRemoteAddr());
278            }
279            $app->logMsg(sprintf('User %s session expired: %s', $_SESSION['_auth_file'][$this->_ns]['username'], join(', ', $expire_reasons)), LOG_INFO, __FILE__, __LINE__);
280        }
281
282        return false;
283    }
284
285    /**
286     * Redirect user to login page if they are not logged in.
287     *
288     * @param string $message The text description of a message to raise.
289     * @param int    $type    The type of message: MSG_NOTICE,
290     *                        MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
291     * @param string $file    __FILE__.
292     * @param string $line    __LINE__.
293     * @access public
294     */
295    function requireLogin($message='', $type=MSG_NOTICE, $file=null, $line=null)
296    {
297        $app =& App::getInstance();
298   
299        if (!$this->isLoggedIn()) {
300            // Display message for requiring login. (RaiseMsg will ignore empty strings.)
301            $app->raiseMsg($message, $type, $file, $line);
302
303            // Login scripts must have the same 'login' tag for boomerangURL verification/manipulation.
304            $app->setBoomerangURL(absoluteMe(), 'login');
305            $app->dieURL($this->_params['login_url']);
306        }
307    }
308   
309    /**
310     * Wrapper function for compatibility with lib/Lock.inc.php.
311     *
312     * @param  string  $username    Username to return.
313     * @return string               Username, or false if none found.
314     */
315    function getUsername($username)
316    {
317        if ('' != $username) {
318            return $username;
319        } else {
320            return false;
321        }
322    }
323
324    /*
325    * Reads the configured htpasswd file into the _users array.
326    *
327    * @access   public
328    * @return   false on error, true on success.
329    * @author   Quinn Comendant <quinn@strangecode.com>
330    * @version  1.0
331    * @since    18 Apr 2006 18:17:48
332    */
333    function _loadHTPasswdFile()
334    {
335        $app =& App::getInstance();
336   
337        static $users = null;
338       
339        if (!file_exists($this->_params['htpasswd_file'])) {
340            $app->logMsg(sprintf('htpasswd file missing or not specified: %s', $this->_params['htpasswd_file']), LOG_ERR, __FILE__, __LINE__);
341            return false;
342        }
343       
344        if (!isset($users)) {
345            if (false === ($users = file($this->_params['htpasswd_file']))) {
346                $app->logMsg(sprintf('Could not read htpasswd file: %s', $this->_params['htpasswd_file']), LOG_ERR, __FILE__, __LINE__);
347                return false;
348            }
349        }
350
351        if (is_array($users)) {
352            foreach ($users as $u) {
353                list($user, $pass) = explode(':', $u, 2);
354                $this->_users[trim($user)] = trim($pass);
355            }
356            return true;
357        }
358        return false;
359    }
360
361    /**
362     * Hash a given password according to the configured encryption
363     * type.
364     *
365     * @param string $password              The password to encrypt.
366     * @param string $encrypted_password    The currently encrypted password to use as salt, if needed.
367     *
368     * @return string  The hashed password.
369     */
370    function _encrypt($password, $encrypted_password=null)
371    {
372        switch ($this->_params['encryption_type']) {
373        case AUTH_ENCRYPT_PLAINTEXT :
374            return $password;
375            break;
376
377        case AUTH_ENCRYPT_SHA1 :
378            return sha1($password);
379            break;
380
381        case AUTH_ENCRYPT_MD5 :
382            return md5($password);
383            break;
384
385        case AUTH_ENCRYPT_CRYPT :
386        default :
387            return crypt($password, $encrypted_password);
388            break;
389        }
390    }
391
392} // end class
393?>
Note: See TracBrowser for help on using the repository browser.