source: trunk/lib/Auth_SQL.inc.php @ 195

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

Q - auth file clearauth added to constructor.

File size: 42.4 KB
Line 
1<?php
2/**
3 * The Auth_SQL class provides a SQL implementation for authentication.
4 *
5 * @author  Quinn Comendant <quinn@strangecode.com>
6 * @version 2.1
7 */
8
9// Available encryption types for class Auth_SQL.
10define('AUTH_ENCRYPT_PLAINTEXT', 1);
11define('AUTH_ENCRYPT_CRYPT', 2);
12define('AUTH_ENCRYPT_SHA1', 3);
13define('AUTH_ENCRYPT_SHA1_HARDENED', 4);
14define('AUTH_ENCRYPT_MD5', 5);
15define('AUTH_ENCRYPT_MD5_HARDENED', 6);
16
17require_once dirname(__FILE__) . '/Email.inc.php';
18
19class Auth_SQL {
20       
21    // Namespace of this auth object.
22    var $_ns;
23   
24    // Static var for test.
25    var $_authentication_tested;
26
27    // Paramters to be configured by setParam.
28    var $_params = array();
29    var $_default_params = array(
30
31        // Automatically create table and verify columns. Better set to false after site launch.
32        'create_table' => true,
33
34        // The database table containing users to authenticate.
35        'db_table' => 'user_tbl',
36
37        // The name of the primary key for the db_table.
38        'db_primary_key' => 'user_id',
39
40        // The name of the username key for the db_table.
41        'db_username_column' => 'username',
42
43        // If using the db_login_table feature, specify the db_login_table. The primary key must match the primary key for the db_table.
44        'db_login_table' => 'user_login_tbl',
45
46        // The type of encryption to use for passwords stored in the db_table. Use one of the AUTH_ENCRYPT_* types specified above.
47        // Hardened password hashes rely on the same key/salt being used to compare encryptions.
48        // Be aware that when using one of the hardened types the App signing_key or $more_salt below cannot change!
49        'encryption_type' => AUTH_ENCRYPT_MD5,
50
51        // The URL to the login script.
52        'login_url' => '/',
53
54        // The maximum amount of time a user is allowed to be logged in. They will be forced to login again if they expire.
55        // In seconds. 21600 seconds = 6 hours.
56        'login_timeout' => 21600,
57
58        // 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.
59        // In seconds. 3600 seconds = 1 hour.
60        'idle_timeout' => 3600,
61
62        // The period of time to compare login abuse attempts. If a threshold of logins is reached in this amount of time the account is blocked.
63        // Days and hours, like this: 'DD:HH'
64        'login_abuse_timeframe' => '04:00',
65
66        // The number of warnings a user will receive (and their password reset each time) before their account is completely blocked.
67        'login_abuse_warnings' => 3,
68
69        // The maximum number of IP addresses a user can login with over the timeout period before their account is blocked.
70        'login_abuse_max_ips' => 5,
71
72        // The IP address subnet size threshold. Uses a CIDR notation network mask (see CIDR cheatsheet at bottom).
73        // Any integar between 0 and 32 is permitted. Setting this to '24' permits any address in a
74        // class C network (255.255.255.0) to be considered the same. Setting to '32' compares each IP absolutely.
75        // Setting to '0' ignores all IPs, thus disabling login_abuse checking.
76        'login_abuse_ip_bitmask' => 32,
77
78        // Specify usernames to exclude from the account abuse detection system. This is specified as a hardcoded array provided at
79        // class instantiation time, or can be saved in the db_table under the login_abuse_exempt field.
80        'login_abuse_exempt_usernames' => array(),
81
82        // An array of IP blocks that are bypass the remote_ip comparison check. Useful for dynamic IPs or those behind proxy servers.
83        'trusted_networks' => array(),
84
85        // Allow user accounts to be blocked? Requires the user table to have the columns 'blocked' and 'blocked_reason'
86        'blocking' => false,
87
88        // Use a db_login_table to detect excessive logins. This requires blocking to be enabled.
89        'abuse_detection' => false,
90    );
91
92    /**
93     * Constructs a new authentication object.
94     *
95     * @access public
96     * @param optional array $params  A hash containing parameters.
97     */
98    function Auth_SQL($namespace='')
99    {
100        $app =& App::getInstance();
101       
102        $this->_ns = $namespace;
103       
104        if (!isset($_SESSION['_auth_sql'][$this->_ns])) {
105            $this->clear();
106        }
107
108        // Initialize default parameters.
109        $this->setParam($this->_default_params);
110
111        // Get create tables config from global context.
112        if (!is_null($app->getParam('db_create_tables'))) {
113            $this->setParam(array('create_table' => $app->getParam('db_create_tables')));
114        }
115    }
116
117    /**
118     * Setup the database tables for this class.
119     *
120     * @access  public
121     * @author  Quinn Comendant <quinn@strangecode.com>
122     * @since   26 Aug 2005 17:09:36
123     */
124    function initDB($recreate_db=false)
125    {
126        $app =& App::getInstance();
127        $db =& DB::getInstance();
128   
129   
130        static $_db_tested = false;
131
132        if ($recreate_db || !$_db_tested && $this->getParam('create_table')) {
133
134            // User table.
135            if ($recreate_db) {
136                $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_table'));
137                $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_DEBUG, __FILE__, __LINE__);
138            }
139
140            // The minimal columns for a table compatable with the Auth_SQL class.
141            $db->query("CREATE TABLE IF NOT EXISTS " . $db->escapeString($this->getParam('db_table')) . " (
142                " . $this->getParam('db_primary_key') . " smallint(11) NOT NULL auto_increment,
143                " . $this->getParam('db_username_column') . " varchar(255) NOT NULL default '',
144                userpass varchar(255) NOT NULL default '',
145                first_name varchar(255) NOT NULL default '',
146                last_name varchar(255) NOT NULL default '',
147                email varchar(255) NOT NULL default '',
148                login_abuse_exempt enum('true') default NULL,
149                blocked enum('true') default NULL,
150                blocked_reason varchar(255) NOT NULL default '',
151                abuse_warning_level tinyint(4) NOT NULL default '0',
152                seconds_online int(11) NOT NULL default '0',
153                last_login_datetime datetime NOT NULL default '0000-00-00 00:00:00',
154                last_access_datetime datetime NOT NULL default '0000-00-00 00:00:00',
155                last_login_ip varchar(255) NOT NULL default '0.0.0.0',
156                added_by_user_id smallint(11) default NULL,
157                modified_by_user_id smallint(11) default NULL,
158                added_datetime datetime NOT NULL default '0000-00-00 00:00:00',
159                modified_datetime datetime NOT NULL default '0000-00-00 00:00:00',
160                PRIMARY KEY (" . $this->getParam('db_primary_key') . "),
161                KEY " . $this->getParam('db_username_column') . " (" . $this->getParam('db_username_column') . "),
162                KEY userpass (userpass),
163                KEY email (email)
164            )");
165
166            if (!$db->columnExists($this->getParam('db_table'), array(
167                $this->getParam('db_primary_key'),
168                $this->getParam('db_username_column'),
169                'userpass',
170                'first_name',
171                'last_name',
172                'email',
173                'login_abuse_exempt',
174                'blocked',
175                'blocked_reason',
176                'abuse_warning_level',
177                'seconds_online',
178                'last_login_datetime',
179                'last_access_datetime',
180                'last_login_ip',
181                'added_by_user_id',
182                'modified_by_user_id',
183                'added_datetime',
184                'modified_datetime',
185            ), false, false)) {
186                $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__);
187                trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), E_USER_ERROR);
188            }
189
190            // Login table is used for abuse_detection features.
191            if ($this->getParam('abuse_detection')) {
192                if ($recreate_db) {
193                    $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_login_table'));
194                    $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_login_table')), LOG_DEBUG, __FILE__, __LINE__);
195                }
196                $db->query("CREATE TABLE IF NOT EXISTS " . $this->getParam('db_login_table') . " (
197                    " . $this->getParam('db_primary_key') . " smallint(11) NOT NULL default '0',
198                    login_datetime datetime NOT NULL default '0000-00-00 00:00:00',
199                    remote_ip_binary char(32) NOT NULL default '',
200                    KEY " . $this->getParam('db_primary_key') . " (" . $this->getParam('db_primary_key') . "),
201                    KEY login_datetime (login_datetime),
202                    KEY remote_ip_binary (remote_ip_binary)
203                )");
204
205                if (!$db->columnExists($this->getParam('db_login_table'), array(
206                    $this->getParam('db_primary_key'),
207                    'login_datetime',
208                    'remote_ip_binary',
209                ), false, false)) {
210                    $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_login_table')), LOG_ALERT, __FILE__, __LINE__);
211                    trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_login_table')), E_USER_ERROR);
212                }
213            }
214        }
215        $_db_tested = true;
216    }
217
218    /**
219     * Set the params of an auth object.
220     *
221     * @param  array $params   Array of parameter keys and value to set.
222     * @return bool true on success, false on failure
223     */
224    function setParam($params)
225    {
226        if (isset($params) && is_array($params)) {
227            // Merge new parameters with old overriding only those passed.
228            $this->_params = array_merge($this->_params, $params);
229        }
230    }
231
232    /**
233     * Return the value of a parameter, if it exists.
234     *
235     * @access public
236     * @param string $param        Which parameter to return.
237     * @return mixed               Configured parameter value.
238     */
239    function getParam($param)
240    {
241        $app =& App::getInstance();
242   
243        if (isset($this->_params[$param])) {
244            return $this->_params[$param];
245        } else {
246            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
247            return null;
248        }
249    }
250
251    /**
252     * Clear any authentication tokens in the current session. A.K.A. logout.
253     *
254     * @access public
255     */
256    function clear()
257    {
258        $db =& DB::getInstance();
259   
260        $this->initDB();
261
262        if ($this->isLoggedIn()) {           
263            $db->query("
264                UPDATE " . $this->_params['db_table'] . " SET
265                seconds_online = seconds_online + (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_access_datetime)),
266                last_login_datetime = '0000-00-00 00:00:00'
267                WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'
268            ");
269        }
270        $_SESSION['_auth_sql'][$this->_ns] = array('authenticated' => false);
271    }
272
273    /**
274     * Sets a variable into a registered auth session.
275     *
276     * @access public
277     * @param mixed $key      Which value to set.
278     * @param mixed $val      Value to set variable to.
279     */
280    function set($key, $val)
281    {
282        if (!isset($_SESSION['_auth_sql'][$this->_ns]['user_data'])) {
283            $_SESSION['_auth_sql'][$this->_ns]['user_data'] = array();
284        }
285        $_SESSION['_auth_sql'][$this->_ns]['user_data'][$key] = $val;
286    }
287
288    /**
289     * Returns a specified value from a registered auth session.
290     *
291     * @access public
292     * @param mixed $key      Which value to return.
293     * @param mixed $default  Value to return if key not found in user_data.
294     * @return mixed          Value stored in session.
295     */
296    function get($key, $default='')
297    {
298        if (isset($_SESSION['_auth_sql'][$this->_ns][$key])) {
299            return $_SESSION['_auth_sql'][$this->_ns][$key];
300        } else if (isset($_SESSION['_auth_sql'][$this->_ns]['user_data'][$key])) {
301            return $_SESSION['_auth_sql'][$this->_ns]['user_data'][$key];
302        } else {
303            return $default;
304        }
305    }
306
307    /**
308     * Find out if a set of login credentials are valid.
309     *
310     * @access private
311     * @param string $username      The username to check.
312     * @param string $password      The password to compare to username.
313     * @return mixed  False if credentials not found in DB, or returns DB row matching credentials.
314     */
315    function authenticate($username, $password)
316    {
317        $app =& App::getInstance();
318        $db =& DB::getInstance();
319
320        $this->initDB();
321
322        switch ($this->_params['encryption_type']) {
323        case AUTH_ENCRYPT_CRYPT :
324            // Query DB for user matching credentials. Compare cyphertext with salted-encrypted password.
325            $qid = $db->query("
326                SELECT *, " . $this->_params['db_primary_key'] . " AS user_id
327                FROM " . $this->_params['db_table'] . "
328                WHERE " . $this->_params['db_username_column'] . " = '" . $db->escapeString($username) . "'
329                AND BINARY userpass = ENCRYPT('" . $db->escapeString($password) . "', LEFT(userpass, 2)))
330            ");
331            break;
332        case AUTH_ENCRYPT_PLAINTEXT :
333        case AUTH_ENCRYPT_MD5 :
334        case AUTH_ENCRYPT_SHA1 :
335        default :
336            // Query DB for user matching credentials. Directly compare cyphertext with result from encryptPassword().
337            $qid = $db->query("
338                SELECT *, " . $this->_params['db_primary_key'] . " AS user_id
339                FROM " . $this->_params['db_table'] . "
340                WHERE " . $this->_params['db_username_column'] . " = '" . $db->escapeString($username) . "'
341                AND BINARY userpass = '" . $db->escapeString($this->encryptPassword($password)) . "'
342            ");
343            break;
344        }
345
346        // Return user data if found.
347        if ($user_data = mysql_fetch_assoc($qid)) {
348            // Don't return password value.
349            unset($user_data['userpass']);
350            $app->logMsg(sprintf('Authentication successful for user %s (%s)', $user_data['user_id'], $username), LOG_INFO, __FILE__, __LINE__);
351            return $user_data;
352        } else {
353            $app->logMsg(sprintf('Authentication failed for user %s (encrypted attempted password: %s)', $username, $this->encryptPassword($password)), LOG_NOTICE, __FILE__, __LINE__);
354            return false;
355        }
356    }
357
358    /**
359     * If user authenticated, register login into session.
360     *
361     * @access private
362     * @param string $username     The username to check.
363     * @param string $password     The password to compare to username.
364     * @return boolean  Whether or not the credentials are valid.
365     */
366    function login($username, $password)
367    {
368        $app =& App::getInstance();
369        $db =& DB::getInstance();
370   
371        $this->initDB();
372
373        $this->clear();
374
375        if (!$user_data = $this->authenticate($username, $password)) {
376            // No login: failed authentication!
377            return false;
378        }
379
380        // Register authenticated session.
381        $_SESSION['_auth_sql'][$this->_ns] = array(
382            'authenticated'         => true,
383            'user_id'               => $user_data['user_id'],
384            'username'              => $username,
385            'login_datetime'        => date('Y-m-d H:i:s'),
386            'last_access_datetime'  => date('Y-m-d H:i:s'),
387            'remote_ip'             => getRemoteAddr(),
388            'login_abuse_exempt'    => isset($user_data['login_abuse_exempt']) ? !empty($user_data['login_abuse_exempt']) : in_array($username, $this->_params['login_abuse_exempt_usernames']),
389            'user_data'             => $user_data
390        );
391
392        /**
393         * Check if the account is blocked, respond in context to reason. Cancel the login if blocked.
394         */
395        if ($this->getParam('blocking')) {
396            if (!empty($user_data['blocked'])) {
397
398                $app->logMsg(sprintf('User %s (%s) login failed due to blocked account: %s', $this->get('user_id'), $this->get('username'), $this->get('blocked_reason')), LOG_NOTICE, __FILE__, __LINE__);
399
400                switch ($user_data['blocked_reason']) {
401                    case 'account abuse' :
402                        $app->raiseMsg(sprintf(_("This account has been blocked due to possible account abuse. Please contact us to reactivate."), null), MSG_WARNING, __FILE__, __LINE__);
403                        break;
404                    default :
405                        $app->raiseMsg(sprintf(_("This account is currently not active. %s"), $user_data['blocked_reason']), MSG_WARNING, __FILE__, __LINE__);
406                        break;
407                }
408
409                // No login: user is blocked!
410                $this->clear();
411                return false;
412            }
413        }
414
415        /**
416         * Check the db_login_table for too many logins under this account.
417         * (1) Count the number of unique IP addresses that logged in under this user within the login_abuse_timeframe
418         * (2) If this number exceeds the login_abuse_max_ips, assume multiple people are logging in under the same account.
419        **/
420        if ($this->getParam('abuse_detection') && !$this->get('login_abuse_exempt')) {
421            $qid = $db->query("
422                SELECT COUNT(DISTINCT LEFT(remote_ip_binary, " . $this->_params['login_abuse_ip_bitmask'] . "))
423                FROM " . $this->_params['db_login_table'] . "
424                WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'
425                AND DATE_ADD(login_datetime, INTERVAL '" . $this->_params['login_abuse_timeframe'] . "' DAY_HOUR) > NOW()
426            ");
427            list($distinct_ips) = mysql_fetch_row($qid);
428            if ($distinct_ips > $this->_params['login_abuse_max_ips']) {
429                if ($this->get('abuse_warning_level') < $this->_params['login_abuse_warnings']) {
430                    // Warn the user with a password reset.
431                    $this->resetPassword(null, _("This is a security precaution. We have detected this account has been accessed from multiple computers simultaneously. It is against policy to share login information with others. If further account abuse is detected this account will be blocked."));
432                    $app->raiseMsg(_("Your password has been reset as a security precaution. Please check your email for more information."), MSG_NOTICE, __FILE__, __LINE__);
433                    $app->logMsg(sprintf('Account abuse detected for user %s (%s) from IP %s', $this->get('user_id'), $this->get('username'), $this->get('remote_ip')), LOG_WARNING, __FILE__, __LINE__);
434                } else {
435                    // Block the account with the reason of account abuse.
436                    $this->blockAccount(null, 'account abuse');
437                    $app->raiseMsg(_("Your account has been blocked as a security precaution. Please contact us for more information."), MSG_NOTICE, __FILE__, __LINE__);
438                    $app->logMsg(sprintf('Account blocked for user %s (%s) from IP %s', $this->get('user_id'), $this->get('username'), $this->get('remote_ip')), LOG_ALERT, __FILE__, __LINE__);
439                }
440                // Increment user's warning level.
441                $db->query("UPDATE " . $this->_params['db_table'] . " SET abuse_warning_level = abuse_warning_level + 1 WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'");
442                // Reset the login counter for this user.
443                $db->query("DELETE FROM " . $this->_params['db_login_table'] . " WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'");
444                // No login: reset password because of account abuse!
445                $this->clear();
446                return false;
447            }
448
449            // Update the login counter table with this login access. Convert IP to binary.
450            // TODO: after MySQL 5.0.23 is released this query could benefit from INSERT DELAYED.
451            $db->query("
452                INSERT INTO " . $this->_params['db_login_table'] . " (
453                    " . $this->_params['db_primary_key'] . ",
454                    login_datetime,
455                    remote_ip_binary
456                ) VALUES (
457                    '" . $this->get('user_id') . "',
458                    '" . $this->get('login_datetime') . "',
459                    '" . sprintf('%032b', ip2long($this->get('remote_ip'))) . "'
460                )
461            ");
462        }
463
464        // Update user table with this login.
465        $db->query("
466            UPDATE " . $this->_params['db_table'] . " SET
467                last_login_datetime = '" . $this->get('login_datetime') . "',
468                last_access_datetime = '" . $this->get('login_datetime') . "',
469                last_login_ip = '" . $this->get('remote_ip') . "'
470            WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'
471        ");
472
473        // We're logged-in!
474        return true;
475    }
476
477    /**
478     * Test if user has a currently logged-in session.
479     *  - authentication flag set to true
480     *  - username not empty
481     *  - total logged-in time is not greater than login_timeout
482     *  - idle time is not greater than idle_timeout
483     *  - remote address is the same as the login remote address (aol users excluded).
484     *
485     * @access public
486     */
487    function isLoggedIn($user_id=null)
488    {
489        $app =& App::getInstance();
490        $db =& DB::getInstance();
491   
492        $this->initDB();
493
494        if (isset($user_id)) {
495            // Check the login status of a specific user.
496            $qid = $db->query("
497                SELECT 1 FROM " . $this->_params['db_table'] . "
498                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
499                AND DATE_ADD(last_login_datetime, INTERVAL '" . $this->_params['login_timeout'] . "' SECOND) > NOW()
500                AND DATE_ADD(last_access_datetime, INTERVAL '" . $this->_params['idle_timeout'] . "' SECOND) > NOW()
501            ");
502            return (mysql_num_rows($qid) > 0);
503        }
504
505        // User login test need only be run once per script execution. We cache the result in the session.
506        if ($this->_authentication_tested && isset($_SESSION['_auth_sql'][$this->_ns]['authenticated'])) {
507            return $_SESSION['_auth_sql'][$this->_ns]['authenticated'];
508        }
509
510        // Tesing login should occur once. This is the first time. Set flag.
511        $this->_authentication_tested = true;
512
513        // 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.
514        if ($trusted_net = ipInRange(getRemoteAddr(), $this->_params['trusted_networks'])) {
515            $user_in_trusted_network = true;
516            $app->logMsg(sprintf('User %s accessing from trusted network %s',
517                ($this->get('user_id') ? ' ' . $this->get('user_id') . ' (' .  $this->get('username') . ')' : ''),
518                $trusted_net
519            ), LOG_DEBUG, __FILE__, __LINE__);
520        } else if (preg_match('/proxy.aol.com$/i', getRemoteAddr(true))) {
521            $user_in_trusted_network = true;
522            $app->logMsg(sprintf('User %s accessing from trusted network proxy.aol.com',
523                ($this->get('user_id') ? ' ' . $this->get('user_id') . ' (' .  $this->get('username') . ')' : '')
524            ), LOG_DEBUG, __FILE__, __LINE__);
525        } else {
526            $user_in_trusted_network = false;
527        }
528
529        // Test login with information stored in session. Skip IP matching for users from trusted networks.
530        if (isset($_SESSION['_auth_sql'][$this->_ns])
531            && true === $_SESSION['_auth_sql'][$this->_ns]['authenticated']
532            && !empty($_SESSION['_auth_sql'][$this->_ns]['username'])
533            && strtotime($_SESSION['_auth_sql'][$this->_ns]['login_datetime']) > time() - $this->_params['login_timeout']
534            && strtotime($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime']) > time() - $this->_params['idle_timeout']
535            && ($_SESSION['_auth_sql'][$this->_ns]['remote_ip'] == getRemoteAddr() || $user_in_trusted_network)
536        ) {
537            // User is authenticated!
538            $_SESSION['_auth_sql'][$this->_ns]['last_access_datetime'] = date('Y-m-d H:i:s');
539
540            // Update the DB with the last_access_datetime and increment the seconds_online.
541            $db->query("
542                UPDATE " . $this->_params['db_table'] . " SET
543                seconds_online = seconds_online + (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_access_datetime)) + 1,
544                last_access_datetime = '" . $this->get('last_access_datetime') . "'
545                WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'
546            ");
547            if (mysql_affected_rows($db->getDBH()) > 0) {
548                // User record still exists in DB. Do this to ensure user was not delete from DB between accesses. Notice "+ 1" in SQL above to ensure record is modified.
549                return true;
550            } else {
551                $app->logMsg(sprintf('User update failed. Record not found for user %s (%s).', $this->get('user_id'), $this->get('username')), LOG_NOTICE, __FILE__, __LINE__);
552            }
553        } else if (isset($_SESSION['_auth_sql'][$this->_ns]) && true === $_SESSION['_auth_sql'][$this->_ns]['authenticated']) {
554            // User is authenticated, but login has expired.
555            if (strtotime($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime']) > time() - 43200) {
556                // Only raise message if last session is less than 12 hours old.
557                $app->raiseMsg(_("Your session has expired. You need to log-in again."), MSG_NOTICE, __FILE__, __LINE__);
558            }
559
560            // Log the reason for login expiration.
561            $expire_reasons = array();
562            if (empty($_SESSION['_auth_sql'][$this->_ns]['username'])) {
563                $expire_reasons[] = 'username not found';
564            }
565            if (strtotime($_SESSION['_auth_sql'][$this->_ns]['login_datetime']) <= time() - $this->_params['login_timeout']) {
566                $expire_reasons[] = 'login_timeout expired';
567            }
568            if (strtotime($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime']) <= time() - $this->_params['idle_timeout']) {
569                $expire_reasons[] = 'idle_timeout expired';
570            }
571            if ($_SESSION['_auth_sql'][$this->_ns]['remote_ip'] != getRemoteAddr() && !$user_in_trusted_network) {
572                $expire_reasons[] = sprintf('remote_ip not matched (%s != %s)', $_SESSION['_auth_sql'][$this->_ns]['remote_ip'], getRemoteAddr());
573            }
574            $app->logMsg(sprintf('User %s (%s) session expired: %s', $this->get('user_id'), $this->get('username'), join(', ', $expire_reasons)), LOG_INFO, __FILE__, __LINE__);
575        }
576
577        // User is not authenticated.
578        $this->clear();
579        return false;
580    }
581
582    /**
583     * Redirect user to login page if they are not logged in.
584     *
585     * @param string $message The text description of a message to raise.
586     * @param int    $type    The type of message: MSG_NOTICE,
587     *                        MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
588     * @param string $file    __FILE__.
589     * @param string $line    __LINE__.
590     * @access public
591     */
592    function requireLogin($message='', $type=MSG_NOTICE, $file=null, $line=null)
593    {
594        $app =& App::getInstance();
595   
596        if (!$this->isLoggedIn()) {
597            // Display message for requiring login. (RaiseMsg will ignore empty strings.)
598            $app->raiseMsg($message, $type, $file, $line);
599
600            // Login scripts must have the same 'login' tag for boomerangURL verification/manipulation.
601            $app->setBoomerangURL(absoluteMe(), 'login');
602            $app->dieURL($this->_params['login_url']);
603        }
604    }
605
606    /**
607     * This sets the 'blocked' field for a user in the db_table, and also
608     * adds an optional reason
609     *
610     * @param  string   $reason      The reason for blocking the account.
611     */
612    function blockAccount($user_id=null, $reason='')
613    {
614        $app =& App::getInstance();
615        $db =& DB::getInstance();
616   
617        $this->initDB();
618
619        if ($this->getParam('blocking')) {
620            if (strlen($db->escapeString($reason)) > 255) {
621                // blocked_reason field is varchar(255).
622                $app->logMsg(sprintf('Blocked reason provided is greater than 255 characters: %s', $reason), LOG_WARNING, __FILE__, __LINE__);
623            }
624
625            // Get user_id if specified.
626            $user_id = isset($user_id) ? $user_id : $this->get('user_id');
627            $db->query("
628                UPDATE " . $this->_params['db_table'] . " SET
629                blocked = 'true',
630                blocked_reason = '" . $db->escapeString($reason) . "'
631                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
632            ");
633        }
634    }
635
636    /**
637     * Unblocks a user in the db_table, and clears any blocked_reason.
638     */
639    function unblockAccount($user_id=null)
640    {
641        $db =& DB::getInstance();
642   
643        $this->initDB();
644   
645        if ($this->getParam('blocking')) {
646            // Get user_id if specified.
647            $user_id = isset($user_id) ? $user_id : $this->get('user_id');
648            $db->query("
649                UPDATE " . $this->_params['db_table'] . " SET
650                blocked = '',
651                blocked_reason = ''
652                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
653            ");
654        }
655    }
656
657    /**
658     * Returns true if username already exists in database.
659     *
660     * @param  string  $username    Username to look for.
661     * @return bool                 True if username exists.
662     */
663    function usernameExists($username)
664    {
665        $db =& DB::getInstance();
666   
667        $this->initDB();
668
669        $qid = $db->query("
670            SELECT 1
671            FROM " . $this->_params['db_table'] . "
672            WHERE " . $this->_params['db_username_column'] . " = '" . $db->escapeString($username) . "'
673        ");
674        return (mysql_num_rows($qid) > 0);
675    }
676
677    /**
678     * Returns a username for a specified user id.
679     *
680     * @param  string  $user_id     User id to look for.
681     * @return string               Username, or false if none found.
682     */
683    function getUsername($user_id)
684    {
685        $db =& DB::getInstance();
686   
687        $this->initDB();
688
689        $qid = $db->query("
690            SELECT " . $this->_params['db_username_column'] . "
691            FROM " . $this->_params['db_table'] . "
692            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
693        ");
694        if (list($username) = mysql_fetch_row($qid)) {
695            return $username;
696        } else {
697            return false;
698        }
699    }
700
701    /**
702     * Returns a randomly generated password based on $pattern. The pattern is any
703     * sequence of 'x', 'V', 'C', 'v', 'c', or 'd' and if it is something like 'cvccv' this
704     * function will generate a pronouncable password. Recommend using more complex
705     * patterns, at minimum the US State Department standard: cvcddcvc.
706     *
707     * - x    a random upper or lower alpha character or digit
708     * - C    a random upper or lower consanant
709     * - V    a random upper or lower vowel
710     * - c    a random lowercase consanant
711     * - v    a random lowercase vowel
712     * - d    a random digit
713     *
714     * @param  string $pattern  a sequence of character types, above.
715     * @return string           a password
716     */
717    function generatePassword($pattern='CvcdCvc')
718    {
719        $app =& App::getInstance();
720        if (preg_match('/[^xCVcvd]/', $pattern)) {
721            $app->logMsg(sprintf('Invalid pattern: %s', $pattern), LOG_WARNING, __FILE__, __LINE__);
722            $pattern='CvcdCvc';
723        }
724        $str = '';
725        for ($i=0; $i<strlen($pattern); $i++) {
726            $x = substr('bcdfghjklmnprstvwxzBCDFGHJKLMNPRSTVWXZaeiouyAEIOUY0123456789', (mt_rand() % 60), 1);
727            $c = substr('bcdfghjklmnprstvwxz', (mt_rand() % 19), 1);
728            $C = substr('bcdfghjklmnprstvwxzBCDFGHJKLMNPRSTVWXZ', (mt_rand() % 38), 1);
729            $v = substr('aeiouy', (mt_rand() % 6), 1);
730            $V = substr('aeiouyAEIOUY', (mt_rand() % 12), 1);
731            $d = substr('0123456789', (mt_rand() % 10), 1);
732            $str .= $$pattern{$i};
733        }
734        return $str;
735    }
736
737    /**
738     *
739     */
740    function encryptPassword($password, $salt=null)
741    {
742        $app =& App::getInstance();
743       
744        // Existing password hashes rely on the same key/salt being used to compare encryptions.
745        // Don't change this unless you know existing hashes or signatures will not be affected!
746        $more_salt = 'B36D18E5-3FE4-4D58-8150-F26642852B81';
747       
748        switch ($this->_params['encryption_type']) {
749        case AUTH_ENCRYPT_PLAINTEXT :
750            return $password;
751            break;
752
753        case AUTH_ENCRYPT_CRYPT :
754            // If comparing plaintext password with a hash, provide first two chars of the hash as the salt.
755            return isset($salt) ? crypt($password, substr($salt, 0, 2)) : crypt($password);
756            break;
757
758        case AUTH_ENCRYPT_SHA1 :
759            return sha1($password);
760            break;
761
762        case AUTH_ENCRYPT_SHA1_HARDENED :
763            $hash = sha1($app->getParam('signing_key') . $password . $more_salt);
764            // Increase key strength by 12 bits.
765            for ($i=0; $i < 4096; $i++) { 
766                $hash = sha1($hash); 
767            } 
768            return $hash;
769            break;
770
771        case AUTH_ENCRYPT_MD5 :
772            return md5($password);
773            break;
774
775        case AUTH_ENCRYPT_MD5_HARDENED :
776            // Include salt to improve hash
777            $hash = md5($app->getParam('signing_key') . $password . $more_salt);
778            // Increase key strength by 12 bits.
779            for ($i=0; $i < 4096; $i++) { 
780                $hash = md5($hash); 
781            } 
782            return $hash;
783            break;
784        default :
785            $app->logMsg(sprintf('Authentication encrypt type specified is unrecognized: %s', $this->_params['encryption_type']), LOG_NOTICE, __FILE__, __LINE__);
786            return false;
787            break;
788        }
789    }
790
791    /**
792     *
793     */
794    function setPassword($user_id=null, $password)
795    {
796        $app =& App::getInstance();
797        $db =& DB::getInstance();
798   
799        $this->initDB();
800
801        // Get user_id if specified.
802        $user_id = isset($user_id) ? $user_id : $this->get('user_id');
803
804        // Issue the password change query.
805        $db->query("
806            UPDATE " . $this->_params['db_table'] . "
807            SET userpass = '" . $db->escapeString($this->encryptPassword($password)) . "'
808            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
809        ");
810       
811        if (mysql_affected_rows($db->getDBH()) != 1) {
812            $app->logMsg(sprintf('setPassword failed to update password for user %s', $user_id), LOG_NOTICE, __FILE__, __LINE__);
813        }
814    }
815
816    /**
817     * Resets the password for the user with the specified id.
818     *
819     * @param  string $user_id   The id of the user to reset.
820     * @param  string $reason    Additional message to add to the reset email.
821     * @return string            The user's new password.
822     */
823    function resetPassword($user_id=null, $reason='')
824    {
825        $app =& App::getInstance();
826        $db =& DB::getInstance();
827   
828        $this->initDB();
829
830        // Get user_id if specified.
831        $user_id = isset($user_id) ? $user_id : $this->get('user_id');
832
833        // Reset password of a specific user.
834        $qid = $db->query("
835            SELECT * FROM " . $this->_params['db_table'] . "
836            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
837        ");
838        if (!$user_data = mysql_fetch_assoc($qid)) {
839            $app->logMsg(sprintf('Reset password failed. User %s not found.', $user_id), LOG_NOTICE, __FILE__, __LINE__);
840            return false;
841        }
842
843        // Get new password.
844        $password = $this->generatePassword();
845
846        // Update password query.
847        $this->setPassword($user_id, $password);
848
849        // Make sure user has an email on record before continuing.
850        if (!isset($user_data['email']) || '' == trim($user_data['email'])) {
851            $app->logMsg(sprintf('Password reset but notification failed, no email address for user %s (%s).', $user_data[$this->_params['db_primary_key']], $user_data[$this->_params['db_username_column']]), LOG_NOTICE, __FILE__, __LINE__);
852        } else {
853            // Send the new password in an email.
854            $email = new Email(array(
855                'to' => $user_data['email'],
856                'from' => sprintf('%s <%s>', $app->getParam('site_name'), $app->getParam('site_email')),
857                'subject' => sprintf('%s password change', $app->getParam('site_name'))
858            ));
859            $email->setTemplate('codebase/services/templates/email_reset_password.txt');
860            $email->replace(array(
861                'SITE_NAME' => $app->getParam('site_name'),
862                'SITE_URL' => $app->getParam('site_url'),
863                'SITE_EMAIL' => $app->getParam('site_email'),
864                'NAME' => ('' != $user_data['first_name'] . $user_data['last_name'] ? $user_data['first_name'] . ' ' . $user_data['last_name'] : $user_data[$this->_params['db_username_column']]),
865                'USERNAME' => $user_data[$this->_params['db_username_column']],
866                'PASSWORD' => $password,
867                'REASON' => ('' == trim($reason) ? '' : trim($reason) . ' '), // Add a space after the reason if it exists for better fromatting.
868            ));
869            $email->send();
870        }
871
872        return array(
873            'username' => $user_data[$this->_params['db_username_column']],
874            'userpass' => $password
875        );
876    }
877
878    /**
879     * If the current user has access to the specified $security_zone, return true.
880     * If the optional $priv is supplied, test that against the zone.
881     *
882     * @param  constant $security_zone   string of comma delimited priviliges for the zone
883     * @param  string   $priv            a privilege that might be found in a zone
884     * @return bool     true if user is a member of security zone, false otherwise
885     */
886    function inClearanceZone($security_zone, $priv='')
887    {
888        return true;
889        $zone_members = preg_split('/,\s*/', $security_zone);
890        $priv = empty($priv) ? $this->get('priv') : $priv;
891
892        // If the current user's privilege level is NOT in that array or if the
893        // user has no privilege, return false. Otherwise the user is clear.
894        if (!in_array($priv, $zone_members) || empty($priv)) {
895            return false;
896        } else {
897            return true;
898        }
899    }
900
901    /**
902     * This function tests a list of arguments $security_zone against the priv that the current user has.
903     * If the user doesn't have one of the supplied privs, die.
904     *
905     * @param  constant $security_zone   string of comma delimited priviliges for the zone
906     */
907    function requireAccessClearance($security_zone, $message='')
908    {
909        $app =& App::getInstance();
910   
911        return true;
912        $zone_members = preg_split('/,\s*/', $security_zone);
913
914        /* If the current user's privilege level is NOT in that array or if the
915         * user has no privilege, DIE with a message. */
916        if (!in_array($this->get('priv'), $zone_members) || !$this->get('priv')) {
917            $message = empty($message) ? _("You have insufficient privileges to view that page.") : $message;
918            $app->raiseMsg($message, MSG_NOTICE, __FILE__, __LINE__);
919            $app->dieBoomerangURL();
920        }
921    }
922
923} // end class
924
925// CIDR cheat-sheet
926//
927// Netmask              Netmask (binary)                 CIDR     Notes
928// _____________________________________________________________________________
929// 255.255.255.255  11111111.11111111.11111111.11111111  /32  Host (single addr)
930// 255.255.255.254  11111111.11111111.11111111.11111110  /31  Unusable
931// 255.255.255.252  11111111.11111111.11111111.11111100  /30    2  useable
932// 255.255.255.248  11111111.11111111.11111111.11111000  /29    6  useable
933// 255.255.255.240  11111111.11111111.11111111.11110000  /28   14  useable
934// 255.255.255.224  11111111.11111111.11111111.11100000  /27   30  useable
935// 255.255.255.192  11111111.11111111.11111111.11000000  /26   62  useable
936// 255.255.255.128  11111111.11111111.11111111.10000000  /25  126  useable
937// 255.255.255.0    11111111.11111111.11111111.00000000  /24 "Class C" 254 useable
938//
939// 255.255.254.0    11111111.11111111.11111110.00000000  /23    2  Class C's
940// 255.255.252.0    11111111.11111111.11111100.00000000  /22    4  Class C's
941// 255.255.248.0    11111111.11111111.11111000.00000000  /21    8  Class C's
942// 255.255.240.0    11111111.11111111.11110000.00000000  /20   16  Class C's
943// 255.255.224.0    11111111.11111111.11100000.00000000  /19   32  Class C's
944// 255.255.192.0    11111111.11111111.11000000.00000000  /18   64  Class C's
945// 255.255.128.0    11111111.11111111.10000000.00000000  /17  128  Class C's
946// 255.255.0.0      11111111.11111111.00000000.00000000  /16  "Class B"
947//
948// 255.254.0.0      11111111.11111110.00000000.00000000  /15    2  Class B's
949// 255.252.0.0      11111111.11111100.00000000.00000000  /14    4  Class B's
950// 255.248.0.0      11111111.11111000.00000000.00000000  /13    8  Class B's
951// 255.240.0.0      11111111.11110000.00000000.00000000  /12   16  Class B's
952// 255.224.0.0      11111111.11100000.00000000.00000000  /11   32  Class B's
953// 255.192.0.0      11111111.11000000.00000000.00000000  /10   64  Class B's
954// 255.128.0.0      11111111.10000000.00000000.00000000  /9   128  Class B's
955// 255.0.0.0        11111111.00000000.00000000.00000000  /8   "Class A"
956//
957// 254.0.0.0        11111110.00000000.00000000.00000000  /7
958// 252.0.0.0        11111100.00000000.00000000.00000000  /6
959// 248.0.0.0        11111000.00000000.00000000.00000000  /5
960// 240.0.0.0        11110000.00000000.00000000.00000000  /4
961// 224.0.0.0        11100000.00000000.00000000.00000000  /3
962// 192.0.0.0        11000000.00000000.00000000.00000000  /2
963// 128.0.0.0        10000000.00000000.00000000.00000000  /1
964// 0.0.0.0          00000000.00000000.00000000.00000000  /0   IP space
965?>
Note: See TracBrowser for help on using the repository browser.