Ignore:
Timestamp:
Nov 30, 2013 7:30:44 PM (11 years ago)
Author:
anonymous
Message:

added public and private keywords to all properties and methods, changed old classname constructor function to construct, removed more ?> closing tags

File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/eli_branch/lib/Auth_File.inc.php

    r396 r439  
    44 * For details visit the project site: <http://trac.strangecode.com/codebase/>
    55 * Copyright 2001-2012 Strangecode, LLC
    6  * 
     6 *
    77 * This file is part of The Strangecode Codebase.
    88 *
     
    1111 * Free Software Foundation, either version 3 of the License, or (at your option)
    1212 * any later version.
    13  * 
     13 *
    1414 * The Strangecode Codebase is distributed in the hope that it will be useful, but
    1515 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1616 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
    1717 * details.
    18  * 
     18 *
    1919 * You should have received a copy of the GNU General Public License along with
    2020 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
     
    3030 * @version 1.2
    3131 */
    32  
     32
    3333// Usage example:
    3434// $auth = new Auth_File();
     
    4747
    4848class Auth_File {
    49    
     49
    5050    // Namespace of this auth object.
    51     var $_ns;
    52    
     51    private $_ns;
     52
    5353    // Parameters to be specified by setParam().
    54     var $_params = array();
    55     var $_default_params = array(
    56        
    57         // Full path to htpasswd file.
    58         'htpasswd_file' => null,
    59 
    60         // The type of encryption to use for passwords stored in the db_table. Use one of the AUTH_ENCRYPT_* types specified above.
    61         'encryption_type' => AUTH_ENCRYPT_CRYPT,
    62 
    63         // The URL to the login script.
    64         'login_url' => '/',
    65 
    66         // The maximum amount of time a user is allowed to be logged in. They will be forced to login again if they expire.
    67         // This applies to admins and users. In seconds. 21600 seconds = 6 hours.
    68         'login_timeout' => 21600,
    69 
    70         // 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.
    71         // This applies to admins and users. In seconds. 3600 seconds = 1 hour.
    72         'idle_timeout' => 3600,
    73 
    74         // An array of IP blocks that are bypass the remote_ip comparison check. Useful for dynamic IPs or those behind proxy servers.
    75         'trusted_networks' => array(),
    76     );
     54    private $_params = array();
     55    private $_default_params = array(
     56
     57    // Full path to htpasswd file.
     58    'htpasswd_file' => null,
     59
     60    // The type of encryption to use for passwords stored in the db_table. Use one of the AUTH_ENCRYPT_* types specified above.
     61    'encryption_type' => AUTH_ENCRYPT_CRYPT,
     62
     63    // The URL to the login script.
     64    'login_url' => '/',
     65
     66    // The maximum amount of time a user is allowed to be logged in. They will be forced to login again if they expire.
     67    // This applies to admins and users. In seconds. 21600 seconds = 6 hours.
     68    'login_timeout' => 21600,
     69
     70    // 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.
     71    // This applies to admins and users. In seconds. 3600 seconds = 1 hour.
     72    'idle_timeout' => 3600,
     73
     74    // An array of IP blocks that are bypass the remote_ip comparison check. Useful for dynamic IPs or those behind proxy servers.
     75    'trusted_networks' => array(), );
    7776
    7877    // Associative array of usernames to hashed passwords.
    79     var $_users = array();
     78    private $_users = array();
    8079
    8180    /**
     
    8685     * @param optional array $params  A hash containing parameters.
    8786     */
    88     function Auth_File($namespace='')
    89     {
    90         $this->_ns = $namespace;
     87    public function __construct($namespace = '') {
     88        $this -> _ns = $namespace;
    9189
    9290        // Initialize default parameters.
    93         $this->setParam($this->_default_params);
     91        $this -> setParam($this -> _default_params);
    9492    }
    9593
     
    10098     * @return bool true on success, false on failure
    10199     */
    102     function setParam($params)
    103     {
     100    public function setParam($params) {
    104101        if (isset($params) && is_array($params)) {
    105102            // Merge new parameters with old overriding only those passed.
    106             $this->_params = array_merge($this->_params, $params);
     103            $this -> _params = array_merge($this -> _params, $params);
    107104        }
    108105    }
     
    115112     * @return mixed               Configured parameter value.
    116113     */
    117     function getParam($param)
    118     {
    119         $app =& App::getInstance();
    120    
    121         if (isset($this->_params[$param])) {
    122             return $this->_params[$param];
     114    public function getParam($param) {
     115        $app = &App::getInstance();
     116
     117        if (isset($this -> _params[$param])) {
     118            return $this -> _params[$param];
    123119        } else {
    124             $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
     120            $app -> logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
    125121            return null;
    126122        }
     
    132128     * @access public
    133129     */
    134     function clear()
    135     {
    136         $_SESSION['_auth_file'][$this->_ns] = array('authenticated' => false);
    137     }
    138 
     130    public function clear() {
     131        $_SESSION['_auth_file'][$this -> _ns] = array('authenticated' => false);
     132    }
    139133
    140134    /**
     
    145139     * @param mixed $val      Value to set variable to.
    146140     */
    147     function set($key, $val)
    148     {
    149         if (!isset($_SESSION['_auth_file'][$this->_ns]['user_data'])) {
    150             $_SESSION['_auth_file'][$this->_ns]['user_data'] = array();
    151         }
    152         $_SESSION['_auth_file'][$this->_ns]['user_data'][$key] = $val;
     141    public function set($key, $val) {
     142        if (!isset($_SESSION['_auth_file'][$this -> _ns]['user_data'])) {
     143            $_SESSION['_auth_file'][$this -> _ns]['user_data'] = array();
     144        }
     145        $_SESSION['_auth_file'][$this -> _ns]['user_data'][$key] = $val;
    153146    }
    154147
     
    161154     * @return mixed          Value stored in session.
    162155     */
    163     function get($key, $default='')
    164     {
    165         if (isset($_SESSION['_auth_file'][$this->_ns][$key])) {
    166             return $_SESSION['_auth_file'][$this->_ns][$key];
    167         } else if (isset($_SESSION['_auth_file'][$this->_ns]['user_data'][$key])) {
    168             return $_SESSION['_auth_file'][$this->_ns]['user_data'][$key];
     156    public function get($key, $default = '') {
     157        if (isset($_SESSION['_auth_file'][$this -> _ns][$key])) {
     158            return $_SESSION['_auth_file'][$this -> _ns][$key];
     159        } else if (isset($_SESSION['_auth_file'][$this -> _ns]['user_data'][$key])) {
     160            return $_SESSION['_auth_file'][$this -> _ns]['user_data'][$key];
    169161        } else {
    170162            return $default;
    171163        }
    172164    }
     165
    173166    /**
    174167     * Find out if a set of login credentials are valid. Only supports
     
    182175     * @return boolean  Whether or not the credentials are valid.
    183176     */
    184     function authenticate($username, $password)
    185     {
    186         $app =& App::getInstance();
    187    
     177    public function authenticate($username, $password) {
     178        $app = &App::getInstance();
     179
    188180        if ('' == trim($password)) {
    189             $app->logMsg(_("No password provided for authentication."), LOG_INFO, __FILE__, __LINE__);
    190             return false;
    191         }
    192        
     181            $app -> logMsg(_("No password provided for authentication."), LOG_INFO, __FILE__, __LINE__);
     182            return false;
     183        }
     184
    193185        // Load users file.
    194         $this->_loadHTPasswdFile();
    195 
    196         if (!isset($this->_users[$username])) {
    197             $app->logMsg(_("User ID provided does not exist."), LOG_INFO, __FILE__, __LINE__);
    198             return false;
    199         }
    200 
    201         if ($this->_encrypt($password, $this->_users[$username]) != $this->_users[$username]) {
    202             $app->logMsg(sprintf('Authentication failed for user %s', $username), LOG_INFO, __FILE__, __LINE__);
    203             return false;
    204         }
    205        
     186        $this -> _loadHTPasswdFile();
     187
     188        if (!isset($this -> _users[$username])) {
     189            $app -> logMsg(_("User ID provided does not exist."), LOG_INFO, __FILE__, __LINE__);
     190            return false;
     191        }
     192
     193        if ($this -> _encrypt($password, $this -> _users[$username]) != $this -> _users[$username]) {
     194            $app -> logMsg(sprintf('Authentication failed for user %s', $username), LOG_INFO, __FILE__, __LINE__);
     195            return false;
     196        }
     197
    206198        // Authentication successful!
    207199        return true;
     
    218210     * @return boolean  Whether or not the credentials are valid.
    219211     */
    220     function login($username, $password)
    221     {
     212    public function login($username, $password) {
    222213        $username = mb_strtolower(trim($username));
    223214
    224         $this->clear();
    225 
    226         if (!$this->authenticate($username, $password)) {
     215        $this -> clear();
     216
     217        if (!$this -> authenticate($username, $password)) {
    227218            // No login: failed authentication!
    228219            return false;
    229220        }
    230        
    231         $_SESSION['_auth_file'][$this->_ns] = array(
    232             'authenticated' => true,
    233             'username' => $username,
    234             'login_datetime' => date('Y-m-d H:i:s'),
    235             'last_access_datetime' => date('Y-m-d H:i:s'),
    236             'remote_ip' => getRemoteAddr()
    237         );
     221
     222        $_SESSION['_auth_file'][$this -> _ns] = array('authenticated' => true, 'username' => $username, 'login_datetime' => date('Y-m-d H:i:s'), 'last_access_datetime' => date('Y-m-d H:i:s'), 'remote_ip' => getRemoteAddr());
    238223
    239224        // We're logged-in!
     
    251236     * @access public
    252237     */
    253     function isLoggedIn()
    254     {
    255         $app =& App::getInstance();
    256    
     238    public function isLoggedIn() {
     239        $app = &App::getInstance();
     240
    257241        // 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.
    258         if ($trusted_net = ipInRange(getRemoteAddr(), $this->_params['trusted_networks'])) {
     242        if ($trusted_net = ipInRange(getRemoteAddr(), $this -> _params['trusted_networks'])) {
    259243            $user_in_trusted_network = true;
    260             $app->logMsg(sprintf('User %s accessing from trusted network %s', $_SESSION['_auth_file'][$this->_ns]['username'], $trusted_net), LOG_DEBUG, __FILE__, __LINE__);
     244            $app -> logMsg(sprintf('User %s accessing from trusted network %s', $_SESSION['_auth_file'][$this -> _ns]['username'], $trusted_net), LOG_DEBUG, __FILE__, __LINE__);
    261245        } else if (preg_match('/proxy.aol.com$/i', getRemoteAddr(true))) {
    262246            $user_in_trusted_network = true;
    263             $app->logMsg(sprintf('User %s accessing from trusted network proxy.aol.com', $_SESSION['_auth_file'][$this->_ns]['username']), LOG_DEBUG, __FILE__, __LINE__);
     247            $app -> logMsg(sprintf('User %s accessing from trusted network proxy.aol.com', $_SESSION['_auth_file'][$this -> _ns]['username']), LOG_DEBUG, __FILE__, __LINE__);
    264248        } else {
    265249            $user_in_trusted_network = false;
     
    267251
    268252        // Test login with information stored in session. Skip IP matching for users from trusted networks.
    269         if (isset($_SESSION['_auth_file'][$this->_ns])
    270             && true === $_SESSION['_auth_file'][$this->_ns]['authenticated']
    271             && !empty($_SESSION['_auth_file'][$this->_ns]['username'])
    272             && strtotime($_SESSION['_auth_file'][$this->_ns]['login_datetime']) > time() - $this->_params['login_timeout']
    273             && strtotime($_SESSION['_auth_file'][$this->_ns]['last_access_datetime']) > time() - $this->_params['idle_timeout']
    274             && ($_SESSION['_auth_file'][$this->_ns]['remote_ip'] == getRemoteAddr() || $user_in_trusted_network)
    275         ) {
     253        if (isset($_SESSION['_auth_file'][$this -> _ns]) && true === $_SESSION['_auth_file'][$this -> _ns]['authenticated'] && !empty($_SESSION['_auth_file'][$this -> _ns]['username']) && strtotime($_SESSION['_auth_file'][$this -> _ns]['login_datetime']) > time() - $this -> _params['login_timeout'] && strtotime($_SESSION['_auth_file'][$this -> _ns]['last_access_datetime']) > time() - $this -> _params['idle_timeout'] && ($_SESSION['_auth_file'][$this -> _ns]['remote_ip'] == getRemoteAddr() || $user_in_trusted_network)) {
    276254            // User is authenticated!
    277             $_SESSION['_auth_file'][$this->_ns]['last_access_datetime'] = date('Y-m-d H:i:s');
     255            $_SESSION['_auth_file'][$this -> _ns]['last_access_datetime'] = date('Y-m-d H:i:s');
    278256            return true;
    279         } else if (isset($_SESSION['_auth_file'][$this->_ns]) && true === $_SESSION['_auth_file'][$this->_ns]['authenticated']) {
    280             if (strtotime($_SESSION['_auth_file'][$this->_ns]['last_access_datetime']) > time() - 43200) {
     257        } else if (isset($_SESSION['_auth_file'][$this -> _ns]) && true === $_SESSION['_auth_file'][$this -> _ns]['authenticated']) {
     258            if (strtotime($_SESSION['_auth_file'][$this -> _ns]['last_access_datetime']) > time() - 43200) {
    281259                // Only raise message if last session is less than 12 hours old.
    282                 $app->raiseMsg(_("Your session has closed. You need to log-in again."), MSG_NOTICE, __FILE__, __LINE__);
     260                $app -> raiseMsg(_("Your session has closed. You need to log-in again."), MSG_NOTICE, __FILE__, __LINE__);
    283261            }
    284262
    285263            // Log the reason for login expiration.
    286264            $expire_reasons = array();
    287             if (empty($_SESSION['_auth_file'][$this->_ns]['username'])) {
     265            if (empty($_SESSION['_auth_file'][$this -> _ns]['username'])) {
    288266                $expire_reasons[] = 'username not found';
    289267            }
    290             if (strtotime($_SESSION['_auth_file'][$this->_ns]['login_datetime']) <= time() - $this->_params['login_timeout']) {
     268            if (strtotime($_SESSION['_auth_file'][$this -> _ns]['login_datetime']) <= time() - $this -> _params['login_timeout']) {
    291269                $expire_reasons[] = 'login_timeout expired';
    292270            }
    293             if (strtotime($_SESSION['_auth_file'][$this->_ns]['last_access_datetime']) <= time() - $this->_params['idle_timeout']) {
     271            if (strtotime($_SESSION['_auth_file'][$this -> _ns]['last_access_datetime']) <= time() - $this -> _params['idle_timeout']) {
    294272                $expire_reasons[] = 'idle_timeout expired';
    295273            }
    296             if ($_SESSION['_auth_file'][$this->_ns]['remote_ip'] != getRemoteAddr() && !$user_in_trusted_network) {
    297                 $expire_reasons[] = sprintf('remote_ip not matched (%s != %s)', $_SESSION['_auth_file'][$this->_ns]['remote_ip'], getRemoteAddr());
    298             }
    299             $app->logMsg(sprintf('User %s session expired: %s', $_SESSION['_auth_file'][$this->_ns]['username'], join(', ', $expire_reasons)), LOG_INFO, __FILE__, __LINE__);
     274            if ($_SESSION['_auth_file'][$this -> _ns]['remote_ip'] != getRemoteAddr() && !$user_in_trusted_network) {
     275                $expire_reasons[] = sprintf('remote_ip not matched (%s != %s)', $_SESSION['_auth_file'][$this -> _ns]['remote_ip'], getRemoteAddr());
     276            }
     277            $app -> logMsg(sprintf('User %s session expired: %s', $_SESSION['_auth_file'][$this -> _ns]['username'], join(', ', $expire_reasons)), LOG_INFO, __FILE__, __LINE__);
    300278        }
    301279
     
    313291     * @access public
    314292     */
    315     function requireLogin($message='', $type=MSG_NOTICE, $file=null, $line=null)
    316     {
    317         $app =& App::getInstance();
    318    
    319         if (!$this->isLoggedIn()) {
     293    public function requireLogin($message = '', $type = MSG_NOTICE, $file = null, $line = null) {
     294        $app = &App::getInstance();
     295
     296        if (!$this -> isLoggedIn()) {
    320297            // Display message for requiring login. (RaiseMsg will ignore empty strings.)
    321             $app->raiseMsg($message, $type, $file, $line);
     298            $app -> raiseMsg($message, $type, $file, $line);
    322299
    323300            // Login scripts must have the same 'login' tag for boomerangURL verification/manipulation.
    324             $app->setBoomerangURL(absoluteMe(), 'login');
    325             $app->dieURL($this->_params['login_url']);
    326         }
    327     }
    328    
     301            $app -> setBoomerangURL(absoluteMe(), 'login');
     302            $app -> dieURL($this -> _params['login_url']);
     303        }
     304    }
     305
    329306    /**
    330307     * Wrapper function for compatibility with lib/Lock.inc.php.
     
    333310     * @return string               Username, or false if none found.
    334311     */
    335     function getUsername($username)
    336     {
     312    public function getUsername($username) {
    337313        if ('' != $username) {
    338314            return $username;
     
    343319
    344320    /*
    345     * Reads the configured htpasswd file into the _users array.
    346     *
    347     * @access   public
    348     * @return   false on error, true on success.
    349     * @author   Quinn Comendant <quinn@strangecode.com>
    350     * @version  1.0
    351     * @since    18 Apr 2006 18:17:48
    352     */
    353     function _loadHTPasswdFile()
    354     {
    355         $app =& App::getInstance();
    356    
     321     * Reads the configured htpasswd file into the _users array.
     322     *
     323     * @access   public
     324     * @return   false on error, true on success.
     325     * @author   Quinn Comendant <quinn@strangecode.com>
     326     * @version  1.0
     327     * @since    18 Apr 2006 18:17:48
     328     */
     329    private function _loadHTPasswdFile() {
     330        $app = &App::getInstance();
     331
    357332        static $users = null;
    358        
    359         if (!file_exists($this->_params['htpasswd_file'])) {
    360             $app->logMsg(sprintf('htpasswd file missing or not specified: %s', $this->_params['htpasswd_file']), LOG_ERR, __FILE__, __LINE__);
    361             return false;
    362         }
    363        
     333
     334        if (!file_exists($this -> _params['htpasswd_file'])) {
     335            $app -> logMsg(sprintf('htpasswd file missing or not specified: %s', $this -> _params['htpasswd_file']), LOG_ERR, __FILE__, __LINE__);
     336            return false;
     337        }
     338
    364339        if (!isset($users)) {
    365             if (false === ($users = file($this->_params['htpasswd_file']))) {
    366                 $app->logMsg(sprintf('Could not read htpasswd file: %s', $this->_params['htpasswd_file']), LOG_ERR, __FILE__, __LINE__);
     340            if (false === ($users = file($this -> _params['htpasswd_file']))) {
     341                $app -> logMsg(sprintf('Could not read htpasswd file: %s', $this -> _params['htpasswd_file']), LOG_ERR, __FILE__, __LINE__);
    367342                return false;
    368343            }
     
    372347            foreach ($users as $u) {
    373348                list($user, $pass) = explode(':', $u, 2);
    374                 $this->_users[trim($user)] = trim($pass);
     349                $this -> _users[trim($user)] = trim($pass);
    375350            }
    376351            return true;
     
    388363     * @return string  The hashed password.
    389364     */
    390     function _encrypt($password, $encrypted_password=null)
    391     {
     365    private function _encrypt($password, $encrypted_password = null) {
    392366        switch ($this->_params['encryption_type']) {
    393         case AUTH_ENCRYPT_PLAINTEXT :
    394             return $password;
    395             break;
    396 
    397         case AUTH_ENCRYPT_SHA1 :
    398             return sha1($password);
    399             break;
    400 
    401         case AUTH_ENCRYPT_MD5 :
    402             return md5($password);
    403             break;
    404 
    405         case AUTH_ENCRYPT_CRYPT :
    406         default :
    407             return crypt($password, $encrypted_password);
    408             break;
     367            case AUTH_ENCRYPT_PLAINTEXT :
     368                return $password;
     369                break;
     370
     371            case AUTH_ENCRYPT_SHA1 :
     372                return sha1($password);
     373                break;
     374
     375            case AUTH_ENCRYPT_MD5 :
     376                return md5($password);
     377                break;
     378
     379            case AUTH_ENCRYPT_CRYPT :
     380            default :
     381                return crypt($password, $encrypted_password);
     382                break;
    409383        }
    410384    }
    411385
    412386} // end class
    413 ?>
Note: See TracChangeset for help on using the changeset viewer.