Ignore:
Timestamp:
Jun 3, 2006 7:47:48 PM (18 years ago)
Author:
scdev
Message:

Q - Merged branches/2.0singleton into trunk. Completed updating classes to use singleton methods. Implemented tests. Fixed some bugs. Changed some interfaces.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/lib/Auth_SQL.inc.php

    r124 r136  
    11<?php
    22/**
    3  * The Auth_SQL:: class provides a SQL implementation for authentication.
     3 * The Auth_SQL class provides a SQL implementation for authentication.
    44 *
    55 * @author  Quinn Comendant <quinn@strangecode.com>
     
    88
    99// Available encryption types for class Auth_SQL.
    10 define('AUTH_ENCRYPT_MD5', 1);
     10define('AUTH_ENCRYPT_PLAINTEXT', 1);
    1111define('AUTH_ENCRYPT_CRYPT', 2);
    1212define('AUTH_ENCRYPT_SHA1', 3);
    13 define('AUTH_ENCRYPT_PLAINTEXT', 4);
     13define('AUTH_ENCRYPT_SHA1_HARDENED', 4);
     14define('AUTH_ENCRYPT_MD5', 5);
     15define('AUTH_ENCRYPT_MD5_HARDENED', 6);
    1416
    1517require_once dirname(__FILE__) . '/Email.inc.php';
    1618
    1719class Auth_SQL {
    18 
    19     var $_auth = '';
    20     var $_sess = '_auth_';
     20       
     21    // Namespace of this auth object.
     22    var $_ns;
     23   
     24    // Static var for test.
    2125    var $_authentication_tested;
     26
     27    // Paramters to be configured by setParam.
    2228    var $_params = array();
    23 
    24     // Default param values.
    2529    var $_default_params = array(
    2630
     
    4145
    4246        // The type of encryption to use for passwords stored in the db_table. Use one of the AUTH_ENCRYPT_* types specified above.
    43         'encryption_type' => AUTH_ENCRYPT_SHA1,
     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,
    4450
    4551        // The URL to the login script.
     
    9096     * @param optional array $params  A hash containing parameters.
    9197     */
    92     function Auth_SQL($auth_name=null)
    93     {
    94         if (isset($auth_name)) {
    95             $this->_auth = $auth_name;
    96             $this->_sess .= $auth_name;
    97         }
     98    function Auth_SQL($namespace='')
     99    {
     100        $app =& App::getInstance();
     101       
     102        $this->_ns = '_auth_' . $namespace;
    98103
    99104        // Initialize default parameters.
     
    101106
    102107        // Get create tables config from global context.
    103         if (!is_null(App::getParam('db_create_tables'))) {
    104             $this->setParam(array('create_table' => App::getParam('db_create_tables')));
     108        if (!is_null($app->getParam('db_create_tables'))) {
     109            $this->setParam(array('create_table' => $app->getParam('db_create_tables')));
    105110        }
    106111    }
     
    115120    function initDB($recreate_db=false)
    116121    {
     122        $app =& App::getInstance();
     123        $db =& DB::getInstance();
     124   
     125   
    117126        static $_db_tested = false;
    118127
     
    121130            // User table.
    122131            if ($recreate_db) {
    123                 DB::query("DROP TABLE IF EXISTS " . $this->getParam('db_table'));
    124                 App::logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_DEBUG, __FILE__, __LINE__);
     132                $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_table'));
     133                $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_DEBUG, __FILE__, __LINE__);
    125134            }
    126135
    127136            // The minimal columns for a table compatable with the Auth_SQL class.
    128             DB::query("CREATE TABLE IF NOT EXISTS " . $this->getParam('db_table') . " (
     137            $db->query("CREATE TABLE IF NOT EXISTS " . $this->getParam('db_table') . " (
    129138                " . $this->getParam('db_primary_key') . " smallint(11) NOT NULL auto_increment,
    130139                " . $this->getParam('db_username_column') . " varchar(255) NOT NULL default '',
     
    152161            )");
    153162
    154             if (!DB::columnExists($this->getParam('db_table'), array(
     163            if (!$db->columnExists($this->getParam('db_table'), array(
    155164                $this->getParam('db_primary_key'),
    156165                $this->getParam('db_username_column'),
     
    173182                'modified_datetime',
    174183            ), false, false)) {
    175                 App::logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__);
     184                $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__);
    176185                trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), E_USER_ERROR);
    177186            }
     
    180189            if ($this->getParam('abuse_detection')) {
    181190                if ($recreate_db) {
    182                     DB::query("DROP TABLE IF EXISTS " . $this->getParam('db_login_table'));
    183                     App::logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_login_table')), LOG_DEBUG, __FILE__, __LINE__);
     191                    $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_login_table'));
     192                    $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_login_table')), LOG_DEBUG, __FILE__, __LINE__);
    184193                }
    185                 DB::query("CREATE TABLE IF NOT EXISTS " . $this->getParam('db_login_table') . " (
     194                $db->query("CREATE TABLE IF NOT EXISTS " . $this->getParam('db_login_table') . " (
    186195                    " . $this->getParam('db_primary_key') . " smallint(11) NOT NULL default '0',
    187196                    login_datetime datetime NOT NULL default '0000-00-00 00:00:00',
     
    192201                )");
    193202
    194                 if (!DB::columnExists($this->getParam('db_login_table'), array(
     203                if (!$db->columnExists($this->getParam('db_login_table'), array(
    195204                    $this->getParam('db_primary_key'),
    196205                    'login_datetime',
    197206                    'remote_ip_binary',
    198207                ), false, false)) {
    199                     App::logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_login_table')), LOG_ALERT, __FILE__, __LINE__);
     208                    $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_login_table')), LOG_ALERT, __FILE__, __LINE__);
    200209                    trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_login_table')), E_USER_ERROR);
    201210                }
     
    228237    function getParam($param)
    229238    {
     239        $app =& App::getInstance();
     240   
    230241        if (isset($this->_params[$param])) {
    231242            return $this->_params[$param];
    232243        } else {
    233             App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
     244            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
    234245            return null;
    235246        }
     
    243254    function clearAuth()
    244255    {
     256        $db =& DB::getInstance();
     257   
    245258        $this->initDB();
    246259
    247         DB::query("
     260        $db->query("
    248261            UPDATE " . $this->_params['db_table'] . " SET
    249262            seconds_online = seconds_online + (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_access_datetime)),
     
    251264            WHERE " . $this->_params['db_primary_key'] . " = '" . $this->getVal('user_id') . "'
    252265        ");
    253         $_SESSION[$this->_sess] = array('authenticated' => false);
     266        $_SESSION[$this->_ns] = array('authenticated' => false);
    254267    }
    255268
     
    263276    function setVal($key, $val)
    264277    {
    265         if (!isset($_SESSION[$this->_sess]['user_data'])) {
    266             $_SESSION[$this->_sess]['user_data'] = array();
    267         }
    268         $_SESSION[$this->_sess]['user_data'][$key] = $val;
     278        if (!isset($_SESSION[$this->_ns]['user_data'])) {
     279            $_SESSION[$this->_ns]['user_data'] = array();
     280        }
     281        $_SESSION[$this->_ns]['user_data'][$key] = $val;
    269282    }
    270283
     
    279292    function getVal($key, $default='')
    280293    {
    281         if (isset($_SESSION[$this->_sess][$key])) {
    282             return $_SESSION[$this->_sess][$key];
    283         } else if (isset($_SESSION[$this->_sess]['user_data'][$key])) {
    284             return $_SESSION[$this->_sess]['user_data'][$key];
     294        if (isset($_SESSION[$this->_ns][$key])) {
     295            return $_SESSION[$this->_ns][$key];
     296        } else if (isset($_SESSION[$this->_ns]['user_data'][$key])) {
     297            return $_SESSION[$this->_ns]['user_data'][$key];
    285298        } else {
    286299            return $default;
     
    298311    function authenticate($username, $password)
    299312    {
     313        $app =& App::getInstance();
     314        $db =& DB::getInstance();
     315
    300316        $this->initDB();
    301317
     
    303319        case AUTH_ENCRYPT_CRYPT :
    304320            // Query DB for user matching credentials. Compare cyphertext with salted-encrypted password.
    305             $qid = DB::query("
     321            $qid = $db->query("
    306322                SELECT *, " . $this->_params['db_primary_key'] . " AS user_id
    307323                FROM " . $this->_params['db_table'] . "
    308                 WHERE " . $this->_params['db_username_column'] . " = '" . DB::escapeString($username) . "'
    309                 AND BINARY userpass = ENCRYPT('" . DB::escapeString($password) . "', LEFT(userpass, 2)))
     324                WHERE " . $this->_params['db_username_column'] . " = '" . $db->escapeString($username) . "'
     325                AND BINARY userpass = ENCRYPT('" . $db->escapeString($password) . "', LEFT(userpass, 2)))
    310326            ");
    311327            break;
     
    315331        default :
    316332            // Query DB for user matching credentials. Directly compare cyphertext with result from encryptPassword().
    317             $qid = DB::query("
     333            $qid = $db->query("
    318334                SELECT *, " . $this->_params['db_primary_key'] . " AS user_id
    319335                FROM " . $this->_params['db_table'] . "
    320                 WHERE " . $this->_params['db_username_column'] . " = '" . DB::escapeString($username) . "'
    321                 AND BINARY userpass = '" . DB::escapeString($this->encryptPassword($password)) . "'
     336                WHERE " . $this->_params['db_username_column'] . " = '" . $db->escapeString($username) . "'
     337                AND BINARY userpass = '" . $db->escapeString($this->encryptPassword($password)) . "'
    322338            ");
    323339            break;
     
    326342        // Return user data if found.
    327343        if ($user_data = mysql_fetch_assoc($qid)) {
    328             App::logMsg(sprintf('Authentication successful for %s %s (%s)', $this->_auth, $user_data['user_id'], $username), LOG_INFO, __FILE__, __LINE__);
     344            $app->logMsg(sprintf('Authentication successful for user %s (%s)', $user_data['user_id'], $username), LOG_INFO, __FILE__, __LINE__);
    329345            return $user_data;
    330346        } else {
    331             App::logMsg(sprintf('Authentication failed for %s %s (encrypted attempted password: %s)', $this->_auth, $username, $this->encryptPassword($password)), LOG_NOTICE, __FILE__, __LINE__);
     347            $app->logMsg(sprintf('Authentication failed for user %s (encrypted attempted password: %s)', $username, $this->encryptPassword($password)), LOG_NOTICE, __FILE__, __LINE__);
    332348            return false;
    333349        }
     
    344360    function login($username, $password)
    345361    {
     362        $app =& App::getInstance();
     363        $db =& DB::getInstance();
     364   
    346365        $this->initDB();
    347366
     
    354373
    355374        // Register authenticated session.
    356         $_SESSION[$this->_sess] = array(
     375        $_SESSION[$this->_ns] = array(
    357376            'authenticated'         => true,
    358377            'user_id'               => $user_data['user_id'],
    359             'auth_name'             => $this->_auth,
    360378            'username'              => $username,
    361379            'login_datetime'        => date('Y-m-d H:i:s'),
     
    372390            if (!empty($user_data['blocked'])) {
    373391
    374                 App::logMsg(sprintf('%s %s (%s) login failed due to blocked account: %s', ucfirst($this->_auth), $this->getVal('user_id'), $this->getVal('username'), $this->getVal('blocked_reason')), LOG_NOTICE, __FILE__, __LINE__);
     392                $app->logMsg(sprintf('User %s (%s) login failed due to blocked account: %s', $this->getVal('user_id'), $this->getVal('username'), $this->getVal('blocked_reason')), LOG_NOTICE, __FILE__, __LINE__);
    375393
    376394                switch ($user_data['blocked_reason']) {
    377395                    case 'account abuse' :
    378                         App::raiseMsg(sprintf(_("This account has been blocked due to possible account abuse. Please contact us to reactivate."), null), MSG_WARNING, __FILE__, __LINE__);
     396                        $app->raiseMsg(sprintf(_("This account has been blocked due to possible account abuse. Please contact us to reactivate."), null), MSG_WARNING, __FILE__, __LINE__);
    379397                        break;
    380398                    default :
    381                         App::raiseMsg(sprintf(_("This account is currently not active. %s"), $user_data['blocked_reason']), MSG_WARNING, __FILE__, __LINE__);
     399                        $app->raiseMsg(sprintf(_("This account is currently not active. %s"), $user_data['blocked_reason']), MSG_WARNING, __FILE__, __LINE__);
    382400                        break;
    383401                }
     
    395413        **/
    396414        if ($this->getParam('abuse_detection') && !$this->getVal('login_abuse_exempt')) {
    397             $qid = DB::query("
     415            $qid = $db->query("
    398416                SELECT COUNT(DISTINCT LEFT(remote_ip_binary, " . $this->_params['login_abuse_ip_bitmask'] . "))
    399417                FROM " . $this->_params['db_login_table'] . "
     
    406424                    // Warn the user with a password reset.
    407425                    $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."));
    408                     App::raiseMsg(_("Your password has been reset as a security precaution. Please check your email for more information."), MSG_NOTICE, __FILE__, __LINE__);
    409                     App::logMsg(sprintf('Account abuse detected for %s %s (%s) from IP %s', $this->_auth, $this->getVal('user_id'), $this->getVal('username'), $this->getVal('remote_ip')), LOG_WARNING, __FILE__, __LINE__);
     426                    $app->raiseMsg(_("Your password has been reset as a security precaution. Please check your email for more information."), MSG_NOTICE, __FILE__, __LINE__);
     427                    $app->logMsg(sprintf('Account abuse detected for user %s (%s) from IP %s', $this->getVal('user_id'), $this->getVal('username'), $this->getVal('remote_ip')), LOG_WARNING, __FILE__, __LINE__);
    410428                } else {
    411429                    // Block the account with the reason of account abuse.
    412430                    $this->blockAccount(null, 'account abuse');
    413                     App::raiseMsg(_("Your account has been blocked as a security precaution. Please contact us for more information."), MSG_NOTICE, __FILE__, __LINE__);
    414                     App::logMsg(sprintf('Account blocked for %s %s (%s) from IP %s', $this->_auth, $this->getVal('user_id'), $this->getVal('username'), $this->getVal('remote_ip')), LOG_ALERT, __FILE__, __LINE__);
     431                    $app->raiseMsg(_("Your account has been blocked as a security precaution. Please contact us for more information."), MSG_NOTICE, __FILE__, __LINE__);
     432                    $app->logMsg(sprintf('Account blocked for user %s (%s) from IP %s', $this->getVal('user_id'), $this->getVal('username'), $this->getVal('remote_ip')), LOG_ALERT, __FILE__, __LINE__);
    415433                }
    416434                // Increment user's warning level.
    417                 DB::query("UPDATE " . $this->_params['db_table'] . " SET abuse_warning_level = abuse_warning_level + 1 WHERE " . $this->_params['db_primary_key'] . " = '" . $this->getVal('user_id') . "'");
     435                $db->query("UPDATE " . $this->_params['db_table'] . " SET abuse_warning_level = abuse_warning_level + 1 WHERE " . $this->_params['db_primary_key'] . " = '" . $this->getVal('user_id') . "'");
    418436                // Reset the login counter for this user.
    419                 DB::query("DELETE FROM " . $this->_params['db_login_table'] . " WHERE " . $this->_params['db_primary_key'] . " = '" . $this->getVal('user_id') . "'");
     437                $db->query("DELETE FROM " . $this->_params['db_login_table'] . " WHERE " . $this->_params['db_primary_key'] . " = '" . $this->getVal('user_id') . "'");
    420438                // No login: reset password because of account abuse!
    421439                $this->clearAuth();
     
    424442
    425443            // Update the login counter table with this login access. Convert IP to binary.
    426             DB::query("
     444            $db->query("
    427445                INSERT INTO " . $this->_params['db_login_table'] . " (
    428446                    " . $this->_params['db_primary_key'] . ",
     
    438456
    439457        // Update user table with this login.
    440         DB::query("
     458        $db->query("
    441459            UPDATE " . $this->_params['db_table'] . " SET
    442460                last_login_datetime = '" . $this->getVal('login_datetime') . "',
     
    462480    function isLoggedIn($user_id=null)
    463481    {
     482        $app =& App::getInstance();
     483        $db =& DB::getInstance();
     484   
    464485        $this->initDB();
    465486
    466487        if (isset($user_id)) {
    467488            // Check the login status of a specific user.
    468             $qid = DB::query("
     489            $qid = $db->query("
    469490                SELECT 1 FROM " . $this->_params['db_table'] . "
    470                 WHERE " . $this->_params['db_primary_key'] . " = '" . DB::escapeString($user_id) . "'
     491                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
    471492                AND DATE_ADD(last_login_datetime, INTERVAL '" . $this->_params['login_timeout'] . "' SECOND) > NOW()
    472493                AND DATE_ADD(last_access_datetime, INTERVAL '" . $this->_params['idle_timeout'] . "' SECOND) > NOW()
     
    476497
    477498        // User login test need only be run once per script execution. We cache the result in the session.
    478         if ($this->_authentication_tested && isset($_SESSION[$this->_sess]['authenticated'])) {
    479             return $_SESSION[$this->_sess]['authenticated'];
     499        if ($this->_authentication_tested && isset($_SESSION[$this->_ns]['authenticated'])) {
     500            return $_SESSION[$this->_ns]['authenticated'];
    480501        }
    481502
     
    486507        if ($trusted_net = ipInRange(getRemoteAddr(), $this->_params['trusted_networks'])) {
    487508            $user_in_trusted_network = true;
    488             App::logMsg(sprintf('%s%s accessing from trusted network %s',
    489                 ucfirst($this->_auth),
     509            $app->logMsg(sprintf('User %s accessing from trusted network %s',
    490510                ($this->getVal('user_id') ? ' ' . $this->getVal('user_id') . ' (' .  $this->getVal('username') . ')' : ''),
    491511                $trusted_net
     
    493513        } else if (preg_match('/proxy.aol.com$/i', getRemoteAddr(true))) {
    494514            $user_in_trusted_network = true;
    495             App::logMsg(sprintf('%s%s accessing from trusted network proxy.aol.com',
    496                 ucfirst($this->_auth),
     515            $app->logMsg(sprintf('User %s accessing from trusted network proxy.aol.com',
    497516                ($this->getVal('user_id') ? ' ' . $this->getVal('user_id') . ' (' .  $this->getVal('username') . ')' : '')
    498517            ), LOG_DEBUG, __FILE__, __LINE__);
     
    502521
    503522        // Test login with information stored in session. Skip IP matching for users from trusted networks.
    504         if (isset($_SESSION[$this->_sess])
    505             && true === $_SESSION[$this->_sess]['authenticated']
    506             && !empty($_SESSION[$this->_sess]['username'])
    507             && strtotime($_SESSION[$this->_sess]['login_datetime']) > time() - $this->_params['login_timeout']
    508             && strtotime($_SESSION[$this->_sess]['last_access_datetime']) > time() - $this->_params['idle_timeout']
    509             && ($_SESSION[$this->_sess]['remote_ip'] == getRemoteAddr() || $user_in_trusted_network)
     523        if (isset($_SESSION[$this->_ns])
     524            && true === $_SESSION[$this->_ns]['authenticated']
     525            && !empty($_SESSION[$this->_ns]['username'])
     526            && strtotime($_SESSION[$this->_ns]['login_datetime']) > time() - $this->_params['login_timeout']
     527            && strtotime($_SESSION[$this->_ns]['last_access_datetime']) > time() - $this->_params['idle_timeout']
     528            && ($_SESSION[$this->_ns]['remote_ip'] == getRemoteAddr() || $user_in_trusted_network)
    510529        ) {
    511530            // User is authenticated!
    512             $_SESSION[$this->_sess]['last_access_datetime'] = date('Y-m-d H:i:s');
     531            $_SESSION[$this->_ns]['last_access_datetime'] = date('Y-m-d H:i:s');
    513532
    514533            // Update the DB with the last_access_datetime and increment the seconds_online.
    515             DB::query("
     534            $db->query("
    516535                UPDATE " . $this->_params['db_table'] . " SET
    517536                seconds_online = seconds_online + (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_access_datetime)) + 1,
     
    519538                WHERE " . $this->_params['db_primary_key'] . " = '" . $this->getVal('user_id') . "'
    520539            ");
    521             if (mysql_affected_rows(DB::getDBH()) > 0) {
     540            if (mysql_affected_rows($db->getDBH()) > 0) {
    522541                // 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.
    523542                return true;
    524543            } else {
    525                 App::logMsg(sprintf('User update failed. Record not found for %s %s (%s).', $this->_auth, $this->getVal('user_id'), $this->getVal('username')), LOG_NOTICE, __FILE__, __LINE__);
    526             }
    527         } else if (isset($_SESSION[$this->_sess]) && true === $_SESSION[$this->_sess]['authenticated']) {
     544                $app->logMsg(sprintf('User update failed. Record not found for user %s (%s).', $this->getVal('user_id'), $this->getVal('username')), LOG_NOTICE, __FILE__, __LINE__);
     545            }
     546        } else if (isset($_SESSION[$this->_ns]) && true === $_SESSION[$this->_ns]['authenticated']) {
    528547            // User is authenticated, but login has expired.
    529             if (strtotime($_SESSION[$this->_sess]['last_access_datetime']) > time() - 43200) {
     548            if (strtotime($_SESSION[$this->_ns]['last_access_datetime']) > time() - 43200) {
    530549                // Only raise message if last session is less than 12 hours old.
    531                 App::raiseMsg(sprintf(_("Your %s session has closed. You need to log-in again."), strtolower($this->_auth)), MSG_NOTICE, __FILE__, __LINE__);
     550                $app->raiseMsg(_("Your session has expired. You need to log-in again."), MSG_NOTICE, __FILE__, __LINE__);
    532551            }
    533552
    534553            // Log the reason for login expiration.
    535554            $expire_reasons = array();
    536             if (empty($_SESSION[$this->_sess]['username'])) {
     555            if (empty($_SESSION[$this->_ns]['username'])) {
    537556                $expire_reasons[] = 'username not found';
    538557            }
    539             if (strtotime($_SESSION[$this->_sess]['login_datetime']) <= time() - $this->_params['login_timeout']) {
     558            if (strtotime($_SESSION[$this->_ns]['login_datetime']) <= time() - $this->_params['login_timeout']) {
    540559                $expire_reasons[] = 'login_timeout expired';
    541560            }
    542             if (strtotime($_SESSION[$this->_sess]['last_access_datetime']) <= time() - $this->_params['idle_timeout']) {
     561            if (strtotime($_SESSION[$this->_ns]['last_access_datetime']) <= time() - $this->_params['idle_timeout']) {
    543562                $expire_reasons[] = 'idle_timeout expired';
    544563            }
    545             if ($_SESSION[$this->_sess]['remote_ip'] != getRemoteAddr() && !$user_in_trusted_network) {
    546                 $expire_reasons[] = sprintf('remote_ip not matched (%s != %s)', $_SESSION[$this->_sess]['remote_ip'], getRemoteAddr());
    547             }
    548             App::logMsg(sprintf('%s %s (%s) session expired: %s', ucfirst($this->_auth), $this->getVal('user_id'), $this->getVal('username'), join(', ', $expire_reasons)), LOG_INFO, __FILE__, __LINE__);
     564            if ($_SESSION[$this->_ns]['remote_ip'] != getRemoteAddr() && !$user_in_trusted_network) {
     565                $expire_reasons[] = sprintf('remote_ip not matched (%s != %s)', $_SESSION[$this->_ns]['remote_ip'], getRemoteAddr());
     566            }
     567            $app->logMsg(sprintf('User %s (%s) session expired: %s', $this->getVal('user_id'), $this->getVal('username'), join(', ', $expire_reasons)), LOG_INFO, __FILE__, __LINE__);
    549568        }
    550569
     
    566585    function requireLogin($message='', $type=MSG_NOTICE, $file=null, $line=null)
    567586    {
     587        $app =& App::getInstance();
     588   
    568589        if (!$this->isLoggedIn()) {
    569590            // Display message for requiring login. (RaiseMsg will ignore empty strings.)
    570             App::raiseMsg($message, $type, $file, $line);
     591            $app->raiseMsg($message, $type, $file, $line);
    571592
    572593            // Login scripts must have the same 'login' tag for boomerangURL verification/manipulation.
    573             App::setBoomerangURL(absoluteMe(), 'login');
    574             App::dieURL($this->_params['login_url']);
     594            $app->setBoomerangURL(absoluteMe(), 'login');
     595            $app->dieURL($this->_params['login_url']);
    575596        }
    576597    }
     
    584605    function blockAccount($user_id=null, $reason='')
    585606    {
     607        $app =& App::getInstance();
     608        $db =& DB::getInstance();
     609   
    586610        $this->initDB();
    587611
    588612        if ($this->getParam('blocking')) {
    589             if (strlen(DB::escapeString($reason)) > 255) {
     613            if (strlen($db->escapeString($reason)) > 255) {
    590614                // blocked_reason field is varchar(255).
    591                 App::logMsg(sprintf('Blocked reason provided is greater than 255 characters: %s', $reason), LOG_WARNING, __FILE__, __LINE__);
     615                $app->logMsg(sprintf('Blocked reason provided is greater than 255 characters: %s', $reason), LOG_WARNING, __FILE__, __LINE__);
    592616            }
    593617
    594618            // Get user_id if specified.
    595619            $user_id = isset($user_id) ? $user_id : $this->getVal('user_id');
    596             DB::query("
     620            $db->query("
    597621                UPDATE " . $this->_params['db_table'] . " SET
    598622                blocked = 'true',
    599                 blocked_reason = '" . DB::escapeString($reason) . "'
    600                 WHERE " . $this->_params['db_primary_key'] . " = '" . DB::escapeString($user_id) . "'
     623                blocked_reason = '" . $db->escapeString($reason) . "'
     624                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
    601625            ");
    602626        }
     
    608632    function unblockAccount($user_id=null)
    609633    {
     634        $db =& DB::getInstance();
     635   
    610636        $this->initDB();
    611 
     637   
    612638        if ($this->getParam('blocking')) {
    613639            // Get user_id if specified.
    614640            $user_id = isset($user_id) ? $user_id : $this->getVal('user_id');
    615             DB::query("
     641            $db->query("
    616642                UPDATE " . $this->_params['db_table'] . " SET
    617643                blocked = '',
    618644                blocked_reason = ''
    619                 WHERE " . $this->_params['db_primary_key'] . " = '" . DB::escapeString($user_id) . "'
     645                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
    620646            ");
    621647        }
     
    630656    function usernameExists($username)
    631657    {
     658        $db =& DB::getInstance();
     659   
    632660        $this->initDB();
    633661
    634         $qid = DB::query("
     662        $qid = $db->query("
    635663            SELECT 1
    636664            FROM " . $this->_params['db_table'] . "
    637             WHERE " . $this->_params['db_username_column'] . " = '" . DB::escapeString($username) . "'
     665            WHERE " . $this->_params['db_username_column'] . " = '" . $db->escapeString($username) . "'
    638666        ");
    639667        return (mysql_num_rows($qid) > 0);
     
    648676    function getUsername($user_id)
    649677    {
     678        $db =& DB::getInstance();
     679   
    650680        $this->initDB();
    651681
    652         $qid = DB::query("
     682        $qid = $db->query("
    653683            SELECT " . $this->_params['db_username_column'] . "
    654684            FROM " . $this->_params['db_table'] . "
    655             WHERE " . $this->_params['db_primary_key'] . " = '" . DB::escapeString($user_id) . "'
     685            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
    656686        ");
    657687        if (list($username) = mysql_fetch_row($qid)) {
     
    698728    function encryptPassword($password, $salt=null)
    699729    {
     730        $app =& App::getInstance();
     731       
     732        // Existing password hashes rely on the same key/salt being used to compare encryptions.
     733        // Don't change this unless you know existing hashes or signatures will not be affected!
     734        $more_salt = 'B36D18E5-3FE4-4D58-8150-F26642852B81';
     735       
    700736        switch ($this->_params['encryption_type']) {
    701737        case AUTH_ENCRYPT_PLAINTEXT :
     
    709745
    710746        case AUTH_ENCRYPT_SHA1 :
    711             return sha1(App::getParam('signing_key') . sha1($password));
     747            return sha1($password);
    712748            break;
    713749
     750        case AUTH_ENCRYPT_SHA1_HARDENED :
     751            $hash = sha1($app->getParam('signing_key') . $password . $more_salt);
     752            // Increase key strength by 12 bits.
     753            for ($i=0; $i < 4096; $i++) {
     754                $hash = sha1($hash);
     755            }
     756            return $hash;
     757            break;
     758
    714759        case AUTH_ENCRYPT_MD5 :
     760            return md5($password);
     761            break;
     762
     763        case AUTH_ENCRYPT_MD5_HARDENED :
     764            // Include salt to improve hash
     765            $hash = md5($app->getParam('signing_key') . $password . $more_salt);
     766            // Increase key strength by 12 bits.
     767            for ($i=0; $i < 4096; $i++) {
     768                $hash = md5($hash);
     769            }
     770            return $hash;
     771            break;
    715772        default :
    716             return md5(App::getParam('signing_key') . md5($password));
     773            $app->logMsg(sprintf('Authentication encrypt type specified is unrecognized: %s', $this->_params['encryption_type']), LOG_NOTICE, __FILE__, __LINE__);
     774            return false;
    717775            break;
    718776        }
     
    724782    function setPassword($user_id=null, $password)
    725783    {
     784        $app =& App::getInstance();
     785        $db =& DB::getInstance();
     786   
    726787        $this->initDB();
    727788
     
    730791
    731792        // Issue the password change query.
    732         DB::query("
     793        $db->query("
    733794            UPDATE " . $this->_params['db_table'] . "
    734             SET userpass = '" . DB::escapeString($this->encryptPassword($password)) . "'
    735             WHERE " . $this->_params['db_primary_key'] . " = '" . DB::escapeString($user_id) . "'
     795            SET userpass = '" . $db->escapeString($this->encryptPassword($password)) . "'
     796            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
    736797        ");
    737798       
    738         if (mysql_affected_rows(DB::getDBH()) != 1) {
    739             App::logMsg(sprintf('setPassword failed to update password for user %s', $user_id), LOG_NOTICE, __FILE__, __LINE__);
     799        if (mysql_affected_rows($db->getDBH()) != 1) {
     800            $app->logMsg(sprintf('setPassword failed to update password for user %s', $user_id), LOG_NOTICE, __FILE__, __LINE__);
    740801        }
    741802    }
     
    750811    function resetPassword($user_id=null, $reason='')
    751812    {
     813        $app =& App::getInstance();
     814        $db =& DB::getInstance();
     815   
    752816        $this->initDB();
    753817
     
    756820
    757821        // Reset password of a specific user.
    758         $qid = DB::query("
     822        $qid = $db->query("
    759823            SELECT * FROM " . $this->_params['db_table'] . "
    760             WHERE " . $this->_params['db_primary_key'] . " = '" . DB::escapeString($user_id) . "'
     824            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
    761825        ");
    762826        if (!$user_data = mysql_fetch_assoc($qid)) {
    763             App::logMsg(sprintf('Reset password failed. %s %s not found.', ucfirst($this->_auth), $user_id), LOG_NOTICE, __FILE__, __LINE__);
     827            $app->logMsg(sprintf('Reset password failed. User %s not found.', $user_id), LOG_NOTICE, __FILE__, __LINE__);
    764828            return false;
    765829        }
     
    773837        // Make sure user has an email on record before continuing.
    774838        if (!isset($user_data['email']) || '' == trim($user_data['email'])) {
    775             App::logMsg(sprintf('Password reset but notification failed, no email address for %s %s (%s).', $this->_auth, $user_data[$this->_params['db_primary_key']], $user_data[$this->_params['db_username_column']]), LOG_NOTICE, __FILE__, __LINE__);
     839            $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__);
    776840        } else {
    777841            // Body for email.
     
    794858            $email = new Email(array(
    795859                'to' => $user_data['email'],
    796                 'from' => sprintf('%s <%s>', App::getParam('site_name'), App::getParam('site_email')),
    797                 'subject' => sprintf('%s password change', App::getParam('site_name'))
     860                'from' => sprintf('%s <%s>', $app->getParam('site_name'), $app->getParam('site_email')),
     861                'subject' => sprintf('%s password change', $app->getParam('site_name'))
    798862            ));
    799863            $email->setString($email_body);
    800864            $email->replace(array(
    801                 'site_name' => App::getParam('site_name'),
    802                 'site_url' => App::getParam('site_url'),
     865                'site_name' => $app->getParam('site_name'),
     866                'site_url' => $app->getParam('site_url'),
    803867                'name' => ('' != $user_data['first_name'] . $user_data['last_name'] ? $user_data['first_name'] . ' ' . $user_data['last_name'] : $user_data[$this->_params['db_username_column']]),
    804868                'username' => $user_data[$this->_params['db_username_column']],
     
    846910    function requireAccessClearance($security_zone, $message='')
    847911    {
     912        $app =& App::getInstance();
     913   
    848914        return true;
    849915        $zone_members = preg_split('/,\s*/', $security_zone);
     
    853919        if (!in_array($this->getVal('priv'), $zone_members) || !$this->getVal('priv')) {
    854920            $message = empty($message) ? _("You have insufficient privileges to view that page.") : $message;
    855             App::raiseMsg($message, MSG_NOTICE, __FILE__, __LINE__);
    856             App::dieBoomerangURL();
     921            $app->raiseMsg($message, MSG_NOTICE, __FILE__, __LINE__);
     922            $app->dieBoomerangURL();
    857923        }
    858924    }
Note: See TracChangeset for help on using the changeset viewer.