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

Last change on this file since 563 was 563, checked in by anonymous, 8 years ago

Removed assumption of localhost for mysql server. Removed exception for proxy.aol.com.

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