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

Last change on this file since 682 was 674, checked in by anonymous, 5 years ago

Add user.cli.php and supporting changes

File size: 52.9 KB
RevLine 
[1]1<?php
2/**
[362]3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
[396]5 * Copyright 2001-2012 Strangecode, LLC
[453]6 *
[362]7 * This file is part of The Strangecode Codebase.
[1]8 *
[362]9 * The Strangecode Codebase is free software: you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your option)
12 * any later version.
[453]13 *
[362]14 * The Strangecode Codebase is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * details.
[453]18 *
[362]19 * You should have received a copy of the GNU General Public License along with
20 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
[1]21 */
22
[362]23/*
24* The Auth_SQL class provides a SQL implementation for authentication.
25*
26* @author  Quinn Comendant <quinn@strangecode.com>
27* @version 2.1
28*/
29
[43]30require_once dirname(__FILE__) . '/Email.inc.php';
31
[502]32class Auth_SQL
33{
[501]34    // Available hash types for class Auth_SQL.
[468]35    const ENCRYPT_PLAINTEXT = 1;
36    const ENCRYPT_CRYPT = 2;
37    const ENCRYPT_SHA1 = 3;
38    const ENCRYPT_SHA1_HARDENED = 4;
39    const ENCRYPT_MD5 = 5;
40    const ENCRYPT_MD5_HARDENED = 6;
[500]41    const ENCRYPT_PASSWORD_BCRYPT = 7;
42    const ENCRYPT_PASSWORD_DEFAULT = 8;
[468]43
[136]44    // Namespace of this auth object.
[484]45    protected $_ns;
[453]46
[136]47    // Static var for test.
[484]48    protected $_authentication_tested;
[1]49
[334]50    // Parameters to be configured by setParam.
[484]51    protected $_params = array();
52    protected $_default_params = array(
[42]53
[1]54        // Automatically create table and verify columns. Better set to false after site launch.
[396]55        // This value is overwritten by the $app->getParam('db_create_tables') setting if it is available.
[1]56        'create_table' => true,
[42]57
[1]58        // The database table containing users to authenticate.
59        'db_table' => 'user_tbl',
[42]60
[1]61        // The name of the primary key for the db_table.
62        'db_primary_key' => 'user_id',
[42]63
[1]64        // The name of the username key for the db_table.
65        'db_username_column' => 'username',
[42]66
[1]67        // If using the db_login_table feature, specify the db_login_table. The primary key must match the primary key for the db_table.
[14]68        'db_login_table' => 'user_login_tbl',
[42]69
[501]70        // The type of hash to use for passwords stored in the db_table. Use one of the Auth_SQL::ENCRYPT_* types specified above.
[550]71        // Hardened password hashes rely on the same key/salt being used to compare hashes.
[136]72        // Be aware that when using one of the hardened types the App signing_key or $more_salt below cannot change!
[501]73        'hash_type' => self::ENCRYPT_MD5,
74        'encryption_type' => null, // Backwards misnomer compatibility.
[1]75
[501]76        // Automatically update stored user hashes when the user next authenticates if the hash type changes (requires user_tbl with populated userpass_hashtype column).
77        'hash_type_autoupdate' => true,
78
[25]79        // The URL to the login script.
[1]80        'login_url' => '/',
81
82        // The maximum amount of time a user is allowed to be logged in. They will be forced to login again if they expire.
[124]83        // In seconds. 21600 seconds = 6 hours.
[1]84        'login_timeout' => 21600,
[42]85
[1]86        // 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.
[124]87        // In seconds. 3600 seconds = 1 hour.
[1]88        'idle_timeout' => 3600,
89
90        // 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.
91        // Days and hours, like this: 'DD:HH'
92        'login_abuse_timeframe' => '04:00',
93
94        // The number of warnings a user will receive (and their password reset each time) before their account is completely blocked.
95        'login_abuse_warnings' => 3,
96
97        // The maximum number of IP addresses a user can login with over the timeout period before their account is blocked.
98        'login_abuse_max_ips' => 5,
99
[334]100        // The IP address subnet size threshold. Uses a CIDR notation network mask (see CIDR cheat-sheet at bottom).
101        // Any integer between 0 and 32 is permitted. Setting this to '24' permits any address in a
[1]102        // class C network (255.255.255.0) to be considered the same. Setting to '32' compares each IP absolutely.
103        // Setting to '0' ignores all IPs, thus disabling login_abuse checking.
104        'login_abuse_ip_bitmask' => 32,
105
[42]106        // Specify usernames to exclude from the account abuse detection system. This is specified as a hardcoded array provided at
[1]107        // class instantiation time, or can be saved in the db_table under the login_abuse_exempt field.
108        'login_abuse_exempt_usernames' => array(),
[42]109
[275]110        // Specify usernames to exclude from remote_ip matching. Users behind proxy servers should be appended to this array so their shifting remote IP will not log them out.
111        'match_remote_ip_exempt_usernames' => array(),
112
113        // Match the user's current remote IP against the one they logged in with.
114        'match_remote_ip' => true,
115
[103]116        // An array of IP blocks that are bypass the remote_ip comparison check. Useful for dynamic IPs or those behind proxy servers.
[1]117        'trusted_networks' => array(),
118
119        // Allow user accounts to be blocked? Requires the user table to have the columns 'blocked' and 'blocked_reason'
120        'blocking' => false,
[42]121
[1]122        // Use a db_login_table to detect excessive logins. This requires blocking to be enabled.
123        'abuse_detection' => false,
[421]124
125        // Allow users to save login form passwords in their browser? Setting to 'true' may pose a potential security risk.
126        'login_form_allow_autocomplete' => false,
[1]127    );
128
129    /**
130     * Constructs a new authentication object.
131     *
132     * @access public
133     * @param optional array $params  A hash containing parameters.
134     */
[468]135    public function __construct($namespace='')
[1]136    {
[479]137        $app =& App::getInstance();
[453]138
[154]139        $this->_ns = $namespace;
[453]140
[1]141        // Initialize default parameters.
142        $this->setParam($this->_default_params);
143
144        // Get create tables config from global context.
[136]145        if (!is_null($app->getParam('db_create_tables'))) {
146            $this->setParam(array('create_table' => $app->getParam('db_create_tables')));
[1]147        }
[198]148
149        if (!isset($_SESSION['_auth_sql'][$this->_ns])) {
[634]150            $app->logMsg(sprintf('No _auth_sql session found; initializing', null), LOG_DEBUG, __FILE__, __LINE__);
[198]151            $this->clear();
152        }
[1]153    }
[42]154
[1]155    /**
156     * Setup the database tables for this class.
157     *
158     * @access  public
159     * @author  Quinn Comendant <quinn@strangecode.com>
160     * @since   26 Aug 2005 17:09:36
161     */
[468]162    public function initDB($recreate_db=false)
[1]163    {
[479]164        $app =& App::getInstance();
165        $db =& DB::getInstance();
[453]166
[1]167        static $_db_tested = false;
[42]168
[1]169        if ($recreate_db || !$_db_tested && $this->getParam('create_table')) {
[42]170
[1]171            // User table.
172            if ($recreate_db) {
[136]173                $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_table'));
[201]174                $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_INFO, __FILE__, __LINE__);
[1]175            }
176
[550]177            // The minimal columns for a table compatible with the Auth_SQL class.
[601]178            $db->query(sprintf(
179                "CREATE TABLE IF NOT EXISTS %1\$s (
180                    %2\$s MEDIUMINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
181                    %3\$s varchar(255) NOT NULL default '',
182                    userpass VARCHAR(255) NOT NULL DEFAULT '',
183                    userpass_hashtype TINYINT UNSIGNED NOT NULL DEFAULT '0',
184                    first_name VARCHAR(50) NOT NULL DEFAULT '',
185                    last_name VARCHAR(50) NOT NULL DEFAULT '',
186                    email VARCHAR(255) NOT NULL DEFAULT '',
187                    login_abuse_exempt ENUM('true') DEFAULT NULL,
188                    blocked ENUM('true') DEFAULT NULL,
189                    blocked_reason VARCHAR(255) NOT NULL DEFAULT '',
190                    abuse_warning_level TINYINT NOT NULL DEFAULT '0',
191                    seconds_online INT NOT NULL DEFAULT '0',
192                    last_login_datetime DATETIME NOT NULL DEFAULT '%4\$s 00:00:00',
193                    last_access_datetime DATETIME NOT NULL DEFAULT '%4\$s 00:00:00',
194                    last_login_ip VARCHAR(45) NOT NULL DEFAULT '0.0.0.0',
195                    added_by_user_id SMALLINT DEFAULT NULL,
196                    modified_by_user_id SMALLINT DEFAULT NULL,
197                    added_datetime DATETIME NOT NULL DEFAULT '%4\$s 00:00:00',
198                    modified_datetime DATETIME NOT NULL DEFAULT '%4\$s 00:00:00',
199                    KEY %5\$s (%5\$s),
200                    KEY userpass (userpass),
201                    KEY email (email),
202                    KEY last_login_datetime (last_login_datetime),
203                    KEY last_access_datetime (last_access_datetime)
204                )",
205                $db->escapeString($this->getParam('db_table')),
206                $this->getParam('db_primary_key'),
207                $this->getParam('db_username_column'),
208                $db->getParam('zero_date'),
209                $this->getParam('db_username_column')
210            ));
[1]211
[136]212            if (!$db->columnExists($this->getParam('db_table'), array(
[42]213                $this->getParam('db_primary_key'),
214                $this->getParam('db_username_column'),
215                'userpass',
216                'first_name',
217                'last_name',
218                'email',
219                'login_abuse_exempt',
220                'blocked',
221                'blocked_reason',
222                'abuse_warning_level',
223                'seconds_online',
224                'last_login_datetime',
225                'last_access_datetime',
226                'last_login_ip',
227                'added_by_user_id',
228                'modified_by_user_id',
229                'added_datetime',
230                'modified_datetime',
[1]231            ), false, false)) {
[136]232                $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__);
[1]233                trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), E_USER_ERROR);
234            }
[42]235
[17]236            // Login table is used for abuse_detection features.
237            if ($this->getParam('abuse_detection')) {
238                if ($recreate_db) {
[136]239                    $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_login_table'));
[201]240                    $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_login_table')), LOG_INFO, __FILE__, __LINE__);
[17]241                }
[601]242                $db->query(sprintf(
243                    "CREATE TABLE IF NOT EXISTS %1\$s (
244                        %2\$s MEDIUMINT UNSIGNED NOT NULL DEFAULT '0',
245                        login_datetime DATETIME NOT NULL DEFAULT '%3\$s 00:00:00',
246                        remote_ip_binary CHAR(32) NOT NULL DEFAULT '',
247                        KEY %4\$s (%4\$s),
248                        KEY login_datetime (login_datetime),
249                        KEY remote_ip_binary (remote_ip_binary)
250                    )",
251                    $this->getParam('db_login_table'),
252                    $this->getParam('db_primary_key'),
253                    $db->getParam('zero_date'),
254                    $this->getParam('db_primary_key')
255                ));
[42]256
[136]257                if (!$db->columnExists($this->getParam('db_login_table'), array(
[17]258                    $this->getParam('db_primary_key'),
259                    'login_datetime',
260                    'remote_ip_binary',
261                ), false, false)) {
[136]262                    $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_login_table')), LOG_ALERT, __FILE__, __LINE__);
[17]263                    trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_login_table')), E_USER_ERROR);
264                }
[1]265            }
[42]266        }
[1]267        $_db_tested = true;
268    }
269
270    /**
271     * Set the params of an auth object.
272     *
273     * @param  array $params   Array of parameter keys and value to set.
274     * @return bool true on success, false on failure
275     */
[468]276    public function setParam($params)
[1]277    {
[501]278        $app =& App::getInstance();
279
[368]280        if (isset($params['match_remote_ip_exempt_usernames'])) {
281            $params['match_remote_ip_exempt_usernames'] = array_map('strtolower', $params['match_remote_ip_exempt_usernames']);
282        }
283        if (isset($params['login_abuse_exempt_usernames'])) {
284            $params['login_abuse_exempt_usernames'] = array_map('strtolower', $params['login_abuse_exempt_usernames']);
285        }
[501]286        if (isset($params['encryption_type'])) {
287            // Backwards misnomer compatibility.
288            $params['hash_type'] = $params['encryption_type'];
289        }
290        if (isset($params['hash_type']) && version_compare(PHP_VERSION, '5.5.0', '<') && in_array($params['hash_type'], array(self::ENCRYPT_PASSWORD_BCRYPT, self::ENCRYPT_PASSWORD_DEFAULT))) {
[500]291            // These hash types require the password_* userland lib in PHP < 5.5.0
292            $pw_compat_lib = 'vendor/ircmaxell/password-compat/lib/password.php';
293            if (false !== stream_resolve_include_path($pw_compat_lib)) {
294                include_once $pw_compat_lib;
295            } else {
[501]296                $app->logMsg(sprintf('Hash type %s requires password-compat lib in PHP < 5.5.0; falling back to ENCRYPT_SHA1_HARDENED', $params['hash_type']), LOG_ERR, __FILE__, __LINE__);
297                $params['hash_type'] = self::ENCRYPT_SHA1_HARDENED;
[500]298            }
299        }
[501]300        if (isset($params['hash_type']) && !in_array($params['hash_type'], array(self::ENCRYPT_PLAINTEXT, self::ENCRYPT_CRYPT, self::ENCRYPT_SHA1, self::ENCRYPT_SHA1_HARDENED, self::ENCRYPT_MD5, self::ENCRYPT_MD5_HARDENED, self::ENCRYPT_PASSWORD_BCRYPT, self::ENCRYPT_PASSWORD_DEFAULT))) {
301            $app->logMsg(sprintf('Invalid hash type %s; falling back to ENCRYPT_SHA1_HARDENED', $params['hash_type']), LOG_ERR, __FILE__, __LINE__);
302            $params['hash_type'] = self::ENCRYPT_SHA1_HARDENED;
303        }
[1]304        if (isset($params) && is_array($params)) {
305            // Merge new parameters with old overriding only those passed.
306            $this->_params = array_merge($this->_params, $params);
307        }
308    }
309
310    /**
311     * Return the value of a parameter, if it exists.
312     *
313     * @access public
314     * @param string $param        Which parameter to return.
315     * @return mixed               Configured parameter value.
316     */
[468]317    public function getParam($param)
[1]318    {
[479]319        $app =& App::getInstance();
[453]320
[478]321        if (array_key_exists($param, $this->_params)) {
[1]322            return $this->_params[$param];
323        } else {
[146]324            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
[1]325            return null;
326        }
327    }
328
329    /**
330     * Clear any authentication tokens in the current session. A.K.A. logout.
331     *
332     * @access public
333     */
[468]334    public function clear()
[1]335    {
[611]336        $app =& App::getInstance();
[479]337        $db =& DB::getInstance();
[453]338
[564]339        if ($this->get('user_id', false)) {
[42]340
[564]341            $this->initDB();
342
[199]343            // FIX ME: Should we check if the session is active?
[601]344            $db->query(sprintf(
345                "UPDATE %s SET
346                    seconds_online = seconds_online + ABS(UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_access_datetime)),
347                    last_login_datetime = '%s 00:00:00'
348                    WHERE %s = '%s'
349                ",
350                $this->_params['db_table'],
351                $db->getParam('zero_date'),
352                $this->_params['db_primary_key'],
353                $this->get('user_id')
354            ));
[195]355        }
[421]356        $_SESSION['_auth_sql'][$this->_ns] = array(
357            'authenticated'         => false,
358            'user_id'               => null,
359            'username'              => null,
360            'login_datetime'        => null,
361            'last_access_datetime'  => null,
362            'remote_ip'             => getRemoteAddr(),
363            'login_abuse_exempt'    => null,
364            'match_remote_ip_exempt'=> null,
365            'user_data'             => null,
366        );
[611]367
368        $app->logMsg(sprintf('Cleared %s auth', $this->_ns), LOG_DEBUG, __FILE__, __LINE__);
[1]369    }
370
371    /**
[103]372     * Sets a variable into a registered auth session.
373     *
374     * @access public
375     * @param mixed $key      Which value to set.
376     * @param mixed $val      Value to set variable to.
377     */
[468]378    public function set($key, $val)
[103]379    {
[154]380        if (!isset($_SESSION['_auth_sql'][$this->_ns]['user_data'])) {
381            $_SESSION['_auth_sql'][$this->_ns]['user_data'] = array();
[103]382        }
[671]383
384        if (isset($_SESSION['_auth_sql'][$this->_ns][$key])) {
385            $_SESSION['_auth_sql'][$this->_ns][$key] = $val;
386        } else {
387            $_SESSION['_auth_sql'][$this->_ns]['user_data'][$key] = $val;
388        }
[103]389    }
390
391    /**
392     * Returns a specified value from a registered auth session.
393     *
394     * @access public
395     * @param mixed $key      Which value to return.
396     * @param mixed $default  Value to return if key not found in user_data.
397     * @return mixed          Value stored in session.
398     */
[468]399    public function get($key, $default='')
[103]400    {
[154]401        if (isset($_SESSION['_auth_sql'][$this->_ns][$key])) {
402            return $_SESSION['_auth_sql'][$this->_ns][$key];
403        } else if (isset($_SESSION['_auth_sql'][$this->_ns]['user_data'][$key])) {
404            return $_SESSION['_auth_sql'][$this->_ns]['user_data'][$key];
[103]405        } else {
406            return $default;
407        }
408    }
409
410    /**
[500]411     * Retrieve and verify the given username and password against a matching user record in the database.
[1]412     *
413     * @access private
414     * @param string $username      The username to check.
415     * @param string $password      The password to compare to username.
416     * @return mixed  False if credentials not found in DB, or returns DB row matching credentials.
417     */
[468]418    public function authenticate($username, $password)
[1]419    {
[479]420        $app =& App::getInstance();
421        $db =& DB::getInstance();
[136]422
[1]423        $this->initDB();
[42]424
[500]425        // Get user data for specified username.
426        $qid = $db->query("
427            SELECT *, " . $this->_params['db_primary_key'] . " AS user_id
428            FROM " . $this->_params['db_table'] . "
429            WHERE " . $this->_params['db_username_column'] . " = '" . $db->escapeString($username) . "'
430        ");
431        if (!$user_data = mysql_fetch_assoc($qid)) {
432            $app->logMsg(sprintf('Username %s not found for authentication', $username), LOG_NOTICE, __FILE__, __LINE__);
433            return false;
[124]434        }
[42]435
[560]436        // Check given password against hashed DB password.
[501]437        $old_hash_type = isset($user_data['userpass_hashtype']) && !empty($user_data['userpass_hashtype']) ? $user_data['userpass_hashtype'] : $this->getParam('hash_type');
438        if ($this->verifyPassword($password, $user_data['userpass'], $old_hash_type)) {
[500]439            $app->logMsg(sprintf('Authentication successful for %s (user_id=%s)', $username, $user_data['user_id']), LOG_INFO, __FILE__, __LINE__);
440            unset($user_data['userpass']); // Avoid revealing the encrypted password in the $user_data.
[501]441            if ($this->getParam('hash_type_autoupdate') && $old_hash_type != $this->getParam('hash_type')) {
442                // Let's update user's password hash to new type (just run setPassword with this authenticated password
).
443                $this->setPassword($user_data['user_id'], $password);
444                $app->logMsg(sprintf('User %s password hash type updated from %s to %s', $username, $old_hash_type, $this->getParam('hash_type')), LOG_INFO, __FILE__, __LINE__);
445            }
[1]446            return $user_data;
447        }
[500]448
449        $app->logMsg(sprintf('Authentication failed for %s (user_id=%s)', $username, $user_data['user_id']), LOG_NOTICE, __FILE__, __LINE__);
450        return false;
[1]451    }
452
453    /**
[582]454     * Check username and password, and create new session if authenticated.
[1]455     *
456     * @access private
457     * @param string $username     The username to check.
[582]458     * @param string $password     The password to compare for username.
[1]459     * @return boolean  Whether or not the credentials are valid.
460     */
[468]461    public function login($username, $password)
[1]462    {
[479]463        $app =& App::getInstance();
464        $db =& DB::getInstance();
[453]465
[582]466        if ($user_data = $this->authenticate($username, $password)) {
467            // The credentials match. Now setup the session.
468            return $this->createSession($user_data);
469        }
470        // No login: failed authentication!
471        return false;
472    }
473
474    /**
475     * Create new login session for given user.
476     *
477     * @access private
478     * @param string $user_data User data that is normally returned from this->authenticate(). If provided manually:
479     *                          Required array values:
480     *                              'user_id' => '1'
481     *                              'username' => 'name'
482     *                          Optional array values:
483     *                              'match_remote_ip_exempt' => true
484     *                              'login_abuse_exempt' => true
485     *                              'abuse_warning_level' => true
486     *                              'blocked' => true
487     *                              'blocked_reason' => ''
488     *                              '
' => '
' (any other values that should be retrievable via this->get())
489     * @return boolean          Whether or not the session was created. It will return true unless abuse detection is enabled and triggered.
490     */
491    public function createSession($user_data)
492    {
493        $app =& App::getInstance();
494        $db =& DB::getInstance();
495
[1]496        $this->initDB();
[42]497
[149]498        $this->clear();
[1]499
[453]500        // Convert 'priv' to 'user_type' nomenclature to support older implementations.
501        if (isset($user_data['priv'])) {
502            $user_data['user_type'] = $user_data['priv'];
503        }
504
[1]505        // Register authenticated session.
[154]506        $_SESSION['_auth_sql'][$this->_ns] = array(
[1]507            'authenticated'         => true,
508            'user_id'               => $user_data['user_id'],
[582]509            'username'              => $user_data['username'],
[1]510            'login_datetime'        => date('Y-m-d H:i:s'),
511            'last_access_datetime'  => date('Y-m-d H:i:s'),
512            'remote_ip'             => getRemoteAddr(),
[582]513            'login_abuse_exempt'    => isset($user_data['login_abuse_exempt']) ? !empty($user_data['login_abuse_exempt']) : in_array(strtolower($user_data['username']), $this->_params['login_abuse_exempt_usernames']),
514            'match_remote_ip_exempt'=> isset($user_data['match_remote_ip_exempt']) ? !empty($user_data['match_remote_ip_exempt']) : in_array(strtolower($user_data['username']), $this->_params['match_remote_ip_exempt_usernames']),
[1]515            'user_data'             => $user_data
516        );
[42]517
[1]518        /**
519         * Check if the account is blocked, respond in context to reason. Cancel the login if blocked.
520         */
521        if ($this->getParam('blocking')) {
[582]522            if (isset($user_data['blocked']) && !empty($user_data['blocked'])) {
523                switch ($this->get('blocked_reason')) {
524                case 'account abuse' :
525                    $app->raiseMsg(sprintf(_("This account has been blocked due to possible account abuse. Please contact an administrator to reactivate."), null), MSG_WARNING, __FILE__, __LINE__);
526                    break;
527                default :
528                    $app->raiseMsg(sprintf(_("This account is currently not active. %s"), $this->get('blocked_reason')), MSG_WARNING, __FILE__, __LINE__);
529                    break;
[1]530                }
[42]531
[1]532                // No login: user is blocked!
[582]533                $app->logMsg(sprintf('User_id %s (%s) login failed due to blocked account: %s', $this->get('user_id'), $this->get('username'), $this->get('blocked_reason')), LOG_NOTICE, __FILE__, __LINE__);
[149]534                $this->clear();
[1]535                return false;
536            }
537        }
[42]538
[1]539        /**
540         * Check the db_login_table for too many logins under this account.
541         * (1) Count the number of unique IP addresses that logged in under this user within the login_abuse_timeframe
542         * (2) If this number exceeds the login_abuse_max_ips, assume multiple people are logging in under the same account.
543        **/
[497]544        // TODO: make this ipv6 compatible. At the moment, ipv6 addresses are converted into zero for remote_ip_binary.
545        // http://www.highonphp.com/5-tips-for-working-with-ipv6-in-php
546        // https://stackoverflow.com/questions/444966/working-with-ipv6-addresses-in-php
[148]547        if ($this->getParam('abuse_detection') && !$this->get('login_abuse_exempt')) {
[136]548            $qid = $db->query("
[1]549                SELECT COUNT(DISTINCT LEFT(remote_ip_binary, " . $this->_params['login_abuse_ip_bitmask'] . "))
550                FROM " . $this->_params['db_login_table'] . "
[148]551                WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'
[1]552                AND DATE_ADD(login_datetime, INTERVAL '" . $this->_params['login_abuse_timeframe'] . "' DAY_HOUR) > NOW()
553            ");
554            list($distinct_ips) = mysql_fetch_row($qid);
555            if ($distinct_ips > $this->_params['login_abuse_max_ips']) {
[148]556                if ($this->get('abuse_warning_level') < $this->_params['login_abuse_warnings']) {
[1]557                    // Warn the user with a password reset.
[550]558                    $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 credentials with others. If further account abuse is detected this account will be blocked."));
[136]559                    $app->raiseMsg(_("Your password has been reset as a security precaution. Please check your email for more information."), MSG_NOTICE, __FILE__, __LINE__);
[372]560                    $app->logMsg(sprintf('Account abuse detected for user_id %s (%s) from IP %s', $this->get('user_id'), $this->get('username'), $this->get('remote_ip')), LOG_WARNING, __FILE__, __LINE__);
[1]561                } else {
562                    // Block the account with the reason of account abuse.
563                    $this->blockAccount(null, 'account abuse');
[136]564                    $app->raiseMsg(_("Your account has been blocked as a security precaution. Please contact us for more information."), MSG_NOTICE, __FILE__, __LINE__);
[372]565                    $app->logMsg(sprintf('Account blocked for user_id %s (%s) from IP %s', $this->get('user_id'), $this->get('username'), $this->get('remote_ip')), LOG_ALERT, __FILE__, __LINE__);
[1]566                }
567                // Increment user's warning level.
[148]568                $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') . "'");
[1]569                // Reset the login counter for this user.
[148]570                $db->query("DELETE FROM " . $this->_params['db_login_table'] . " WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'");
[1]571                // No login: reset password because of account abuse!
[149]572                $this->clear();
[1]573                return false;
574            }
575
576            // Update the login counter table with this login access. Convert IP to binary.
[563]577            // TODO: this query could benefit from INSERT DELAYED.
[136]578            $db->query("
[1]579                INSERT INTO " . $this->_params['db_login_table'] . " (
[42]580                    " . $this->_params['db_primary_key'] . ",
581                    login_datetime,
[1]582                    remote_ip_binary
583                ) VALUES (
[148]584                    '" . $this->get('user_id') . "',
585                    '" . $this->get('login_datetime') . "',
586                    '" . sprintf('%032b', ip2long($this->get('remote_ip'))) . "'
[1]587                )
588            ");
589        }
[42]590
[1]591        // Update user table with this login.
[136]592        $db->query("
[1]593            UPDATE " . $this->_params['db_table'] . " SET
[148]594                last_login_datetime = '" . $this->get('login_datetime') . "',
595                last_access_datetime = '" . $this->get('login_datetime') . "',
596                last_login_ip = '" . $this->get('remote_ip') . "'
597            WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'
[1]598        ");
[42]599
[582]600        // Session created! We're logged-in!
[1]601        return true;
602    }
603
604    /**
605     * Test if user has a currently logged-in session.
606     *  - authentication flag set to true
607     *  - username not empty
608     *  - total logged-in time is not greater than login_timeout
609     *  - idle time is not greater than idle_timeout
[563]610     *  - remote address is the same as the login remote address
[1]611     *
612     * @access public
613     */
[468]614    public function isLoggedIn($user_id=null)
[1]615    {
[479]616        $app =& App::getInstance();
617        $db =& DB::getInstance();
[372]618
[1]619        $this->initDB();
[42]620
[1]621        if (isset($user_id)) {
622            // Check the login status of a specific user.
[136]623            $qid = $db->query("
[671]624                SELECT
625                    TIMESTAMPDIFF(SECOND, last_login_datetime, NOW()) AS seconds_since_last_login,
626                    TIMESTAMPDIFF(SECOND, last_access_datetime, NOW()) AS seconds_since_last_access
627                FROM " . $this->_params['db_table'] . "
[136]628                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
[671]629                AND last_login_datetime > DATE_SUB(NOW(), INTERVAL '" . $db->escapeString($this->_params['login_timeout']) . "' SECOND)
630                AND last_access_datetime > DATE_SUB(NOW(), INTERVAL '" . $db->escapeString($this->_params['idle_timeout']) . "' SECOND)
[1]631            ");
[671]632            $result = mysql_fetch_assoc($qid);
633            if (mysql_num_rows($qid) > 0 && isset($result['seconds_since_last_login']) && isset($result['seconds_since_last_access'])) {
634                $seconds_until_login_timeout = max(0, $this->_params['login_timeout'] - $result['seconds_since_last_login']);
635                $seconds_until_idle_timeout = max(0, $this->_params['idle_timeout'] - $result['seconds_since_last_access']);
636                $session_expiry_seconds = min($seconds_until_login_timeout, $seconds_until_idle_timeout);
637                $app->logMsg(sprintf('Returning true login status for user_id %s (session expires in %s seconds)', $user_id, $session_expiry_seconds), LOG_DEBUG, __FILE__, __LINE__);
638                return $session_expiry_seconds;
639            } else {
640                $app->logMsg(sprintf('Returning false login status for user_id %s', $user_id), LOG_DEBUG, __FILE__, __LINE__);
641                return false;
642            }
[1]643        }
644
645        // User login test need only be run once per script execution. We cache the result in the session.
[154]646        if ($this->_authentication_tested && isset($_SESSION['_auth_sql'][$this->_ns]['authenticated'])) {
[372]647            $app->logMsg(sprintf('Returning cached authentication status: %s', ($_SESSION['_auth_sql'][$this->_ns]['authenticated'] ? 'true' : 'false')), LOG_DEBUG, __FILE__, __LINE__);
[154]648            return $_SESSION['_auth_sql'][$this->_ns]['authenticated'];
[1]649        }
[42]650
[563]651        // Testing login should occur once. This is the first time. Set flag.
[1]652        $this->_authentication_tested = true;
[35]653
[453]654        // Some users will access from networks with a changing IP number (i.e. behind a proxy server).
[370]655        // These users must be allowed entry by adding their IP to the list of trusted_networks, or their usernames to the list of match_remote_ip_exempt_usernames.
[1]656        if ($trusted_net = ipInRange(getRemoteAddr(), $this->_params['trusted_networks'])) {
657            $user_in_trusted_network = true;
[372]658            $app->logMsg(sprintf('User_id %s accessing from trusted network %s',
659                ($this->get('user_id') ? $this->get('user_id') . ' (' .  $this->get('username') . ')' : 'unknown'),
[1]660                $trusted_net
[71]661            ), LOG_DEBUG, __FILE__, __LINE__);
[1]662        } else {
663            $user_in_trusted_network = false;
664        }
[453]665
[275]666        // Do we match the user's remote IP at all? Yes, if set in config and not disabled for specific user.
667        if ($this->getParam('match_remote_ip') && !$this->get('match_remote_ip_exempt')) {
[276]668            $remote_ip_is_matched = (isset($_SESSION['_auth_sql'][$this->_ns]['remote_ip']) && $_SESSION['_auth_sql'][$this->_ns]['remote_ip'] == getRemoteAddr()) || $user_in_trusted_network;
[275]669        } else {
[453]670            $app->logMsg(sprintf('User_id %s exempt from remote_ip match (comparing %s == %s)',
[372]671                ($this->get('user_id') ? $this->get('user_id') . ' (' .  $this->get('username') . ')' : 'unknown'),
[277]672                $_SESSION['_auth_sql'][$this->_ns]['remote_ip'],
673                getRemoteAddr()
[275]674            ), LOG_DEBUG, __FILE__, __LINE__);
675            $remote_ip_is_matched = true;
676        }
[42]677
[1]678        // Test login with information stored in session. Skip IP matching for users from trusted networks.
[453]679        if (isset($_SESSION['_auth_sql'][$this->_ns]['authenticated'])
[154]680            && true === $_SESSION['_auth_sql'][$this->_ns]['authenticated']
[372]681            && isset($_SESSION['_auth_sql'][$this->_ns]['username'])
[154]682            && !empty($_SESSION['_auth_sql'][$this->_ns]['username'])
[372]683            && isset($_SESSION['_auth_sql'][$this->_ns]['login_datetime'])
[541]684            && strtotime($_SESSION['_auth_sql'][$this->_ns]['login_datetime']) > (time() - $this->_params['login_timeout'])
[372]685            && isset($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime'])
[541]686            && strtotime($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime']) > (time() - $this->_params['idle_timeout'])
[275]687            && $remote_ip_is_matched
[1]688        ) {
689            // User is authenticated!
690
[671]691            // Update the last_access_datetime to now.
692            $this->set('last_access_datetime', date('Y-m-d H:i:s'));
693
[1]694            // Update the DB with the last_access_datetime and increment the seconds_online.
[136]695            $db->query("
[42]696                UPDATE " . $this->_params['db_table'] . " SET
[502]697                seconds_online = seconds_online + ABS(UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_access_datetime)) + 1,
[148]698                last_access_datetime = '" . $this->get('last_access_datetime') . "'
699                WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'
[1]700            ");
[136]701            if (mysql_affected_rows($db->getDBH()) > 0) {
[1]702                // 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.
703                return true;
704            } else {
[372]705                $app->logMsg(sprintf('Session update failed; record not found for user_id %s (%s).', $this->get('user_id'), $this->get('username')), LOG_NOTICE, __FILE__, __LINE__);
[1]706            }
[224]707        } else if (isset($_SESSION['_auth_sql'][$this->_ns]['authenticated']) && true === $_SESSION['_auth_sql'][$this->_ns]['authenticated']) {
[1]708            // User is authenticated, but login has expired.
[42]709
[1]710            // Log the reason for login expiration.
711            $expire_reasons = array();
[593]712            $user_notified = false;
[541]713            if (!isset($_SESSION['_auth_sql'][$this->_ns]['username']) || empty($_SESSION['_auth_sql'][$this->_ns]['username'])) {
[1]714                $expire_reasons[] = 'username not found';
715            }
[541]716            if (!isset($_SESSION['_auth_sql'][$this->_ns]['login_datetime']) || strtotime($_SESSION['_auth_sql'][$this->_ns]['login_datetime']) <= (time() - $this->_params['login_timeout'])) {
[372]717                $expire_reasons[] = sprintf('login_timeout expired (%s older than %s seconds ago)', $_SESSION['_auth_sql'][$this->_ns]['login_datetime'], $this->_params['login_timeout']);
[1]718            }
[541]719            if (!isset($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime']) || strtotime($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime']) <= (time() - $this->_params['idle_timeout'])) {
[372]720                $expire_reasons[] = sprintf('idle_timeout expired (%s older than %s seconds ago)', $_SESSION['_auth_sql'][$this->_ns]['last_access_datetime'], $this->_params['idle_timeout']);
[593]721                if (strtotime($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime']) > (time() - 43200)) {
722                    // Only raise message if last session is less than 12 hours old.
723                    // Notify user why they were logged out if they haven't yet been given a reason.
[619]724                    $user_notified || $app->raiseMsg(sprintf(_("For your security we logged you out after being idle for %s. Please log in again."), humanTime($this->_params['idle_timeout'], 'hour', '%01.0f')), MSG_NOTICE, __FILE__, __LINE__);
[593]725                    $user_notified = true;
726                }
[1]727            }
[541]728            if (!isset($_SESSION['_auth_sql'][$this->_ns]['remote_ip']) || $_SESSION['_auth_sql'][$this->_ns]['remote_ip'] != getRemoteAddr()) {
[370]729                if ($this->getParam('match_remote_ip') && !$this->get('match_remote_ip_exempt') && !$user_in_trusted_network) {
730                    // There are three cases when a remote IP match will be the cause of a session termination:
731                    //   1. match_remote_ip config is enabled
732                    //   2. user is not match_remote_ip_exempt (set in the user_data, or in the match_remote_ip_exempt_usernames list)
[563]733                    //   3. the user is connecting from a trusted network (their IP is listed in the trusted_networks)
[275]734                    $expire_reasons[] = sprintf('remote_ip not matched (%s != %s)', $_SESSION['_auth_sql'][$this->_ns]['remote_ip'], getRemoteAddr());
[593]735                    // Notify user why they were logged out if they haven't yet been given a reason.
[619]736                    $user_notified || $app->raiseMsg(sprintf(_("For your security we logged you out because your IP address has changed. Please log in again."), null), MSG_NOTICE, __FILE__, __LINE__);
[593]737                    $user_notified = true;
[275]738                } else {
739                    $expire_reasons[] = sprintf('remote_ip not matched but user was exempt from this check (%s != %s)', $_SESSION['_auth_sql'][$this->_ns]['remote_ip'], getRemoteAddr());
740                }
[1]741            }
[372]742            $app->logMsg(sprintf('User_id %s (%s) session expired: %s', $this->get('user_id'), $this->get('username'), join(', ', $expire_reasons)), LOG_INFO, __FILE__, __LINE__);
[535]743        } else {
[541]744            $app->logMsg('Session is not authenticated', LOG_DEBUG, __FILE__, __LINE__);
[1]745        }
746
747        // User is not authenticated.
[149]748        $this->clear();
[1]749        return false;
750    }
751
752    /**
753     * Redirect user to login page if they are not logged in.
754     *
[32]755     * @param string $message The text description of a message to raise.
[1]756     * @param int    $type    The type of message: MSG_NOTICE,
757     *                        MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
758     * @param string $file    __FILE__.
759     * @param string $line    __LINE__.
760     * @access public
761     */
[468]762    public function requireLogin($message='', $type=MSG_NOTICE, $file=null, $line=null)
[1]763    {
[479]764        $app =& App::getInstance();
[453]765
[1]766        if (!$this->isLoggedIn()) {
[103]767            // Display message for requiring login. (RaiseMsg will ignore empty strings.)
[203]768            if ('' != $message) {
769                $app->raiseMsg($message, $type, $file, $line);
770            }
[32]771
[28]772            // Login scripts must have the same 'login' tag for boomerangURL verification/manipulation.
[136]773            $app->setBoomerangURL(absoluteMe(), 'login');
774            $app->dieURL($this->_params['login_url']);
[1]775        }
776    }
777
778    /**
779     * This sets the 'blocked' field for a user in the db_table, and also
780     * adds an optional reason
[42]781     *
[1]782     * @param  string   $reason      The reason for blocking the account.
783     */
[468]784    public function blockAccount($user_id=null, $reason='')
[1]785    {
[479]786        $app =& App::getInstance();
787        $db =& DB::getInstance();
[453]788
[1]789        $this->initDB();
[42]790
[1]791        if ($this->getParam('blocking')) {
[247]792            if (mb_strlen($db->escapeString($reason)) > 255) {
[1]793                // blocked_reason field is varchar(255).
[136]794                $app->logMsg(sprintf('Blocked reason provided is greater than 255 characters: %s', $reason), LOG_WARNING, __FILE__, __LINE__);
[1]795            }
[42]796
[1]797            // Get user_id if specified.
[148]798            $user_id = isset($user_id) ? $user_id : $this->get('user_id');
[136]799            $db->query("
[1]800                UPDATE " . $this->_params['db_table'] . " SET
801                blocked = 'true',
[136]802                blocked_reason = '" . $db->escapeString($reason) . "'
803                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
[1]804            ");
805        }
806    }
807
808    /**
[266]809     * Tests if the "blocked" flag is set for a user.
810     *
811     * @param  int      $user_id    User id to look for.
812     * @return boolean              True if the user is blocked, false otherwise.
813     */
[468]814    public function isBlocked($user_id=null)
[266]815    {
[479]816        $db =& DB::getInstance();
[266]817
818        $this->initDB();
819
820        if ($this->getParam('blocking')) {
821            // Get user_id if specified.
822            $user_id = isset($user_id) ? $user_id : $this->getVal('user_id');
823            $qid = $db->query("
[453]824                SELECT 1
[266]825                FROM " . $this->_params['db_table'] . "
826                WHERE blocked = 'true'
827                AND " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
828            ");
829            return mysql_num_rows($qid) === 1;
830        }
831    }
832
833    /**
[42]834     * Unblocks a user in the db_table, and clears any blocked_reason.
[1]835     */
[468]836    public function unblockAccount($user_id=null)
[1]837    {
[479]838        $db =& DB::getInstance();
[453]839
[1]840        $this->initDB();
[453]841
[1]842        if ($this->getParam('blocking')) {
843            // Get user_id if specified.
[148]844            $user_id = isset($user_id) ? $user_id : $this->get('user_id');
[136]845            $db->query("
[1]846                UPDATE " . $this->_params['db_table'] . " SET
[622]847                blocked = NULL,
[1]848                blocked_reason = ''
[136]849                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
[1]850            ");
851        }
852    }
853
854    /**
855     * Returns true if username already exists in database.
856     *
857     * @param  string  $username    Username to look for.
858     * @return bool                 True if username exists.
859     */
[468]860    public function usernameExists($username)
[42]861    {
[479]862        $db =& DB::getInstance();
[453]863
[1]864        $this->initDB();
[42]865
[136]866        $qid = $db->query("
[42]867            SELECT 1
[15]868            FROM " . $this->_params['db_table'] . "
[136]869            WHERE " . $this->_params['db_username_column'] . " = '" . $db->escapeString($username) . "'
[15]870        ");
[1]871        return (mysql_num_rows($qid) > 0);
872    }
873
874    /**
875     * Returns a username for a specified user id.
876     *
877     * @param  string  $user_id     User id to look for.
878     * @return string               Username, or false if none found.
879     */
[468]880    public function getUsername($user_id)
[42]881    {
[479]882        $db =& DB::getInstance();
[453]883
[1]884        $this->initDB();
[42]885
[136]886        $qid = $db->query("
[15]887            SELECT " . $this->_params['db_username_column'] . "
888            FROM " . $this->_params['db_table'] . "
[136]889            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
[15]890        ");
[1]891        if (list($username) = mysql_fetch_row($qid)) {
892            return $username;
893        } else {
894            return false;
895        }
896    }
897
[674]898    /**
899     * Returns a user_id for a specified username.
900     *
901     * @param  string  $username    Username to look for.
902     * @return string               User_id, or false if none found.
903     */
904    public function getUserID($username)
905    {
906        $db =& DB::getInstance();
907
908        $this->initDB();
909
910        $qid = $db->query("
911            SELECT " . $this->_params['db_primary_key'] . "
912            FROM " . $this->_params['db_table'] . "
913            WHERE " . $this->_params['db_username_column'] . " = '" . $db->escapeString($username) . "'
914        ");
915        if (list($user_id) = mysql_fetch_row($qid)) {
916            return $user_id;
917        } else {
918            return false;
919        }
920    }
921
[500]922    /*
923    * Generate a cryptographically secure, random password.
924    *
925    * @access   public
926    * @param    int  $bytes     Length of password (in bytes)
927    * @return   string          Random string of characters.
928    * @author   Quinn Comendant <quinn@strangecode.com>
929    * @version  1.0
930    * @since    15 Nov 2014 20:30:27
931    */
932    public function generatePassword($bytes=10)
[1]933    {
[174]934        $app =& App::getInstance();
[500]935
936        $bytes = is_numeric($bytes) ? $bytes : 10;
937        $string = strtok(base64_encode(openssl_random_pseudo_bytes($bytes, $strong)), '=');
938        if (!$strong) {
939            $app->logMsg(sprintf('Password generated was not "cryptographically strong"; check your openssl.', null), LOG_NOTICE, __FILE__, __LINE__);
[174]940        }
[500]941
942        return $string;
[1]943    }
[42]944
[1]945    /**
946     *
947     */
[501]948    public function encryptPassword($password, $salt=null, $hash_type=null)
[1]949    {
[136]950        $app =& App::getInstance();
[453]951
[500]952        $password = (string)$password;
953
[501]954        // Existing password hashes rely on the same key/salt being used to compare hashs.
[334]955        // Don't change this (or the value applied to signing_key) unless you know existing hashes or signatures will not be affected!
[136]956        $more_salt = 'B36D18E5-3FE4-4D58-8150-F26642852B81';
[453]957
[501]958        $hash_type = isset($hash_type) && !empty($hash_type) ? $hash_type : $this->getParam('hash_type');
959
960        switch ($hash_type) {
[468]961        case self::ENCRYPT_PLAINTEXT :
[500]962            $encrypted_password = $password;
[1]963            break;
[42]964
[468]965        case self::ENCRYPT_CRYPT :
[500]966            // If comparing password with an existing hashed password, provide the hashed password as the salt.
967            $encrypted_password = isset($salt) ? crypt($password, $salt) : crypt($password);
[1]968            break;
[42]969
[468]970        case self::ENCRYPT_SHA1 :
[500]971            $encrypted_password = sha1($password);
[15]972            break;
[42]973
[468]974        case self::ENCRYPT_SHA1_HARDENED :
[500]975            $encrypted_password = sha1($app->getParam('signing_key') . $password . $more_salt);
976            for ($i=0; $i < pow(2, 20); $i++) {
977                $encrypted_password = sha1($password . $encrypted_password);
[453]978            }
[136]979            break;
980
[468]981        case self::ENCRYPT_MD5 :
[500]982            $encrypted_password = md5($password);
[136]983            break;
984
[468]985        case self::ENCRYPT_MD5_HARDENED :
[500]986            $encrypted_password = md5($app->getParam('signing_key') . $password . $more_salt);
987            for ($i=0; $i < pow(2, 20); $i++) {
988                $encrypted_password = md5($password . $encrypted_password);
[453]989            }
[136]990            break;
[371]991
[500]992        case self::ENCRYPT_PASSWORD_BCRYPT :
993            $encrypted_password = password_hash($password, PASSWORD_BCRYPT, array('cost' => 12));
994            break;
995
996        case self::ENCRYPT_PASSWORD_DEFAULT :
997            $encrypted_password = password_hash($password, PASSWORD_DEFAULT, array('cost' => 12));
998            break;
999
[1]1000        default :
[501]1001            $app->logMsg(sprintf('Unknown hash type: %s', $hash_type), LOG_WARNING, __FILE__, __LINE__);
[136]1002            return false;
[1]1003        }
[500]1004
1005        // In case our hashing function returns 'false' or another empty value, bail out.
1006        if ('' == trim((string)$encrypted_password)) {
[501]1007            $app->logMsg(sprintf('Invalid password hash returned ("%s") for hash type %s; check yo crypto!', $encrypted_password, $hash_type), LOG_ALERT, __FILE__, __LINE__);
[500]1008            return false;
1009        }
1010
1011        return $encrypted_password;
[1]1012    }
1013
[500]1014    /*
1015    *
1016    *
1017    * @access   public
1018    * @param
1019    * @return
1020    * @author   Quinn Comendant <quinn@strangecode.com>
1021    * @version  1.0
1022    * @since    15 Nov 2014 21:37:28
1023    */
[501]1024    public function verifyPassword($password, $encrypted_password, $hash_type=null)
[500]1025    {
[501]1026        $app =& App::getInstance();
1027
1028        $hash_type = isset($hash_type) && !empty($hash_type) ? $hash_type : $this->getParam('hash_type');
1029
1030        switch ($hash_type) {
[500]1031        case self::ENCRYPT_CRYPT :
[541]1032            return $this->encryptPassword($password, $encrypted_password, $hash_type) == $encrypted_password;
[500]1033
1034        case self::ENCRYPT_PLAINTEXT :
1035        case self::ENCRYPT_MD5 :
1036        case self::ENCRYPT_MD5_HARDENED :
1037        case self::ENCRYPT_SHA1 :
1038        case self::ENCRYPT_SHA1_HARDENED :
[541]1039            return $this->encryptPassword($password, $encrypted_password, $hash_type) == $encrypted_password;
[500]1040
1041        case self::ENCRYPT_PASSWORD_BCRYPT :
1042        case self::ENCRYPT_PASSWORD_DEFAULT :
1043            return password_verify($password, $encrypted_password);
[541]1044
1045        default :
1046            $app->logMsg(sprintf('Unknown hash type: %s', $hash_type), LOG_WARNING, __FILE__, __LINE__);
1047            return false;
[500]1048        }
[501]1049
[500]1050    }
1051
[1]1052    /**
[42]1053     *
[1]1054     */
[501]1055    public function setPassword($user_id=null, $password, $hash_type=null)
[42]1056    {
[479]1057        $app =& App::getInstance();
1058        $db =& DB::getInstance();
[453]1059
[1]1060        $this->initDB();
[42]1061
[1]1062        // Get user_id if specified.
[148]1063        $user_id = isset($user_id) ? $user_id : $this->get('user_id');
[42]1064
[501]1065        // New hash type.
1066        $hash_type = isset($hash_type) ? $hash_type : $this->getParam('hash_type');
[453]1067
[500]1068        // Save the hash method used if a table exists for it.
[501]1069        $userpass_hashtype_clause = '';
[500]1070        if ($db->columnExists($this->_params['db_table'], 'userpass_hashtype', false)) {
[501]1071            $userpass_hashtype_clause = ", userpass_hashtype = '" . $db->escapeString($hash_type) . "'";
[500]1072        }
1073
[1]1074        // Issue the password change query.
[136]1075        $db->query("
[502]1076            UPDATE " . $this->_params['db_table'] . " SET
1077                userpass = '" . $db->escapeString($this->encryptPassword($password, null, $hash_type)) . "',
1078                modified_datetime = NOW(),
1079                modified_by_user_id = '" . $db->escapeString($user_id) . "'
1080                $userpass_hashtype_clause
[136]1081            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
[1]1082        ");
[453]1083
[136]1084        if (mysql_affected_rows($db->getDBH()) != 1) {
[501]1085            $app->logMsg(sprintf('Failed to update password for user_id %s (no affected rows)', $user_id), LOG_WARNING, __FILE__, __LINE__);
[229]1086            return false;
[119]1087        }
[453]1088
[500]1089        $app->logMsg(sprintf('Password change successful for user_id %s', $user_id), LOG_INFO, __FILE__, __LINE__);
[229]1090        return true;
[1]1091    }
1092
1093    /**
1094     * Resets the password for the user with the specified id.
1095     *
1096     * @param  string $user_id   The id of the user to reset.
1097     * @param  string $reason    Additional message to add to the reset email.
1098     * @return string            The user's new password.
1099     */
[468]1100    public function resetPassword($user_id=null, $reason='')
[1]1101    {
[479]1102        $app =& App::getInstance();
1103        $db =& DB::getInstance();
[453]1104
[1]1105        $this->initDB();
[42]1106
[1]1107        // Get user_id if specified.
[148]1108        $user_id = isset($user_id) ? $user_id : $this->get('user_id');
[42]1109
[1]1110        // Reset password of a specific user.
[136]1111        $qid = $db->query("
[1]1112            SELECT * FROM " . $this->_params['db_table'] . "
[136]1113            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
[1]1114        ");
[15]1115        if (!$user_data = mysql_fetch_assoc($qid)) {
[372]1116            $app->logMsg(sprintf('Reset password failed. User_id %s not found.', $user_id), LOG_NOTICE, __FILE__, __LINE__);
[15]1117            return false;
1118        }
[42]1119
[1]1120        // Get new password.
1121        $password = $this->generatePassword();
[42]1122
[1]1123        // Update password query.
1124        $this->setPassword($user_id, $password);
[41]1125
[43]1126        // Make sure user has an email on record before continuing.
1127        if (!isset($user_data['email']) || '' == trim($user_data['email'])) {
[372]1128            $app->logMsg(sprintf('Password reset but notification failed, no email address for user_id %s (%s).', $user_data[$this->_params['db_primary_key']], $user_data[$this->_params['db_username_column']]), LOG_NOTICE, __FILE__, __LINE__);
[43]1129        } else {
[189]1130            // Send the new password in an email.
[43]1131            $email = new Email(array(
1132                'to' => $user_data['email'],
[550]1133                'from' => sprintf('"%s" <%s>', addcslashes($app->getParam('site_name'), '"'), $app->getParam('site_email')),
[136]1134                'subject' => sprintf('%s password change', $app->getParam('site_name'))
[43]1135            ));
[189]1136            $email->setTemplate('codebase/services/templates/email_reset_password.txt');
[43]1137            $email->replace(array(
[189]1138                'SITE_NAME' => $app->getParam('site_name'),
1139                'SITE_URL' => $app->getParam('site_url'),
1140                'SITE_EMAIL' => $app->getParam('site_email'),
1141                'NAME' => ('' != $user_data['first_name'] . $user_data['last_name'] ? $user_data['first_name'] . ' ' . $user_data['last_name'] : $user_data[$this->_params['db_username_column']]),
1142                'USERNAME' => $user_data[$this->_params['db_username_column']],
1143                'PASSWORD' => $password,
[334]1144                'REASON' => ('' == trim($reason) ? '' : trim($reason) . ' '), // Add a space after the reason if it exists for better formatting.
[43]1145            ));
1146            $email->send();
1147        }
[41]1148
[15]1149        return array(
[42]1150            'username' => $user_data[$this->_params['db_username_column']],
[15]1151            'userpass' => $password
1152        );
[1]1153    }
[42]1154
[500]1155} // end class
Note: See TracBrowser for help on using the repository browser.