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

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

fixed Auth_File

File size: 6.6 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.1
8 */
9
10// Available encryption types for class Auth_SQL.
11define('AUTH_ENCRYPT_MD5', 'md5');
12define('AUTH_ENCRYPT_CRYPT', 'crypt');
13define('AUTH_ENCRYPT_SHA1', 'sha1');
14define('AUTH_ENCRYPT_PLAINTEXT', 'plaintext');
15
16class Auth_File {
17
18    var $_params = array(
19        'encryption_type' => AUTH_ENCRYPT_CRYPT,
20        'htpasswd_file' => null,
21        'login_timeout' => 21600, // 6 hours.
22        'idle_timeout' => 3600, // 1 hour.
23    );
24    var $_users = array();
25
26    /**
27     * Constructs a new htpasswd authentication object.
28     *
29     * @access public
30     *
31     * @param optional array $params  A hash containing parameters.
32     */
33    function Auth_File($params = array())
34    {
35        $this->_params = array_merge($this->_params, $params);
36
37        if (!empty($this->_params['htpasswd_file'])) {
38            if (false === ($users = file($this->_params['htpasswd_file']))) {
39                App::logMsg(sprintf(_("Could not read htpasswd file: %s"), $this->_params['htpasswd_file']), LOG_ERR, __FILE__, __LINE__);
40            }
41            if (is_array($users)) {
42                foreach ($users as $line) {
43                    list($user, $pass) = explode(':', $line, 2);
44                    $this->_users[trim($user)] = trim($pass);
45                }
46            }
47        }
48    }
49
50    /**
51     * Set the params of an auth object.
52     *
53     * @param  array $params   Array of parameter keys and value to set.
54     * @return bool true on success, false on failure
55     */
56    function setParam($params)
57    {
58        if (isset($params) && is_array($params)) {
59            // Merge new parameters with old overriding only those passed.
60            $this->_params = array_merge($this->_params, $params);
61        }
62    }
63
64    /**
65     * Return the value of a parameter, if it exists.
66     *
67     * @access public
68     * @param string $param        Which parameter to return.
69     * @return mixed               Configured parameter value.
70     */
71    function getParam($param)
72    {
73        if (isset($this->_params[$param])) {
74            return $this->_params[$param];
75        } else {
76            App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
77            return null;
78        }
79    }
80
81    /**
82     * Clear any authentication tokens in the current session. A.K.A. logout.
83     *
84     * @access public
85     */
86    function clearAuth()
87    {
88        $_SESSION['_auth_file'] = array('authenticated' => false);
89    }
90
91    /**
92     * Find out if a set of login credentials are valid. Only supports
93     * htpasswd files with DES passwords right now.
94     *
95     * @access public
96     *
97     * @param string $username      The username to check.
98     * @param array $password      The password to compare to username.
99     *
100     * @return boolean  Whether or not the credentials are valid.
101     */
102    function authenticate($username, $password)
103    {
104        if ('' == trim($password)) {
105            App::logMsg(_("No password provided for htpasswd authentication."), LOG_INFO, __FILE__, __LINE__);
106            return false;
107        }
108
109        if (!isset($this->_users[$username])) {
110            App::logMsg(_("User ID provided does not exist."), LOG_INFO, __FILE__, __LINE__);
111            return false;
112        }
113
114        if ($this->_encrypt($password, $password) == $this->_users[$username]) {
115            return true;
116        } else {
117            App::logMsg(sprintf('Authentication failed for user %s', $username), LOG_INFO, __FILE__, __LINE__);
118            return false;
119        }
120    }
121
122    /**
123     * If user passes authentication create authenticated session.
124     *
125     * @access public
126     *
127     * @param string $username     The username to check.
128     * @param array $password     The password to compare to username.
129     *
130     * @return boolean  Whether or not the credentials are valid.
131     */
132    function login($username, $password)
133    {
134        $username = strtolower(trim($username));
135
136        $this->clearAuth();
137
138        if ($this->authenticate($username, $password)) {
139            $_SESSION['_auth_file'] = array(
140                'authenticated' => true,
141                'username' => $username,
142                'login_datetime' => date('Y-m-d H:i:s'),
143                'last_access_datetime' => date('Y-m-d H:i:s'),
144                'remote_addr' => getRemoteAddr()
145            );
146            return true;
147        }
148        return false;
149    }
150
151    /**
152     * Test if user has a currently logged-in session.
153     *  - authentication flag set to true
154     *  - username not empty
155     *  - total logged-in time is not greater than login_timeout
156     *  - idle time is not greater than idle_timeout
157     *  - remote address is the same as the login remote address.
158     *
159     * @access public
160     */
161    function isLoggedIn()
162    {
163        if (isset($_SESSION['_auth_file'])) {
164            if (true === $_SESSION['_auth_file']['authenticated']
165            && !empty($_SESSION['_auth_file']['username'])
166            && strtotime($_SESSION['_auth_file']['login_datetime']) > time() - $this->_params['login_timeout']
167            && strtotime($_SESSION['_auth_file']['last_access_datetime']) > time() - $this->_params['idle_timeout']
168            && $_SESSION['_auth_file']['remote_addr'] == getRemoteAddr()
169            ) {
170                $_SESSION['_auth_file']['last_access_datetime'] = date('Y-m-d H:i:s');
171                return true;
172            } else if (true === $_SESSION['_auth_file']['authenticated']) {
173                App::raiseMsg(_("Your session has closed. You need to log-in again."), MSG_NOTICE, __FILE__, __LINE__);
174                $this->clearAuth();
175            }
176        }
177        return false;
178    }
179
180    /**
181     * Hash a given password according to the configured encryption
182     * type.
183     *
184     * @param string $password              The password to encrypt.
185     * @param string $encrypted_password    The currently encrypted password to use as salt, if needed.
186     *
187     * @return string  The hashed password.
188     */
189    function _encrypt($password, $encrypted_password=null)
190    {
191        switch ($this->_params['encryption_type']) {
192        case AUTH_ENCRYPT_PLAINTEXT :
193            return $password;
194            break;
195
196        case AUTH_ENCRYPT_SHA1 :
197            return sha1($password);
198            break;
199
200        case AUTH_ENCRYPT_MD5 :
201            return md5($password);
202            break;
203
204        case AUTH_ENCRYPT_CRYPT :
205        default :
206            return crypt($password, $encrypted_password);
207            break;
208        }
209    }
210
211} // end class
212?>
Note: See TracBrowser for help on using the repository browser.