tbauth.php3 9.94 KB
Newer Older
1 2 3
<?php
#
# Login support: Beware empty spaces (cookies)!
4 5 6 7 8 9
#

$CHECKLOGIN_NOTLOGGEDIN = 0;
$CHECKLOGIN_LOGGEDIN    = 1;
$CHECKLOGIN_TIMEDOUT    = -1;
$CHECKLOGIN_MAYBEVALID  = 2;
10
$CHECKLOGIN_PSWDEXPIRED = 3;
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

#
# Generate a hash value suitable for authorization. We use the results of
# microtime, combined with a random number.
# 
function GENHASH() {
    $fp = fopen("/dev/urandom", "r");
    if (! $fp) {
        TBERROR("Error opening /dev/urandom", 1);
    }
    $random_bytes = fread($fp, 8);
    fclose($fp);

    $hash  = mhash (MHASH_MD5, bin2hex($retval) . " " . microtime());
    return bin2hex($hash);
}

28 29 30
#
# Return the value of the currently logged in uid, or null if not
# logged in. Basically, check the browser to see if its sending a UID
31
# and HASH back, and then check the DB to see if the user is really
32 33 34
# logged in.
# 
function GETLOGIN() {
35
    global $CHECKLOGIN_LOGGEDIN, $CHECKLOGIN_PSWDEXPIRED;
36

37 38 39
    if (($uid = GETUID()) == FALSE)
	    return FALSE;

40 41 42 43
    $check = CHECKLOGIN($uid);

    if ($check == $CHECKLOGIN_LOGGEDIN ||
	$check == $CHECKLOGIN_PSWDEXPIRED)
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
	    return $uid;

    return FALSE;
}

#
# Return the value of the UID cookie. This does not check to see if
# this person is currently logged in. We just want to know what the
# browser thinks, if anything.
# 
function GETUID() {
    global $TBNAMECOOKIE, $HTTP_COOKIE_VARS;

    $curname = $HTTP_COOKIE_VARS[$TBNAMECOOKIE];
    if ($curname == NULL)
	    return FALSE;

    return $curname;
}

64
#
65
# Verify a login by sucking a UIDs current hash value out of the database.
66 67 68
# If the login has expired, or of the hashkey in the database does not
# match what came back in the cookie, then the UID is no longer logged in.
#
69 70 71 72 73 74
# Returns: if not logged in ever.
#          if logged in okay
#          if login timed out
#          if login record exists, is not timed out, but no hash cookie.
#             this case will be caught later when the user tries to do
#             something for which a valid login is required.
75
#	   if logged in okay but password is expired.
76
#
77
function CHECKLOGIN($uid) {
78
    global $TBDBNAME, $TBAUTHCOOKIE, $HTTP_COOKIE_VARS, $TBAUTHTIMEOUT;
79 80
    global $CHECKLOGIN_NOTLOGGEDIN, $CHECKLOGIN_LOGGEDIN;
    global $CHECKLOGIN_TIMEDOUT, $CHECKLOGIN_MAYBEVALID;
81
    global $CHECKLOGIN_PSWDEXPIRED;
82 83

    $curhash = $HTTP_COOKIE_VARS[$TBAUTHCOOKIE];
84

85 86 87 88 89
    $query_result =
	DBQueryFatal("select NOW()>=u.pswd_expires,l.hashkey,l.timeout ".
		     " from users as u ".
		     "left join login as l on l.uid=u.uid ".
		     "where u.uid='$uid'");
90

91 92
    # No such user.
    if (($row = mysql_fetch_row($query_result)) == 0) {
93
	return $CHECKLOGIN_NOTLOGGEDIN;
94 95
    }

96 97 98 99 100 101 102 103 104
    $expired = $row[0];
    $hashkey = $row[1];
    $timeout = $row[2];

    #
    # If user exists, but login has no entry, quit now.
    #
    if (!$hashkey)
	return $CHECKLOGIN_NOTLOGGEDIN;
105 106

    # A match?
107 108 109 110 111 112 113 114 115
    if ($timeout > time()) {
        if (strcmp($curhash, $hashkey) == 0) {
	    #
   	    # We update the time in the database. Basically, each time the
	    # user does something, we bump the logout further into the future.
	    # This avoids timing them out just when they are doing useful work.
	    #
	    $timeout = time() + $TBAUTHTIMEOUT;

116 117 118 119 120 121 122 123
	    $query_result =
		DBQueryFatal("UPDATE login set timeout='$timeout' ".
			     "WHERE uid='$uid'");

	    if ($expired)
		return $CHECKLOGIN_PSWDEXPIRED;
	    else
		return $CHECKLOGIN_LOGGEDIN;
124 125 126 127 128 129
	}
	elseif (!isset($curhash) || !$curhash || $curhash == NULL) {
	    #
	    # A login is valid, but we have no proof yet. Proof will be
	    # demanded later by whatever page wants it.
	    # 
130 131 132 133
	    if ($expired)
		return $CHECKLOGIN_PSWDEXPIRED;
	    else
		return $CHECKLOGIN_MAYBEVALID;
134
	}
135 136 137 138 139
    }

    #
    # Clear out the database entry for completeness.
    #
140 141
    $query_result =
	DBQueryFatal("DELETE FROM login WHERE uid='$uid'");
142

143
    return $CHECKLOGIN_TIMEDOUT;
144 145 146 147 148 149 150
}

#
# This one checks for login, but then dies with an appropriate error
# message.
#
function LOGGEDINORDIE($uid) {
151 152
    global $CHECKLOGIN_NOTLOGGEDIN, $CHECKLOGIN_LOGGEDIN;
    global $CHECKLOGIN_TIMEDOUT, $CHECKLOGIN_MAYBEVALID;
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    global $CHECKLOGIN_PSWDEXPIRED;

    $status = CHECKLOGIN($uid);
    switch ($status) {
    case $CHECKLOGIN_NOTLOGGEDIN:
        USERERROR("You do not appear to be logged in!", 1);
        break;
    case $CHECKLOGIN_LOGGEDIN:
        return $uid;
        break;
    case $CHECKLOGIN_TIMEDOUT:
        USERERROR("Your login has timed out! Please log in again.", 1);
        break;
    case $CHECKLOGIN_MAYBEVALID:
        USERERROR("Your login cannot be verified. Are cookies turned on?", 1);
        break;
    case $CHECKLOGIN_PSWDEXPIRED:
        USERERROR("Your password has expired. Please change it now!", 1);
        break;
    }
    TBERROR("LOGGEDINORDIE failed mysteriously", 1);
}

#
# Special function for changing passwords.
#
function LOGGEDINORDIE_SPECIAL($uid) {
    global $CHECKLOGIN_NOTLOGGEDIN, $CHECKLOGIN_LOGGEDIN;
    global $CHECKLOGIN_TIMEDOUT, $CHECKLOGIN_MAYBEVALID;
    global $CHECKLOGIN_PSWDEXPIRED;
183

184
    $status = CHECKLOGIN($uid);
185
    switch ($status) {
186 187
    case $CHECKLOGIN_NOTLOGGEDIN:
        USERERROR("You do not appear to be logged in!", 1);
188
        break;
189
    case $CHECKLOGIN_LOGGEDIN:
190
    case $CHECKLOGIN_PSWDEXPIRED:
191 192
        return $uid;
        break;
193
    case $CHECKLOGIN_TIMEDOUT:
194 195
        USERERROR("Your login has timed out! Please log in again.", 1);
        break;
196 197 198
    case $CHECKLOGIN_MAYBEVALID:
        USERERROR("Your login cannot be verified. Are cookies turned on?", 1);
        break;
199 200 201 202 203 204 205 206 207
    }
    TBERROR("LOGGEDINORDIE failed mysteriously", 1);
}

#
# Attempt a login.
# 
function DOLOGIN($uid, $password) {
    global $TBDBNAME, $TBAUTHCOOKIE, $TBAUTHDOMAIN, $TBAUTHTIMEOUT;
208
    global $TBNAMECOOKIE, $TBSECURECOOKIES;
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232

    $query_result = mysql_db_query($TBDBNAME,
	"SELECT usr_pswd FROM users WHERE uid=\"$uid\"");
    if (! $query_result) {
        $err = mysql_error();
        TBERROR("Database Error retrieving password for $uid: $err\n", 1);
    }

    #
    # Check password in the database against provided. 
    #
    if ($row = mysql_fetch_row($query_result)) {
        $db_encoding = $row[0];
        $salt = substr($db_encoding, 0, 2);
        if ($salt[0] == $salt[1]) { $salt = $salt[0]; }
        $encoding = crypt("$password", $salt);
        if (strcmp($encoding, $db_encoding)) {
            return -1;
        }
        #
        # Pass! Insert a record in the login table for this uid with
        # the new hash value. If the user is already logged in, thats
        # okay; just update it in place with a new hash and timeout. 
        #
233
	$timeout = time() + $TBAUTHTIMEOUT;
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
	$hashkey = GENHASH();
        $query_result = mysql_db_query($TBDBNAME,
		"SELECT timeout FROM login WHERE uid=\"$uid\"");
	if (mysql_num_rows($query_result)) {
		$query_result = mysql_db_query($TBDBNAME,
			"UPDATE login set ".
			"timeout='$timeout', hashkey='$hashkey' ".
			"WHERE uid=\"$uid\"");
	}
	else {
		$query_result = mysql_db_query($TBDBNAME,
			"INSERT into login (uid, hashkey, timeout) ".
                        "VALUES ('$uid', '$hashkey', '$timeout')");
	}
        if (! $query_result) {
            $err = mysql_error();
            TBERROR("Database Error logging in $uid: $err\n", 1);
        }

253 254 255 256 257 258
	#
	# Create a last login record.
	#
	$query_result = mysql_db_query($TBDBNAME,
	       "REPLACE into lastlogin (uid, time) VALUES ('$uid', NOW())");

259
	#
260 261 262 263 264 265 266 267 268
	# Issue the cookie requests so that subsequent pages come back
	# with the hash value and auth usr embedded.

	#
	# For the hashkey, we give it a longish timeout since we are going
	# to control the actual timeout via the database. This just avoids
	# having to update the hash as we update the timeout in the database
	# each time the user does something. Eventually the cookie will
	# expire and the user will be forced to log in again anyway. 
269
	#
270
	$timeout = time() + (60 * 60 * 24);
271 272
	setcookie($TBAUTHCOOKIE, $hashkey, $timeout, "/",
                  $TBAUTHDOMAIN, $TBSECURECOOKIES);
273

274 275 276 277 278 279 280 281 282 283 284
	#
	# We give this a really long timeout. We want to remember who the
	# the user was each time they load a page, and more importantly,
	# each time they come back to the main page so we can fill in their
	# user name. NOTE: This cookie is integral to authorization, since
	# we do not pass around the UID anymore, but look for it in the
	# cookie.
	# 
	$timeout = time() + (60 * 60 * 24 * 32);
	setcookie($TBNAMECOOKIE, $uid, $timeout, "/", $TBAUTHDOMAIN, 0);

285 286 287 288 289 290 291 292 293 294 295 296 297 298
	return 0;
    }
    #
    # No such user
    #
    return -1;
}

#
# Log out a UID. Simply clear the entry from the login table.
#
# Should we kill the cookie? 
# 
function DOLOGOUT($uid) {
299
    global $TBDBNAME, $TBSECURECOOKIES;
300 301 302 303 304 305 306 307 308 309 310 311 312 313

    $query_result = mysql_db_query($TBDBNAME,
	"SELECT hashkey timeout FROM login WHERE uid=\"$uid\"");
    if (! $query_result) {
        $err = mysql_error();
        TBERROR("Database Error retrieving login info for $uid: $err\n", 1);
    }

    # Not logged in.
    if (($row = mysql_fetch_array($query_result)) == 0) {
	return 0;
    }

    $hashkey = $row[hashkey];
314
    $timeout = time() - 1000000;
315 316 317 318 319 320 321

    $query_result = mysql_db_query($TBDBNAME,
	"DELETE FROM login WHERE uid=\"$uid\"");

    #
    # Issue a cookie request to delete the cookie. 
    #
322
    setcookie($TBAUTHCOOKIE, "", $timeout, "/", $TBAUTHDOMAIN, 0);
323 324 325 326

    return 0;
}

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
#
# Primitive "nologins" support.
#
function NOLOGINS() {
    global $TBDBNAME;

    $query_result = mysql_db_query($TBDBNAME,
	"SELECT nologins FROM nologins where nologins=1");
    if (! $query_result) {
        $err = mysql_error();
        TBERROR("Database Error nologins info: $err\n", 1);
    }

    # No entry
    if (($row = mysql_fetch_array($query_result)) == 0) {
	return 0;
    }

    $nologins = $row[nologins];
    return $nologins;
}

349 350 351 352 353 354 355 356 357 358 359 360 361
function LASTWEBLOGIN($uid) {
    global $TBDBNAME;

    $query_result = mysql_db_query($TBDBNAME,
	"SELECT time from lastlogin where uid=\"$uid\"");
    
    if (mysql_num_rows($query_result)) {
	$lastrow      = mysql_fetch_array($query_result);
	return $lastrow[time];
    }
    return 0;
}

362 363 364 365
#
# Beware empty spaces (cookies)!
# 
?>