Jump to content

Using an authcode stored in a cookie to automatically log a user in.


andrew_biggart

Recommended Posts

I am trying to create a remember me checkbox for the login of my CMS.

 

What I am trying to achieve is that whenever a user logs in with the checkbox ticked and auth code is created and stored in a cookie and also the database under their user info row. When I user closes their browser without logging out and then returns to the CMS a few days later etc I am trying to run some code straight away if they get redirected to the login page. The code will check to see if the auth code cookie exists, if it does it gets checked against the database records, if a match is found then log that user in. If it doesn't do nothing until the user uses the login form.

 

I have written what I though was the perfect solution but it never seems to automatically log the user in, even if they haven't logged out. Some direction in this matter would be very helpful, thank you.

 

I would also like to know if there is a way of using php to stop my session getting cleared by the trash collector after some inactivity?

 

 

 

Login.php  (I am using PHpass for the password hashing)

 

<?php include ('functions.php'); ?>
<?php get_header('login'); ?>
    <div id="login-result">
    <?php
	$redirect = htmlspecialchars(mysql_real_escape_string(addslashes($_GET['redirect'])));

	if(isset($_COOKIE['authcode'])){

		connect();

		$authcookie  = htmlspecialchars(mysql_real_escape_string(addslashes($_COOKIE['authcode'])));

		$sql         = "SELECT uid, username, firstname, lastname, role FROM usersT WHERE authcode='$authcode'";
		$result      = mysql_query($sql);
		$count       = mysql_num_rows($result);
		$row         = mysql_fetch_array($result);

		$uid         = $row['uid'];
		$username    = $row['username'];
		$fname       = $row['firstname'];
		$lname       = $row['lastname'];
		$role        = $row['role'];

   
		if($count==1){
			$sql2    = "UPDATE usersT SET status = '1' WHERE uid = '$uid'";
			$result2 = mysql_query($sql2);

			if($result2){

				session_register("uid");
				session_register("uname");
				session_register("ulevel");
				$_SESSION["uid"]       = $uid;
				$_SESSION["username"]  = $username;
				$_SESSION["uname"]     = $fname;
				$_SESSION["ufullname"] = $fname . " " .$lname;
				$_SESSION["urole"]     = $role;

				if(!empty($redirect)) {
					header( 'Location: '. $redirect ) ;
					exit(); 
				}
				else {
					header( 'Location: index.php' ) ;
					exit();
				}

			}

		}

	}
?>
    <?php
	if (isset($_POST['admin_login'])){

		if(isset($_POST["username"]) && isset($_POST["password"])){

			connect();

			$username_p        = htmlspecialchars(mysql_real_escape_string(addslashes($_POST["username"])));
			$password_p        = htmlspecialchars(mysql_real_escape_string(addslashes($_POST["password"])));

			if (strlen($password_1) < 73) {

				//Password hashing

				$sql3          = "SELECT password FROM usersT WHERE username='$username_p'";
				$result3       = mysql_query($sql3);
				$row3          = mysql_fetch_array($result3);

				require("inc/password-hash.php");
				$hasher        = new PasswordHash(8, false);
				$stored_hash   = "*";
				$stored_hash   = $row3['password'];
				$check         = $hasher->CheckPassword($password_p, $stored_hash);

				if($check){

					$sql4      = "SELECT uid, username, firstname, lastname, role FROM usersT WHERE username='$username_p'";
					$result4   = mysql_query($sql4);
					$row4      = mysql_fetch_array($result4);

					$uid       = $row4['uid'];
					$username  = $row4['username'];
					$fname     = $row4['firstname'];
					$lname     = $row4['lastname'];
					$role      = $row4['role'];

					$authcode  = random(30);
					$sql5      = "UPDATE usersT SET status = '1', authcode = '$authcode' WHERE uid = '$uid'";
					$result5   = mysql_query($sql5);

					if($result5){

						session_register("uid");
						session_register("uname");
						session_register("ulevel");
						$_SESSION["uid"]        = $uid;
						$_SESSION["username"]   = $username;
						$_SESSION["uname"]      = $fname;
						$_SESSION["ufullname"]  = $fname . " " .$lname;
						$_SESSION["urole"]      = $role;

						if(isset($_POST['remember'])) { 
							setcookie("authcode", $authcode, time() + 86400 * 365 * 2); 
						} // Check if the user wants to be remembered.

						if(!empty($redirect)) {
							header( 'Location: '. $redirect ) ;
							exit(); 
						} // Check if the user has been redirected from another page.
						else {
							header( 'Location: index.php' ) ;
							exit();
						}

					} // Check if the users status has been updated.
					else {
						echo "<div class=\"error rounded5 shadow\">User status couldn't be updated!</div>";
					}

				} // Check the entered password against the stored hash.
				else {
					echo "<div class=\"error rounded5 shadow\">Invalid username or password!</div>";
				}

			} // Checked the character length of the password.
			else {
				echo "<div class=\"error rounded5 shadow\">Password must be 72 characters or less!</div>";
			}

		} // Check both fields have been filled in.

	} // Check the user has submitted the data.	

?>
    </div><!-- / login-results -->
    <div id="login" class="rounded5 shadow">
	<form name="loginform" id="loginform" action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
            <p>
                <label for="username">Username<br>
                <input type="text" name="username" id="username" class="rounded5" value="<?php echo $username_p; ?>" size="20" tabindex="10" /></label>
            </p>
            <p>
                <label for="password">Password<br>
                <input type="password" name="password" id="password" class="rounded5" value="<?php echo $password_p; ?>" size="20" tabindex="20" maxlength="72" /></label>
            </p>
            <p class="submit">
            	Keep me logged in <input type="checkbox" name="remember" id="remember" <?php if(isset($_COOKIE['remembered'])){ echo "selected=\"selected\""; } ?>  /><br /><br /><a href="" class="left">Lost your password?</a>
                <input type="submit" name="admin_login" id="admin_login" class="btn rounded10 right" value="Log In" tabindex="100" />
            </p>
            <div class="cleaner"></div><!-- / cleaner -->
        </form>
    </div><!-- / login-->
<?php get_footer('login'); ?>

 

 

 

 

Logout.php

 

<?php
session_start();
include ('functions.php');
connect();
$uid    = mysql_real_escape_string($_SESSION['uid']);
$sql    = "UPDATE usersT SET status = '0', authcode = '' WHERE uid = '$uid'";
$result = mysql_query($sql);

if($result) {
	session_unset(); 
	session_destroy(); 
	setcookie("authcode", $authcode, time() - 86400 * 365 * 2); 
	header("location:" . get_option('home') . "/login.php");
	exit();
}
else {
	exit();
}
?> 

 

 

Redirect Code

 

<?php 
session_start();
$url   = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$uid   = $_SESSION['uid'];
if (!isset($uid)) {
	header('location:login.php?redirect='.$url);
	exit();
	die();
}
?>

Link to comment
Share on other sites

There's a couple things that stuck out in your script that are wrong:

1. You don't need to use addslashes and mysql_real_escape_string at the same time - that will just end up looking like: a string \\\' with a quote in it which will then be saved in your database as: a string \' with a quote in it.

 

2. You are using session_register which is deprecated as of PHP 5.3 and completely removed as of PHP 5.4.

 

 

As for your problem, this is where debugging comes in. Skimming quickly I didn't see anything too obvious, so it's up to you to make sure things are right. Some things to try:

- What is the value of $authcode? Does it match what is in the database?

- Are you getting any rows returned when you match the authcode?

- Was the cookie set properly?

 

As for the session garbage collection, you can change everything about that. Here is three settings you can change to alter the behavior of the garbage collection: http://us.php.net/manual/en/session.configuration.php#ini.session.gc-probability

 

Namely: gc_probability, gc_divisor, and gc_maxlifetime.

Link to comment
Share on other sites

Absolute schoolboy error, the problem was I was using '$authcode' as the variable in the WHERE statement but I was saving the cookie as '$authcookie'.

 

Modified code:

 

$authcookie  = htmlspecialchars(mysql_real_escape_string($_COOKIE['authcode']));
$sql         = "SELECT uid, username, firstname, lastname, role FROM usersT WHERE authcode='$authcookie'";

 

I have also removed the addslashes and session_register, thanks for the advice.

 

I guess now this is working properly I won't need to worry about trash collection, because if the session times out they will get redirected to the login page, the cookie will be checked, re-log them in and redirect them. So basically they won't realise they have even been timed out. Obviously this won't happen if they haven't checked remember me... That'll teach them!

Link to comment
Share on other sites

For anyone who is interested, and would like to either use this code or learn from it here is the working code.

 

I have also added a user id cookie to use as a further check. It is used if the auth code cannot be found in the database, it checks if the user id row from the cookie auth code field is empty. If it isn't  it lets the user know that their authentication has expired because they have logged in on a new computer / browser and created a new auth code.

 

Login.php

	<?php include ('functions.php'); ?>
<?php get_header('login'); ?>
    <div id="login-result">
    <?php
	$redirect = htmlspecialchars(mysql_real_escape_string($_GET['redirect']));

	if(isset($_COOKIE['authcode'])){

		connect();

		$authcookie  = htmlspecialchars(mysql_real_escape_string($_COOKIE['authcode']));

		$sql         = "SELECT uid, username, firstname, lastname, role FROM usersT WHERE authcode='$authcookie'";
		$result      = mysql_query($sql);
		$count       = mysql_num_rows($result);
		$row         = mysql_fetch_array($result);

		$uid         = $row['uid'];
		$username    = $row['username'];
		$fname       = $row['firstname'];
		$lname       = $row['lastname'];
		$role        = $row['role'];

   
		if($count==1){

			$new_authcode  = random(30);
			$sql2    = "UPDATE usersT SET status = '1', authcode = '$new_authcode' WHERE uid = '$uid'";
			$result2 = mysql_query($sql2);

			if($result2){

				$_SESSION["uid"]       = $uid;
				$_SESSION["username"]  = $username;
				$_SESSION["uname"]     = $fname;
				$_SESSION["ufullname"] = $fname . " " .$lname;
				$_SESSION["urole"]     = $role;
				setcookie("uid", $uid, time() + 86400 * 365 * 2);
				setcookie("authcode", $new_authcode, time() + 86400 * 365 * 2);

				if(!empty($redirect)) {
					header( 'Location: '. $redirect ) ;
					exit(); 
				}
				else {
					header( 'Location: index.php' ) ;
					exit();
				}

			}

		}
		else {

			connect();
			$uid3     = $_COOKIE['uid'];
			$sql3     = "SELECT username FROM usersT WHERE uid = '$uid3' AND authcode != ''";
			$result3  = mysql_query($sql3);
			$count3   = mysql_num_rows($result3);
			$row3     = mysql_fetch_array($result3);
			$username = $row3['username'];

			if($count3 > 0) {
				setcookie("authcode", $authcode, time() - 86400 * 365 * 2);
				echo "<div class=\"error rounded5 shadow\">Authentication expired for $username! Please login.</div>";
			}

		}


	}
?>
    <?php
	if (isset($_POST['admin_login'])){

		if(isset($_POST["username"]) && isset($_POST["password"])){

			connect();

			$username_p        = htmlspecialchars(mysql_real_escape_string($_POST["username"]));
			$password_p        = htmlspecialchars(mysql_real_escape_string($_POST["password"]));

			if (strlen($password_p) < 73) {

				$sql4          = "SELECT password FROM usersT WHERE username='$username_p'";
				$result4       = mysql_query($sql4);
				$row4          = mysql_fetch_array($result4);

				//Password hashing
				require("inc/password-hash.php");
				$hasher        = new PasswordHash(8, false);
				$stored_hash   = "*";
				$stored_hash   = $row4['password'];
				$check         = $hasher->CheckPassword($password_p, $stored_hash);

				if($check){

					$sql5      = "SELECT uid, username, firstname, lastname, role FROM usersT WHERE username='$username_p'";
					$result5   = mysql_query($sql5);
					$row5      = mysql_fetch_array($result5);

					$uid       = $row5['uid'];
					$username  = $row5['username'];
					$fname     = $row5['firstname'];
					$lname     = $row5['lastname'];
					$role      = $row5['role'];

					$authcode  = random(30);
					$sql6      = "UPDATE usersT SET status = '1', authcode = '$authcode' WHERE uid = '$uid'";
					$result6   = mysql_query($sql6);

					if($result5 && $result6){

						$_SESSION["uid"]        = $uid;
						$_SESSION["username"]   = $username;
						$_SESSION["uname"]      = $fname;
						$_SESSION["ufullname"]  = $fname . " " .$lname;
						$_SESSION["urole"]      = $role;
						setcookie("uid", $uid, time() + 86400 * 365 * 2);

						if(isset($_POST['remember'])) { 
							setcookie("authcode", $authcode, time() + 86400 * 365 * 2); 
						} // Check if the user wants to be remembered.

						if(!empty($redirect)) {
							header( 'Location: '. $redirect ) ;
							exit(); 
						} // Check if the user has been redirected from another page.
						else {
							header( 'Location: index.php' ) ;
							exit();
						}

					} // Check if the users status has been updated.
					else {
						echo "<div class=\"error rounded5 shadow\">User status couldn't be updated!</div>";
					}

				} // Check the entered password against the stored hash.
				else {
					echo "<div class=\"error rounded5 shadow\">Invalid username or password!</div>";
				}

			} // Checked the character length of the password.
			else {
				echo "<div class=\"error rounded5 shadow\">Password must be 72 characters or less!</div>";
			}

		} // Check both fields have been filled in.

	} // Check the user has submitted the data.	

?>
    </div><!-- / login-results -->
    <div id="login" class="rounded5 shadow">
	<form name="loginform" id="loginform" action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
            <p>
                <label for="username">Username<br>
                <input type="text" name="username" id="username" class="rounded5" value="<?php echo $username_p; ?>" size="20" tabindex="10" /></label>
            </p>
            <p>
                <label for="password">Password<br>
                <input type="password" name="password" id="password" class="rounded5" value="<?php echo $password_p; ?>" size="20" tabindex="20" maxlength="72" /></label>
            </p>
            <p class="submit">
            	Keep me logged in <input type="checkbox" name="remember" id="remember"  /><br /><br /><a href="" class="left">Lost your password?</a>
                <input type="submit" name="admin_login" id="admin_login" class="btn rounded10 right" value="Log In" tabindex="100" />
            </p>
            <div class="cleaner"></div><!-- / cleaner -->
        </form>
    </div><!-- / login-->
<?php get_footer('login'); ?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.