source: tags/2.0.2/lib/Auth_File.inc.php @ 312

Last change on this file since 312 was 196, checked in by scdev, 18 years ago

Q - ...

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