tbauth.php3 10.3 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
    $query_result =
86
	DBQueryFatal("select NOW()>=u.pswd_expires,l.hashkey,l.timeout,status".
87 88 89
		     " 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
    $expired = $row[0];
    $hashkey = $row[1];
    $timeout = $row[2];
99
    $status  = $row[3];
100 101 102 103 104 105

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

107 108 109 110 111 112 113 114 115 116
    #
    # Check for frozen account.
    #
    if ($status == $TBDB_USERSTATUS_FROZEN) {
	DBQueryFatal("DELETE FROM login WHERE uid='$uid'");
	return $CHECKLOGIN_NOTLOGGEDIN;
    }

    # If not frozen and its a match, compare the timeout and hash.
    # 
117 118 119 120 121 122 123 124 125
    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;

126 127 128 129 130 131 132 133
	    $query_result =
		DBQueryFatal("UPDATE login set timeout='$timeout' ".
			     "WHERE uid='$uid'");

	    if ($expired)
		return $CHECKLOGIN_PSWDEXPIRED;
	    else
		return $CHECKLOGIN_LOGGEDIN;
134 135 136 137 138 139
	}
	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.
	    # 
140 141 142 143
	    if ($expired)
		return $CHECKLOGIN_PSWDEXPIRED;
	    else
		return $CHECKLOGIN_MAYBEVALID;
144
	}
145 146 147
	#
	# A hashkey mismatch is the same as an expired login.
	#
148 149 150 151 152
    }

    #
    # Clear out the database entry for completeness.
    #
153 154
    $query_result =
	DBQueryFatal("DELETE FROM login WHERE uid='$uid'");
155

156
    return $CHECKLOGIN_TIMEDOUT;
157 158 159 160 161 162 163
}

#
# This one checks for login, but then dies with an appropriate error
# message.
#
function LOGGEDINORDIE($uid) {
164 165
    global $CHECKLOGIN_NOTLOGGEDIN, $CHECKLOGIN_LOGGEDIN;
    global $CHECKLOGIN_TIMEDOUT, $CHECKLOGIN_MAYBEVALID;
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
    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;
196

197
    $status = CHECKLOGIN($uid);
198
    switch ($status) {
199 200
    case $CHECKLOGIN_NOTLOGGEDIN:
        USERERROR("You do not appear to be logged in!", 1);
201
        break;
202
    case $CHECKLOGIN_LOGGEDIN:
203
    case $CHECKLOGIN_PSWDEXPIRED:
204 205
        return $uid;
        break;
206
    case $CHECKLOGIN_TIMEDOUT:
207 208
        USERERROR("Your login has timed out! Please log in again.", 1);
        break;
209 210 211
    case $CHECKLOGIN_MAYBEVALID:
        USERERROR("Your login cannot be verified. Are cookies turned on?", 1);
        break;
212 213 214 215 216 217 218 219 220
    }
    TBERROR("LOGGEDINORDIE failed mysteriously", 1);
}

#
# Attempt a login.
# 
function DOLOGIN($uid, $password) {
    global $TBDBNAME, $TBAUTHCOOKIE, $TBAUTHDOMAIN, $TBAUTHTIMEOUT;
221
    global $TBNAMECOOKIE, $TBSECURECOOKIES;
222

223 224 225 226 227
    if (! isset($password) ||
	strcmp($password, "") == 0) {
	return -1;
    }

228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    $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. 
        #
251
	$timeout = time() + $TBAUTHTIMEOUT;
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
	$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);
        }

271 272 273 274 275 276
	#
	# Create a last login record.
	#
	$query_result = mysql_db_query($TBDBNAME,
	       "REPLACE into lastlogin (uid, time) VALUES ('$uid', NOW())");

277
	#
278 279 280 281 282 283 284 285 286
	# 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. 
287
	#
288
	$timeout = time() + (60 * 60 * 24);
289 290
	setcookie($TBAUTHCOOKIE, $hashkey, $timeout, "/",
                  $TBAUTHDOMAIN, $TBSECURECOOKIES);
291

292 293 294 295 296 297 298 299 300 301 302
	#
	# 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);

303 304 305 306 307 308 309 310 311 312 313 314 315 316
	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) {
317
    global $TBDBNAME, $TBSECURECOOKIES;
318 319 320 321 322 323 324 325 326 327 328 329 330 331

    $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];
332
    $timeout = time() - 1000000;
333 334 335 336 337 338 339

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

    #
    # Issue a cookie request to delete the cookie. 
    #
340
    setcookie($TBAUTHCOOKIE, "", $timeout, "/", $TBAUTHDOMAIN, 0);
341 342 343 344

    return 0;
}

345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
#
# 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;
}

367 368 369 370 371 372 373 374 375 376 377 378 379
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;
}

380 381 382 383
#
# Beware empty spaces (cookies)!
# 
?>