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

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

${1}

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