Jump to content

Password Reset Form


SalientAnimal

Recommended Posts

Hi All,

I am busy working on my password reset form. And I was fortunate enough to find the source code to do this, how ever I am having a few problems with the source code. When access the reset password page I ge the following two error messages:

Notice: Undefined index: lockout in C:\htdocs\includes\resetpwd.php on line 14
Notice: Undefined index: badCount in C:\htdocs\includes\resetpwd.php on line 89

Line 14:
if ($_SESSION['lockout'] == true && (mktime() > $_SESSION['lastTime'] + 900))

Line 89:
if ($_SESSION['badCount'] >= 3)

Then when entering my username the page display as intended except for the 3 error messages:

Notice: Undefined index: lockout in C:\htdocs\includes\resetpwd.php on line 14
Notice: Undefined index: lockout in C:\htdocs\includes\resetpwd.php on line 19
Notice: Undefined index: badCount in C:\htdocs\includes\resetpwd.php on line 89
Notice: Undefined index: What is your pet's name? in C:\autopage_auxilium\htdocs\includes\functions.php on line 389

Line 19:
if (isset($_POST['subStep']) && !isset($_GET['a']) && $_SESSION['lockout'] != true)

Line 389:
return $questions[$security_q];

Line 14 / 89 are the same as aboce as they come from the same file.

Despite answering the security question correctly, the form does not accept it and I do not get to a point to reset.
Any help will be appreciated.

 

 

Here is the code to the two files:

Password Reset Functions

//PSSWORD RESET FUNCTIONS




//define(PW_SALT,'(+3%_');
 
function checkUNEmail($username,$email)
{
    global $mysqli;
    $error = array('status'=>false,'user_id'=>0);
    if (isset($email) && trim($email) != '') {
        //email was entered
        if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE email = ? LIMIT 1"))
        {
            $stmt->bind_param('s',trim($email));
            $stmt->execute();
            $stmt->store_result();
            $numRows = $stmt->num_rows();
            $stmt->bind_result($user_id);
            $stmt->fetch();
            $stmt->close();
            if ($numRows >= 1) return array('status'=>true,'id'=>$user_id);
        } else { return $error; }
    } elseif (isset($username) && trim($username) != '') {
        //username was entered
        if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE username = ? LIMIT 1"))
        {
            $stmt->bind_param('s',trim($username));
            $stmt->execute();
            $stmt->store_result();
            $numRows = $stmt->num_rows();
            $stmt->bind_result($user_id);
            $stmt->fetch();
            $stmt->close();
            if ($numRows >= 1) return array('status'=>true,'id'=>$user_id);
        } else { return $error; }
    } else {
        //nothing was entered;
        return $error;
    }
}



function getSecurityQuestion($user_id)
{
    global $mysqli;
    $questions = array();
    $questions[0] = "What is your mother's maiden name?";
    $questions[1] = "What city were you born in?";
    $questions[2] = "What is your favorite colour?";
    $questions[3] = "What year did you graduate from High School?";
    $questions[4] = "What is your pet's name?";
    $questions[5] = "What is your favorite model of car?";
    if ($stmt = $mysqli->prepare("SELECT security_q FROM members WHERE id = ? LIMIT 1"))
    {
        $stmt->bind_param('i',$user_id);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($security_q);
        $stmt->fetch();
        $stmt->close();
        return $questions[$security_q];
    } else {
        return false;
    }
}
 
function checkSecAnswer($user_id, $security_a)
{
    global $mysqli;
    if ($stmt = $mysqli->prepare("SELECT username FROM members WHERE id = ? AND LOWER(security_q) = ? LIMIT 1"))
    {
        $security_a = strtolower($security_a);
        $stmt->bind_param('is',$user_id, $security_a);
        $stmt->execute();
        $stmt->store_result();
        $numRows = $stmt->num_rows();
        $stmt->close();
        if ($numRows >= 1) { return true; }
    } else {
        return false;
    }
}




function sendPasswordEmail($user_id)
{
    global $mysqli;
    if ($stmt = $mysqli->prepare("SELECT username, email, password FROM members WHERE id = ? LIMIT 1"))
    {
        $stmt->bind_param('i',$user_id);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($username, $email, $pword);
        $stmt->fetch();
        $stmt->close();
        $expFormat = mktime(date("H"), date("i"), date("s"), date("m")  , date("d")+3, date("Y"));
        $expDate = date("Y-m-d H:i:s",$expFormat);
        $security_key = md5($username . '_' . $email . rand(0,10000) .$expDate . PW_SALT);
        if ($stmt = $mysqli->prepare("INSERT INTO password_reset (user_id, security_key, expiry_date) VALUES (?,?,?)"))
        {
            $stmt->bind_param('iss',$user_id, $security_key, $expDate);
            $stmt->execute();
            $stmt->close();
            $passwordLink = "<a href=\"?a=recover&email=" . $security_key . "&u=" . urlencode(base64_encode($user_id)) . "\">http://www.oursite.com/forgotPass.php?a=recover&email=" . $security_key . "&u=" . urlencode(base64_encode($user_id)) . "</a>";
            $message = "Dear $username,\r\n";
            $message .= "Please visit the following link to reset your password:\r\n";
            $message .= "-----------------------\r\n";
            $message .= "$passwordLink\r\n";
            $message .= "-----------------------\r\n";
            $message .= "Please be sure to copy the entire link into your browser. The link will expire after 3 days for security reasons.\r\n\r\n";
            $message .= "If you did not request this forgotten password email, no action is needed, your password will not be reset as long as the link above is not visited. However, you may want to log into your account and change your security password and answer, as someone may have guessed it.\r\n\r\n";
            $message .= "Thanks,\r\n";
            $message .= "-- Our site team";
            $headers .= "From: Our Site <webmaster@oursite.com
			
<script type='text/javascript'>
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>> \n";
            $headers .= "To-Sender: \n";
            $headers .= "X-Mailer: PHP\n"; // mailer
            $headers .= "Reply-To: webmaster@oursite.com<script type='text/javascript'>
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>\n"; // Reply address
            $headers .= "Return-Path: webmaster@oursite.com<script type='text/javascript'>
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>\n"; //Return Path for errors
            $headers .= "Content-Type: text/html; charset=iso-8859-1"; //Enc-type
            $subject = "Your Lost password";
            @mail($email,$subject,$message,$headers);
            return str_replace("\r\n","<br/ >",$message);
        }
    }
}


function checkEmailKey($security_key,$user_id)
{
    global $mysqli;
    $curDate = date("Y-m-d H:i:s");
    if ($stmt = $mysqli->prepare("SELECT user_id FROM password_reset WHERE security_key = ? AND user_id = ? AND expiry_date >= ?"))
    {
        $stmt->bind_param('sis',$security_key, $user_id, $curDate);
        $stmt->execute();
        $stmt->execute();
        $stmt->store_result();
        $numRows = $stmt->num_rows();
        $stmt->bind_result($user_id);
        $stmt->fetch();
        $stmt->close();
        if ($numRows > 0 && $user_id != '')
        {
            return array('status'=>true,'user_id'=>$user_id);
        }
    }
    return false;
}
 
function updateUserPassword($user_id, $password, $security_key)
{
    global $mysqli;
    if (checkEmailsecurity_key($security_key,$user_id) === false) return false;
    if ($stmt = $mysqli->prepare("UPDATE members SET password = ? WHERE id = ?"))
    {
        $password = md5(trim($password) . PW_SALT);
        $stmt->bind_param('si',$password,$user_id);
        $stmt->execute();
        $stmt->close();
        $stmt = $mysqli->prepare("DELETE FROM password_reset WHERE security_key = ?");
        $stmt->bind_param('s',$security_key);
        $stmt->execute();
    }
}
 
function getUserName($user_id)
{
    global $mysqli;
    if ($stmt = $mysqli->prepare("SELECT username FROM members WHERE id = ?"))
    {
        $stmt->bind_param('i',$user_id);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($username);
        $stmt->fetch();
        $stmt->close();
    }
    return $username;
}

Password Form

<?php
include_once 'db_connect.php';
include_once 'functions.php';
include_once 'formatting.php';	
sec_session_start();
if (login_check($mysqli) == true) 
	{
    $logged = 'in';
	} 
	


$show = 'emailForm'; //which form step to show by default
if ($_SESSION['lockout'] == true && (mktime() > $_SESSION['lastTime'] + 900))
{
    $_SESSION['lockout'] = false;
    $_SESSION['badCount'] = 0;
}
if (isset($_POST['subStep']) && !isset($_GET['a']) && $_SESSION['lockout'] != true)
{
    switch($_POST['subStep'])
    {
        case 1:
            //we just submitted an email or username for verification
            $result = checkUNEmail($_POST['username'],$_POST['email']);
            if ($result['status'] == false )
            {
                $error = true;
                $show = 'userNotFound';
            } else {
                $error = false;
                $show = 'securityForm';
                $securityUser = $result['id'];
            }
        break;
        case 2:
            //we just submitted the security question for verification
            if ($_POST['user_id'] != "" && $_POST['security_a'] != "")
            {
                $result = checkSecAnswer($_POST['user_id'],$_POST['security_a']);
                if ($result == true)
                {
                    //answer was right
                    $error = false;
                    $show = 'successPage';
                    $passwordMessage = sendPasswordEmail($_POST['user_id']);
                    $_SESSION['badCount'] = 0;
                } else {
                    //answer was wrong
                    $error = true;
                    $show = 'securityForm';
                    $securityUser = $_POST['user_id'];
                    $_SESSION['badCount']++;
                }
            } else {
                $error = true;
                $show = 'securityForm';
            }
        break;
        case 3:
            //we are submitting a new password (only for encrypted)
            if ($_POST['user_id'] == '' || $_POST['security_key'] == '') header("location: ../login.php");
            if (strcmp($_POST['pw0'],$_POST['pw1']) != 0 || trim($_POST['pw0']) == '')
            {
                $error = true;
                $show = 'recoverForm';
            } else {
                $error = false;
                $show = 'recoverSuccess';
                updateUserPassword($_POST['user_id'],$_POST['pw0'],$_POST['security_key']);
            }
        break;
    }
}

elseif (isset($_GET['a']) && $_GET['a'] == 'recover' && $_GET['email'] != "") {
    $show = 'invalidKey';
    $result = checkEmailKey($_GET['email'],urldecode(base64_decode($_GET['u'])));
    if ($result == false)
    {
        $error = true;
        $show = 'invalidKey';
    } elseif ($result['status'] == true) {
        $error = false;
        $show = 'recoverForm';
        $securityUser = $result['user_id'];
    }
}
if ($_SESSION['badCount'] >= 3)
{
    $show = 'speedLimit';
    $_SESSION['lockout'] = true;
    $_SESSION['lastTime'] = '' ? mktime() : $_SESSION['lastTime'];
}
?>

	 


<!doctype html>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Password Recovery</title>
<link href="css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="header"></div>
<div id="page">

<?php switch($show) {
    case 'emailForm': ?>
    <h2>Password Recovery</h2>
    <p>You can use this form to recover your password if you have forgotten it. Because your password is securely encrypted in our database, it is impossible actually recover your password, but we will email you a link that will enable you to reset it securely. Enter either your username or your email address below to get started.</p>
    <form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
        <div class="fieldGroup"><label for="username">Username</label><div class="field"><input type="text" name="username" id="username" value="" maxlength="20"></div></div>
        <div class="fieldGroup"><label>- OR -</label></div>
        <div class="fieldGroup"><label for="email">Email</label><div class="field"><input type="text" name="email" id="email" value="" maxlength="255"></div></div>
        <input type="hidden" name="subStep" value="1" />
        <div class="fieldGroup"><input type="submit" value="Submit" style="margin-left: 150px;" /></div>
        <div class="clear"></div>
    </form>
    <?php break; case 'securityForm': ?>
    <h2>Password Recovery</h2>
    <p>Please answer the security question below:</p>
    <?php if ($error == true) { ?><span class="error">You must answer the security question correctly to receive your lost password.</span><?php } ?>
    <form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
        <div class="fieldGroup">
			<label>Question</label>
				<div class="field"><?= getSecurityQuestion($securityUser); ?></div>
		</div>
			
        <div class="fieldGroup">
			<label for="security_a">Answer</label>
				<div class="field"><input type="text" name="security_a" id="security_a" value="" maxlength="255"></div>
		</div>
        <input type="hidden" name="subStep" value="2" />
        <input type="hidden" name="user_id" value="<?= $securityUser; ?>" />
        <div class="fieldGroup"><input type="submit" value="Submit" style="margin-left: 150px;" /></div>
        <div class="clear"></div>
    </form>
 
     
     <?php break; case 'userNotFound': ?><br>    
	 <h2>Password Recovery</h2><br>    
	 <p>The username or email you entered was not found in our database.<br /><br />
	 <a href="?">Click here</a> to try again.</p><br>    
	 <?php break; case 'successPage': ?><br>    
	 <h2>Password Recovery</h2><br>    
	 <p>An email has been sent to you with instructions on how to reset your password. 
	 <strong>(Mail will not send unless you have an smtp server running locally.)</strong>
	 <br /><br /><a href="../login.php">Return</a> to the login page. </p><br>    
	 <p>This is the message that would appear in the email:</p><br>    
	 <div class="message"><?= $passwordMessage;?></div><br>    
	
	
	 <?php break;
case 'recoverForm': ?>
    <h2>Password Recovery</h2>
    <p>Welcome back, <?= getUserName($securityUser=='' ? $_POST['user_id'] : $securityUser); ?>.</p>
    <p>In the fields below, enter your new password.</p>
    <?php if ($error == true) { ?><span class="error">The new passwords must match and must not be empty.</span><?php } ?>
    <form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
        <div class="fieldGroup"><label for="pw0">New Password</label><div class="field"><input type="password" class="input" name="pw0" id="pw0" value="" maxlength="20"></div></div>
        <div class="fieldGroup"><label for="pw1">Confirm Password</label><div class="field"><input type="password" class="input" name="pw1" id="pw1" value="" maxlength="20"></div></div>
        <input type="hidden" name="subStep" value="3" />
        <input type="hidden" name="user_id" value="<?= $securityUser=='' ? $_POST['user_id'] : $securityUser; ?>" />
        <input type="hidden" name="security_key" value="<?= $_GET['email']=='' ? $_POST['security_key'] : $_GET['email']; ?>" />
        <div class="fieldGroup"><input type="submit" value="Submit" style="margin-left: 150px;" /></div>
        <div class="clear"></div>
    </form>
    <?php break; case 'invalidsecurity_key': ?>
    <h2>Invalid security_key</h2>
    <p>The security_key that you entered was invalid. Either you did not copy the entire security_key from the email, you are trying to use the security_key after it has expired (3 days after request), or you have already used the security_key in which case it is deactivated.<br /><br /><a href="login.php">Return</a> to the login page. </p>
    <?php break; case 'recoverSuccess': ?>
    <h2>Password Reset</h2>
    <p>Congratulations! your password has been reset successfully.</p><br /><br /><a href="login.php">Return</a> to the login page. </p>
    <?php break; case 'speedLimit': ?>
    <h2>Warning</h2>
    <p>You have answered the security question wrong too many times. You will be locked out for 15 minutes, after which you can try again.</p><br /><br /><a href="login.php">Return</a> to the login page. </p>
    <?php break; }
    ob_flush();
    $mysqli->close();
?>


<!--PAGE CONTENT-->
</div>
</body>
</html>



Edited by SalientAnimal
Link to comment
Share on other sites

You getting the notices because you are using keys to $_SESSION which do not exist.

 

To fix the notices use isset before the use of the variable, example for line 14

if (isset($_SESSION['lockout']) && $_SESSION['lockout'] == true && (mktime() > $_SESSION['lastTime'] + 900))

 

 

Notice: Undefined index: What is your pet's name? in C:\autopage_auxilium\htdocs\includes\functions.php on line 389

If you have stored the security question in the database, then line 389 should be

return $security_q;
Edited by Ch0cu3r
Link to comment
Share on other sites

I managed to get the form working. There are just a few problems that still exist:

 

  1. The source code encodes the password / new password to MD5, however I am using SHA512, how do I change this to accommodate the different encryption?
  2. I am still getting a few errors on my form that I am not sure how to fix:
  • Notice: Undefined index: lockout in C:\autopage_auxilium\htdocs\includes\resetpwd.php on line 19
    LINE 19
    if (isset($_POST['subStep']) && !isset($_GET['a']) &&  $_SESSION['lockout'] != true)

  • Notice: Use of undefined constant PW_SALT - assumed 'PW_SALT' in C:\autopage_auxilium\htdocs\includes\functions.php on line 429
    LINE 429
    $security_key = md5($username . '_' . $email . rand(0,10000) .$expDate . PW_SALT);

  • Notice: Undefined variable: headers in C:\autopage_auxilium\htdocs\includes\functions.php on line 451
    LINE 451
    </script>> \n";
                $headers .= "To-Sender: \n";
                $headers .= "X-Mailer: PHP\n"; // mailer
                $headers .= "Reply-To: webmaster@oursite.com<script type='text/javascript'>

    Could this be because I am not sending an e-mail? But rather displaying the message to the user provided they answer the question correctly.

Link to comment
Share on other sites

 

 

  1. The source code encodes the password / new password to MD5, however I am using SHA512, how do I change this to accommodate the different encryption?

Find  md5(   replace with   hash('sha512',

 

 

 

  1. I am still getting a few errors on my form that I am not sure how to fix:
  • Notice: Undefined index: lockout in C:\autopage_auxilium\htdocs\includes\resetpwd.php on line 19

    LINE 19

    if (isset($_POST['subStep']) && !isset($_GET['a']) &&  $_SESSION['lockout'] != true)

lockout has not be defined in your session. Add

if(!isset($_SESSION['lockout']))
   $_SESSION['lockout'] = false;

Before

if ($_SESSION['lockout'] == true && (mktime() > $_SESSION['lastTime'] + 900))

 

 

  • Notice: Use of undefined constant PW_SALT - assumed 'PW_SALT' in C:\autopage_auxilium\htdocs\includes\functions.php on line 429

    LINE 429

    $security_key = md5($username . '_' . $email . rand(0,10000) .$expDate . PW_SALT);

You are using a constant which has not been defined. Either define it or remove it.

 

 

 

 

 

Notice: Undefined variable: headers in C:\autopage_auxilium\htdocs\includes\functions.php on line 451

LINE 451

</script>> \n";

            $headers .= "To-Sender: \n";

            $headers .= "X-Mailer: PHP\n"; // mailer

            $headers .= "Reply-To: webmaster@oursite.com<script type='text/javascript'>

 

Why are you adding html/Javascript to an email header? headers should be plain text. HTML/Javascript should be in the email body

Edited by Ch0cu3r
Link to comment
Share on other sites

I wanted to ask you, is it necessary to use the PW_SALT in my password reset form?

 

Also one of the other errors I picked up is should I enter my Security Answer incorrectly the first time, it will not accept even the correct answer on a second / third attempt. The error I get when this happens is again an undefined variable error. What I don't understand is that I define this earlier in the page if I'm not mistaken?

Notice: Undefined variable: securityUser in \htdocs\includes\resetpwd.php on line 181

Here is line 181 and a few lines prior to it (181 is the last line)

<div class="fieldGroup">
<?php if ($error == true) { ?><span class="error">You have answered the security question incorrectly, please try again. If you are unable to remember the answer to your question, please contact your Team Manager.</span><?php } ?></div>

<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">

			<div class="fieldGroup"><label>Security Question :
			<span class="small">Validation Question</span>
			</label>
			<div class="field">   <?= getSecurityQuestion($securityUser);?></div></div>

Thanks.

Link to comment
Share on other sites

Ok, after spending an entire day on this, I eventually got the form to generate. The last issue I have is the password that is being updated into the database table now does not work.

 

This is the last part I need to get working to get my password reset form working.

 

Here is the code that is currently working for me:

 

Password Reset Functions:

//PSSWORD RESET FUNCTIONS




//define(PW_SALT,'(+3%_');
 
function checkUNEmail($username,$email)
{
    global $mysqli;
    $error = array('status'=>false,'user_id'=>0);
    if (isset($email) && trim($email) != '') {
        //email was entered
        if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE email = ? LIMIT 1"))
        {
            $stmt->bind_param('s',trim($email));
            $stmt->execute();
            $stmt->store_result();
            $numRows = $stmt->num_rows();
            $stmt->bind_result($user_id);
            $stmt->fetch();
            $stmt->close();
            if ($numRows >= 1) return array('status'=>true,'id'=>$user_id);
        } else { return $error; }
    } elseif (isset($username) && trim($username) != '') {
        //username was entered
        if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE username = ? LIMIT 1"))
        {
            $stmt->bind_param('s',trim($username));
            $stmt->execute();
            $stmt->store_result();
            $numRows = $stmt->num_rows();
            $stmt->bind_result($user_id);
            $stmt->fetch();
            $stmt->close();
            if ($numRows >= 1) return array('status'=>true,'id'=>$user_id);
        } else { return $error; }
    } else {
        //nothing was entered;
        return $error;
    }
}



function getSecurityQuestion($user_id)
{
    global $mysqli;
    $questions = array();
    $questions[0] = "What is your mother's maiden name?";
    $questions[1] = "What city were you born in?";
    $questions[2] = "What is your favorite colour?";
    $questions[3] = "What year did you graduate from High School?";
    $questions[4] = "What is your pet's name?";
    $questions[5] = "What is your favorite model of car?";
    if ($stmt = $mysqli->prepare("SELECT security_q FROM members WHERE id = ? LIMIT 1"))
    {
        $stmt->bind_param('i',$user_id);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($security_q);
        $stmt->fetch();
        $stmt->close();
		return $security_q;
    } else {
        return false;
    }
}
 
function checkSecAnswer($user_id, $security_a)
{
    global $mysqli;
    if ($stmt = $mysqli->prepare("SELECT username FROM members WHERE id = ? AND LOWER(security_a) = ? LIMIT 1"))
    {
        $security_a = strtolower($security_a);
        $stmt->bind_param('is',$user_id, $security_a);
        $stmt->execute();
        $stmt->store_result();
        $numRows = $stmt->num_rows();
        $stmt->close();
        if ($numRows >= 1) { return true; }
    } else {
        return false;
    }
}




function sendPasswordEmail($user_id)
{
    global $mysqli;
    if ($stmt = $mysqli->prepare("SELECT username, email, password FROM members WHERE id = ? LIMIT 1"))
    {
        $stmt->bind_param('i',$user_id);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($username, $email, $pword);
        $stmt->fetch();
        $stmt->close();
        $expFormat = mktime(date("H"), date("i"), date("s"), date("m")  , date("d")+3, date("Y"));
        $expDate = date("Y-m-d H:i:s",$expFormat);
        $security_key =  hash('sha512',$username . '_' . $email . rand(0,10000) .$expDate . PW_SALT);
        if ($stmt = $mysqli->prepare("INSERT INTO password_reset (user_id, security_key, expiry_date) VALUES (?,?,?)"))
        {
            $stmt->bind_param('iss',$user_id, $security_key, $expDate);
            $stmt->execute();
            $stmt->close();
            $passwordLink = "<a href=\"?a=recover&email=" . $security_key . "&u=" . urlencode(base64_encode($user_id)) . "\">http://www.oursite.com/forgotPass.php?a=recover&email=" . $security_key . "&u=" . urlencode(base64_encode($user_id)) . "</a>";
            $message = "Dear $username,\r\n";
            $message .= "Please visit the following link to reset your password:\r\n";
            $message .= "-----------------------\r\n";
            $message .= "$passwordLink\r\n";
            $message .= "-----------------------\r\n";
            $message .= "Please be sure to copy the entire link into your browser. The link will expire after 3 days for security reasons.\r\n\r\n";
            $message .= "If you did not request this forgotten password email, no action is needed, your password will not be reset as long as the link above is not visited. However, you may want to log into your account and change your security password and answer, as someone may have guessed it.\r\n\r\n";
            $message .= "Thanks,\r\n";
            $message .= "-- Our site team";
            $headers .= "From: Our Site <webmaster@oursite.com
			
<script type='text/javascript'>
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>> \n";
            $headers .= "To-Sender: \n";
            $headers .= "X-Mailer: PHP\n"; // mailer
            $headers .= "Reply-To: webmaster@oursite.com<script type='text/javascript'>
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>\n"; // Reply address
            $headers .= "Return-Path: webmaster@oursite.com<script type='text/javascript'>
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>\n"; //Return Path for errors
            $headers .= "Content-Type: text/html; charset=iso-8859-1"; //Enc-type
            $subject = "Your Lost password";
            @mail($email,$subject,$message,$headers);
            return str_replace("\r\n","<br/ >",$message);
        }
    }
}


function checkEmailKey($security_key,$user_id)
{
    global $mysqli;
    $curDate = date("Y-m-d H:i:s");
    if ($stmt = $mysqli->prepare("SELECT user_id FROM password_reset WHERE security_key = ? AND user_id = ? AND expiry_date >= ?"))
    {
        $stmt->bind_param('sis',$security_key, $user_id, $curDate);
        $stmt->execute();
        $stmt->execute();
        $stmt->store_result();
        $numRows = $stmt->num_rows();
        $stmt->bind_result($user_id);
        $stmt->fetch();
        $stmt->close();
        if ($numRows > 0 && $user_id != '')
        {
            return array('status'=>true,'user_id'=>$user_id);
        }
    }
    return false;
}
 
function updateUserPassword($user_id, $password, $security_key)
{
    global $mysqli;
    if (checkEmailkey($security_key,$user_id) === false) return false;
    if ($stmt = $mysqli->prepare("UPDATE members SET password = ? WHERE id = ?"))
    {
        $password = hash('sha512',trim($password));
        $stmt->bind_param('si',$password,$user_id);
        $stmt->execute();
        $stmt->close();
        $stmt = $mysqli->prepare("DELETE FROM password_reset WHERE security_key = ?");
        $stmt->bind_param('s',$security_key);
        $stmt->execute();
    }
}
 
function getUserName($user_id)
{
    global $mysqli;
    if ($stmt = $mysqli->prepare("SELECT username FROM members WHERE id = ?"))
    {
        $stmt->bind_param('i',$user_id);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($username);
        $stmt->fetch();
        $stmt->close();
    }
    return $username;
}

Password Reset Form:

<?php
include_once 'db_connect.php';
include_once 'functions.php';
include_once 'formatting_includes.php';	
sec_session_start();
if (login_check($mysqli) == true) 
	{
    $logged = 'in';
	} 
	


$show = 'emailForm'; //which form step to show by default
if(!isset($_SESSION['lastTime']))
   $_SESSION['lastTime'] = false;
if (isset($_SESSION['lockout']) && $_SESSION['lockout'] == true && (mktime() > $_SESSION['lastTime'] + 900))
{
    $_SESSION['lockout'] = false;
    $_SESSION['badCount'] = 0;
}
if(!isset($_SESSION['lockout']))
   $_SESSION['lockout'] = false;
if (isset($_POST['subStep']) && !isset($_GET['a']) &&  $_SESSION['lockout'] != true)
{
    switch($_POST['subStep'])
    {
        case 1:
            //we just submitted an email or username for verification
            $result = checkUNEmail($_POST['username'],$_POST['email']);
            if ($result['status'] == false )
            {
                $error = true;
                $show = 'userNotFound';
            } else {
                $error = false;
                $show = 'securityForm';
                $securityUser = $result['id'];
            }
        break;
        case 2:
            //we just submitted the security question for verification
            if ($_POST['user_id'] != "" && $_POST['security_a'] != "")
            {
                $result = checkSecAnswer($_POST['user_id'],$_POST['security_a']);
                if ($result == true)
                {
                    //answer was right
                    $error = false;
                    $show = 'successPage';
                    $passwordMessage = sendPasswordEmail($_POST['user_id']);
                    $_SESSION['badCount'] = 0;
                } else {
                    //answer was wrong
                    $error = true;
                    $show = 'securityForm';
                    $securityUser = $_POST['user_id'];
                    $_SESSION['badCount']++;
                }
            } else {
                $error = true;
                $show = 'securityForm';
            }
        break;
        case 3:
            //we are submitting a new password (only for encrypted)
            if ($_POST['user_id'] == '' || $_POST['security_key'] == '') header("location: ../index.php");
            if (strcmp($_POST['pw0'],$_POST['pw1']) != 0 || trim($_POST['pw0']) == '')
            {
                $error = true;
                $show = 'recoverForm';
            } else {
                $error = false;
                $show = 'recoverSuccess';
                updateUserPassword($_POST['user_id'],$_POST['pw0'],$_POST['security_key']);
            }
        break;
    }
}

elseif (isset($_GET['a']) && $_GET['a'] == 'recover' && $_GET['email'] != "") {
    $show = 'invalidKey';
    $result = checkEmailKey($_GET['email'],urldecode(base64_decode($_GET['u'])));
    if ($result == false)
    {
        $error = true;
        $show = 'invalidKey';
    } elseif ($result['status'] == true) {
        $error = false;
        $show = 'recoverForm';
        $securityUser = $result['user_id'];
    }
}
if (isset($_SESSION['badCount']) && $_SESSION['badCount'] >= 3)
{
    $show = 'speedLimit';
    $_SESSION['lockout'] = true;
    $_SESSION['lastTime'] = '' ? mktime() : $_SESSION['lastTime'];
}
?>

	 


<!doctype html>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Password Recovery</title>
<link href="css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>

<?php
// INCLUDING THE TOP LOGIN / LOGOUT PANEL
include 'panel.php';
// INCLUDING THE NAVIGATION MENU
?>

<div id="container">
<div id="content" style="margin-top:-45px;">
		<img src="../images/logo.png" alt="Altech Autopage"></img>


<!-- CREATE THE FORM TO REQUEST THE USER TO SUBMIT DETAILS OF ACCOUNT -->

<?php switch($show) {
    case 'emailForm': ?>
	<div id="stylized" class="form">

	<h2>Password Recovery</h2>

		<p>Upon registration your password was securly encrypted in our database and it is impossible to actually recover your password. 																		
		However by filling in the for below, and answering your security question we can allow you to securely reset it. </p>

		<p>Please enter either your registered username or registered e-mail address below to get stared.</p>

		<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">


		
			<div class="fieldGroup"><label>Username :
			<span class="small">Username created when registering</span>
			</label>
			<div class="field"><input type="text" name="username" id="username" value="">
			</div>
			</div>
			
			<br><br>
			
			<p align='center' style="color: #ED1C24; font: bold 16px Arial, sans-serif;">-- OR -- </p>
			
			<br>
				
			<div class="fieldGroup"><label>E-Mail Address :
			<span class="small">E-Mail Address used when registering</span>
			</label>
			<div class="field"><input type="text" name="email" id="email" value="">
			</div>
			</div>
				
        	<input type="hidden" name="subStep" value="1" />
			<div class="fieldGroup"><input type="button" value="Find User" class="bt_login" onClick="form.submit()"/></div>
			<div class="clear"></div>
		</form>
	</div>


<?php break; case 'securityForm': ?>


	<div id="stylized" class="form">
	
	<h2>Password Recovery</h2>

		<p>Here comes the tricky part where we test your knowledge...</p>

		<p>Please answer the security question below so that we can verify that the correct person is trying to access your account.</p>

		<div class="fieldGroup">
		<?php if ($error == true) { ?>
		<span class="error">You have answered the security question incorrectly, please try again. If you are unable to remember the answer to 		your question, please contact your Team Manager.</span>
		<?php } ?>
		</div>

		<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">

			<div class="fieldGroup"><label>Security Question :
			<span class="small">Validation Question</span>
			</label>
			<div class="field">   <?= getSecurityQuestion($securityUser);?></div></div>

			<br>
			
			
			<div class="fieldGroup"><label>Security Answer :
			<span class="small">Validation Answer</span>
			</label>
			<div class="field"><input type="text" name="security_a" id="security_a" value=""></div></div>

        	<input type="hidden" name="subStep" value="2" />
        	<input type="hidden" name="user_id" value="<?= $securityUser; ?>" />
			<div class="fieldGroup">
			<input type="button" value="Recover" class="bt_login" onClick="form.submit()" style="margin-left: 150px;"/>										
			</div>
        	<div class="clear"></div>
    	</form>
	</div>
 
     
     	<?php break; case 'userNotFound': ?><br>  

	<div id="stylized" class="form">
	
	 	<h2>Password Recovery</h2><br>    
	 	<p>It appears that the username / password you are searching for is not valid,
	 	please <a href="?">Click here</a> to go back and try again.</p><br>    
		<div class="fieldGroup"></div> 
	</div>
		
		<?php break; case 'successPage': ?><br>   
	 	<h2>Password Recovery</h2><br>    

	 	<div class="message"><?= $passwordMessage;?></div><br>    
	


	
	 	<?php break; case 'recoverForm': ?>
	<div id="stylized" class="form">
	
    	<h2>Password Recovery</h2>
    	<p>Welcome back, <?= getUserName($securityUser=='' ? $_POST['user_id'] : $securityUser); ?>.</p>
    	<p>In the fields below, enter your new password.</p>
    	
		<?php if ($error == true) { ?><span class="error">The new passwords must match and must not be empty.</span><?php } ?>
    	<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
			<div class="fieldGroup"><label for="pw0">New Password</label><div class="field">
			<input type="password" class="input" name="pw0" id="pw0" value="" maxlength="20"></div></div>
			<div class="fieldGroup"><label for="pw1">Confirm Password</label><div class="field">
			<input type="password" class="input" name="pw1" id="pw1" value="" maxlength="20"></div></div>
			<input type="hidden" name="subStep" value="3" />
			<input type="hidden" name="user_id" value="<?= $securityUser=='' ? $_POST['user_id'] : $securityUser; ?>" />
			<input type="hidden" name="security_key" value="<?= $_GET['email']=='' ? $_POST['security_key'] : $_GET['email']; ?>" />
			<div class="fieldGroup"><input type="submit" value="Submit" style="margin-left: 150px;" /></div>
			<div class="clear"></div>
		</form>
	</div>
	
    <?php break; case 'invalidsecurity_key': ?>
    <h2>Invalid security_key</h2>
    <p>The security_key that you entered was invalid. Either you did not copy the entire security_key from the email, you are trying to use the security_key after it has expired (3 days after request), or you have already used the security_key in which case it is deactivated.<br /><br /><a href="../index.php">Return</a> to the login page. </p>
    <?php break; case 'recoverSuccess': ?>
    <h2>Password Reset</h2>
    <p>Congratulations! your password has been reset successfully.</p><br /><br /><a href="../index.php">Return</a> to the login page. </p>
    <?php break; case 'speedLimit': ?>
    <h2>Warning</h2>
    <p>You have answered the security question wrong too many times. You will be locked out for 15 minutes, after which you can try again.</p><br /><br /><a href="../index.php">Return</a> to the login page. </p>
    <?php break; }
    ob_flush();
    $mysqli->close();
?>
<br><br><br>
</div>
</div>
</div>

<div id="container">
<div id="footer" style="margin-top:10px;">
<footer style="background:#E5E5E5; height:20px">
  <p>Copyright © Altech Autopage 2014 | <a href="mailto:lclaassen@autopage.altech.co.za">Contact Us</a>.</p>
  <img src="../images/altron-footer-logo.png" alt="Altron Footer Logo" align="left"></img>
  <img src="../images/altech_bbbee.png" alt="Altech Level 2 BBEE" align="left"></img>
</footer>
</div>	
</div>

<!--PAGE CONTENT-->
</div>
</body>
</html>

I am not getting any error message. I get my last message that says:

 

Congratulations! your password has been reset successfully.


Return to the login page.

 

 

 

 

 

 

 

 

 

Please I need some help again :-).... Thanks.

Edited by SalientAnimal
Link to comment
Share on other sites

The form is updating the database with something, but I am not sure exactly with what, and why it is not working when trying to login with the new details.

 

What I have done, is I submitted the password to the table un-hashed to check that the correct password is being added, and this is correct. The only other thing that I feel my be cause any problems is the SALT which I have excluded from the script. I would really appreciate some help here.

 

Here are all the functions that I have, I assume it could be something to do with the login functions and the SALT conflicting, but I'm not entirely sure.

<?php

// includes/functions.php -->

//
//ERROR CHECKING FUNCTIONS - ADD TO PAGES TO CHECK FOR POSSIBLE ERRORS
//	var_dump(login_check($mysqli));
//	var_dump($_SESSION); exit; 
//	var_dump($_POST);exit; 

include_once 'psl-config.php';

function sec_session_start() {
    $session_name = 'sec_session_id';   // Set a custom session name
    $secure = SECURE;
    // This stops JavaScript being able to access the session id.
    $httponly = true;
    // Forces sessions to only use cookies.
    if (ini_set('session.use_only_cookies', 1) === FALSE) {
        header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
        exit();
    }
    // Gets current cookies params.
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params($cookieParams["lifetime"],
        $cookieParams["path"], 
        $cookieParams["domain"], 
        $secure,
        $httponly);
    // Sets the session name to the one set above.
    session_name($session_name);
    session_start();            // Start the PHP session 
    session_regenerate_id();    // regenerated the session, delete the old one. 
}



function login($email, $password, $mysqli) {
    // Using prepared statements means that SQL injection is not possible. 
    if ($stmt = $mysqli->prepare("SELECT id, username, password, email, level, salt 
        FROM members
       WHERE username = ?
        LIMIT 1")) {
        $stmt->bind_param('s', $email);  // Bind "$email" to parameter.
        $stmt->execute();    // Execute the prepared query.
        $stmt->store_result();

        // get variables from result.
        $stmt->bind_result($user_id, $username, $db_password, $email, $level, $salt);
        $stmt->fetch();

        // hash the password with the unique salt.
        $password = hash('sha512', $password . $salt);
        if ($stmt->num_rows == 1) {
            // If the user exists we check if the account is locked
            // from too many login attempts 
 
            if (checkbrute($user_id, $mysqli) == true) {
                // Account is locked 
                // Send an email to user saying their account is locked
                return false;
            } else {
                // Check if the password in the database matches
                // the password the user submitted.
                if ($db_password == $password) {
                    // Password is correct!
                    // Get the user-agent string of the user.
                    $user_browser = $_SERVER['HTTP_USER_AGENT'];
                    // XSS protection as we might print this value
                    $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                    $_SESSION['user_id'] = $user_id;
                    // XSS protection as we might print this value
                    $username = preg_replace("/[^a-zA-Z0-9_\-]+/", 
                                                                "", 
                                                                $username);
                    $_SESSION['username'] = $username;
                    $_SESSION['login_string'] = hash('sha512',$password . $user_browser);
					$_SESSION['email'] = $email;
					$_SESSION['level'] = $level;
					$_SESSION['session_status'] = $session_status;
                    $mysqli->query("SELECT * FROM login_success WHERE user_id = '$user_id'");
					if			  (mysql_num_rows($mysqli) > 0)
						{
						$mysqli->query("UPDATE login_success SET time = NOW() WHERE user_id = '$user_id'");
						}
					else
						{
						$mysqli->query("INSERT INTO login_success(user_id, time) VALUES ('$user_id', now()");
						}
					//UPDATE login_success SET time = now() where user_id = '$user_id'");							  
                    // Login successful.
                    return true;
                } else {
                    // Password is not correct
                    // We record this attempt in the database
                    //$now = time();
                    $mysqli->query("INSERT INTO login_attempts(user_id, time)
                                    VALUES ('$user_id', now())");
                    return false;
                }
            }
        } else {
            // No user exists.
            return false;
        }
    }
}



function checkbrute($user_id, $mysqli) {
    // Get timestamp of current time 
    $now = time();

    // All login attempts are counted from the past 2 hours. 
    $valid_attempts = $now - (2 * 60 * 60);

    if ($stmt = $mysqli->prepare("SELECT time 
                             FROM login_attempts 
                             WHERE user_id = ? 
                            AND time > '$valid_attempts'")) {
        $stmt->bind_param('i', $user_id);

        // Execute the prepared query. 
        $stmt->execute();
        $stmt->store_result();

        // If there have been more than 5 failed logins 
        if ($stmt->num_rows > 5) {
            return true;
        } else {
            return false;
        }
    }
}



function login_check($mysqli) 
	{
    // Check if all session variables are set 
    if (isset($_SESSION['user_id'], 
			  $_SESSION['username'], 
			  $_SESSION['login_string'],
			  $_SESSION['email'],
			  $_SESSION['level']
			  //$_SESSION['session_status']
			  )) 
	{

    $user_id = $_SESSION['user_id'];
    $login_string = $_SESSION['login_string'];
    $username = $_SESSION['username'];
	$email = $_SESSION['email'];
	$level = $_SESSION['level'];
	//$status = $_SESSON['session_status'];
		

        // Get the user-agent string of the user.
        $user_browser = $_SERVER['HTTP_USER_AGENT'];

        if ($stmt = $mysqli->prepare("SELECT password 
                                      FROM members 
                                      WHERE id = ? LIMIT 1")) {
            // Bind "$user_id" to parameter. 
            $stmt->bind_param('i', $user_id);
            $stmt->execute();   // Execute the prepared query.
            $stmt->store_result();

            if ($stmt->num_rows == 1) {
                // If the user exists get variables from result.
                $stmt->bind_result($password);
                $stmt->fetch();
                $login_check = hash('sha512', $password . $user_browser);

                if ($login_check == $login_string) {
                    // Logged In!!!! 
					//echo 'logged in';
                    return true;
                } else {
                    // Not logged in 
					echo 1;
                    return false;
                }
            } else {
                // Not logged in
					echo 2;
                return false;
            }
        } else {
            // Not logged in 
			echo 3;
            return false;
        }
    } else {
        // Not logged in 
		//echo 4;
        return false;
    }
}



function esc_url($url) {

    if ('' == $url) {
        return $url;
    }

    $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);

    $strip = array('%0d', '%0a', '%0D', '%0A');
    $url = (string) $url;

    $count = 1;
    while ($count) {
        $url = str_replace($strip, '', $url, $count);
   }

    $url = str_replace(';//', '://', $url);

    $url = htmlentities($url);

    $url = str_replace('&', '&', $url);
    $url = str_replace("'", ''', $url);

    if ($url[0] !== '/') {
        // We're only interested in relative links from $_SERVER['PHP_SELF']
        return '';
    } else {
        return $url;
    }
}





function crypto_rand_secure($min, $max) {
        $range = $max - $min;
        if ($range < 0) return $min; // not so random...
        $log = log($range, 2);
        $bytes = (int) ($log /  + 1; // length in bytes
        $bits = (int) $log + 1; // length in bits
        $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
        do {
            $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
            $rnd = $rnd & $filter; // discard irrelevant bits
        } while ($rnd >= $range);
        return $min + $rnd;
}

function getToken($length=32){
    $token = "";
    $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
    $codeAlphabet.= "0123456789";
    for($i=0;$i<$length;$i++){
        $token .= $codeAlphabet[crypto_rand_secure(0,strlen($codeAlphabet))];
    }
    return $token;
}






/* RESTRICTED ACCESS LEVEL MANAGEMENT */


	
	function checkLoginLevel() {
        $allowed = array(
            '0' => array('register.addinfo.php','process/*','includes/*','index.php','index.html'), /* NEW REGISTRATION ACCESS LEVELS */
            '1' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','walkin_form.php','walkin_delete.php'),		/* ACCESS LEVELS FROM RECEPTION */
            '2' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','first-page.php'),
            '3' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','retail_view.php','retail_viewer.php','walkin_form.php','retail_form.php'),
			'4' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','premier_form.php', 'second-page.php', 'third-page.php'), /* SUPERVISOR ACCESS LEVELS */
            '5' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','premier_form.php', 'second-page.php', 'third-page.php'), /* SUPERVISOR ACCESS LEVELS */
			'99' => true, /* ADMINISTRATION ACCESS LEVELS */
        );

    if(!isset($allowed[$_SESSION['level']])) {
        echo 'Your access level has not been set. Please return to the Login / Registration Page.';
        exit;
    }
	
	if($_SESSION['level'] == 0) {
	header('Location:register.addinfo.php');
	exit;
	}

    if(is_array($allowed[$_SESSION['level']])) {

        $file = $_SERVER["PHP_SELF"];
        $filearray = explode('/', $file);
        $filename = array_pop($filearray);
        $directory = array_pop($filearray);

        foreach($allowed[$_SESSION['level']] as $access) {
            if(strpos($access,'*')) {
                if($access == $directory . '/*') {
                    return true;
                }
            } elseif($access == $filename) {
                return true;
            }
        }
    }

    if(is_bool($allowed[$_SESSION['level']])) {
        return true;
    }

    echo 'You are not authorised to view this page. Please contact your manager to have your access level adjusted';
    exit;
}





//PSSWORD RESET FUNCTIONS




//define(PW_SALT,'(+3%_');
 
function checkUNEmail($username,$email)
{
    global $mysqli;
    $error = array('status'=>false,'user_id'=>0);
    if (isset($email) && trim($email) != '') {
        //email was entered
        if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE email = ? LIMIT 1"))
        {
            $stmt->bind_param('s',trim($email));
            $stmt->execute();
            $stmt->store_result();
            $numRows = $stmt->num_rows();
            $stmt->bind_result($user_id);
            $stmt->fetch();
            $stmt->close();
            if ($numRows >= 1) return array('status'=>true,'id'=>$user_id);
        } else { return $error; }
    } elseif (isset($username) && trim($username) != '') {
        //username was entered
        if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE username = ? LIMIT 1"))
        {
            $stmt->bind_param('s',trim($username));
            $stmt->execute();
            $stmt->store_result();
            $numRows = $stmt->num_rows();
            $stmt->bind_result($user_id);
            $stmt->fetch();
            $stmt->close();
            if ($numRows >= 1) return array('status'=>true,'id'=>$user_id);
        } else { return $error; }
    } else {
        //nothing was entered;
        return $error;
    }
}



function getSecurityQuestion($user_id)
{
    global $mysqli;
    $questions = array();
    $questions[0] = "What is your mother's maiden name?";
    $questions[1] = "What city were you born in?";
    $questions[2] = "What is your favorite colour?";
    $questions[3] = "What year did you graduate from High School?";
    $questions[4] = "What is your pet's name?";
    $questions[5] = "What is your favorite model of car?";
    if ($stmt = $mysqli->prepare("SELECT security_q FROM members WHERE id = ? LIMIT 1"))
    {
        $stmt->bind_param('i',$user_id);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($security_q);
        $stmt->fetch();
        $stmt->close();
		return $security_q;
    } else {
        return false;
    }
}
 
function checkSecAnswer($user_id, $security_a)
{
    global $mysqli;
    if ($stmt = $mysqli->prepare("SELECT username FROM members WHERE id = ? AND LOWER(security_a) = ? LIMIT 1"))
    {
        $security_a = strtolower($security_a);
        $stmt->bind_param('is',$user_id, $security_a);
        $stmt->execute();
        $stmt->store_result();
        $numRows = $stmt->num_rows();
        $stmt->close();
        if ($numRows >= 1) { return true; }
    } else {
        return false;
    }
}




function sendPasswordEmail($user_id)
{
    global $mysqli;
    if ($stmt = $mysqli->prepare("SELECT username, email, password FROM members WHERE id = ? LIMIT 1"))
    {
        $stmt->bind_param('i',$user_id);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($username, $email, $pword);
        $stmt->fetch();
        $stmt->close();
        $expFormat = mktime(date("H"), date("i"), date("s"), date("m")  , date("d")+3, date("Y"));
        $expDate = date("Y-m-d H:i:s",$expFormat);
        $security_key =  hash('sha512',$username . '_' . $email . rand(0,10000) .$expDate . $salt);
        if ($stmt = $mysqli->prepare("INSERT INTO password_reset (user_id, security_key, expiry_date) VALUES (?,?,?)"))
        {
            $stmt->bind_param('iss',$user_id, $security_key, $expDate);
            $stmt->execute();
            $stmt->close();
            $passwordLink = "<a href=\"?a=recover&email=" . $security_key . "&u=" . urlencode(base64_encode($user_id)) . "\">http://www.oursite.com/forgotPass.php?a=recover&email=" . $security_key . "&u=" . urlencode(base64_encode($user_id)) . "</a>";
            $message = "Dear $username,\r\n";
            $message .= "Please visit the following link to reset your password:\r\n";
            $message .= "-----------------------\r\n";
            $message .= "$passwordLink\r\n";
            $message .= "-----------------------\r\n";
            $message .= "Please be sure to copy the entire link into your browser. The link will expire after 3 days for security reasons.\r\n\r\n";
            $message .= "If you did not request this forgotten password email, no action is needed, your password will not be reset as long as the link above is not visited. However, you may want to log into your account and change your security password and answer, as someone may have guessed it.\r\n\r\n";
            $message .= "Thanks,\r\n";
            $message .= "-- Our site team";
            $headers .= "From: Our Site <webmaster@oursite.com
			
<script type='text/javascript'>
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>> \n";
            $headers .= "To-Sender: \n";
            $headers .= "X-Mailer: PHP\n"; // mailer
            $headers .= "Reply-To: webmaster@oursite.com<script type='text/javascript'>
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>\n"; // Reply address
            $headers .= "Return-Path: webmaster@oursite.com<script type='text/javascript'>
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>\n"; //Return Path for errors
            $headers .= "Content-Type: text/html; charset=iso-8859-1"; //Enc-type
            $subject = "Your Lost password";
            @mail($email,$subject,$message,$headers);
            return str_replace("\r\n","<br/ >",$message);
        }
    }
}


function checkEmailKey($security_key,$user_id)
{
    global $mysqli;
    $curDate = date("Y-m-d H:i:s");
    if ($stmt = $mysqli->prepare("SELECT user_id FROM password_reset WHERE security_key = ? AND user_id = ? AND expiry_date >= ?"))
    {
        $stmt->bind_param('sis',$security_key, $user_id, $curDate);
        $stmt->execute();
        $stmt->execute();
        $stmt->store_result();
        $numRows = $stmt->num_rows();
        $stmt->bind_result($user_id);
        $stmt->fetch();
        $stmt->close();
        if ($numRows > 0 && $user_id != '')
        {
            return array('status'=>true,'user_id'=>$user_id);
        }
    }
    return false;
}
 
function updateUserPassword($user_id, $password, $security_key)
{
    global $mysqli;
    if (checkEmailkey($security_key,$user_id) === false) return false;
    if ($stmt = $mysqli->prepare("UPDATE members SET password = ? WHERE id = ?"))
    {
        $password = hash('sha512',trim($password) . $salt);
        $stmt->bind_param('si',$password,$user_id);
        $stmt->execute();
        $stmt->close();
        $stmt = $mysqli->prepare("DELETE FROM password_reset WHERE security_key = ?");
        $stmt->bind_param('s',$security_key);
        $stmt->execute();
    }
}
 
function getUserName($user_id)
{
    global $mysqli;
    if ($stmt = $mysqli->prepare("SELECT username FROM members WHERE id = ?"))
    {
        $stmt->bind_param('i',$user_id);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($username);
        $stmt->fetch();
        $stmt->close();
    }
    return $username;
}



Edited by SalientAnimal
Link to comment
Share on other sites

  • 2 months later...

 

The form is updating the database with something, but I am not sure exactly with what, and why it is not working when trying to login with the new details.

 

What I have done, is I submitted the password to the table un-hashed to check that the correct password is being added, and this is correct. The only other thing that I feel my be cause any problems is the SALT which I have excluded from the script. I would really appreciate some help here.

 

Here are all the functions that I have, I assume it could be something to do with the login functions and the SALT conflicting, but I'm not entirely sure.

<?php

// includes/functions.php -->

//
//ERROR CHECKING FUNCTIONS - ADD TO PAGES TO CHECK FOR POSSIBLE ERRORS
//	var_dump(login_check($mysqli));
//	var_dump($_SESSION); exit; 
//	var_dump($_POST);exit; 

include_once 'psl-config.php';

function sec_session_start() {
    $session_name = 'sec_session_id';   // Set a custom session name
    $secure = SECURE;
    // This stops JavaScript being able to access the session id.
    $httponly = true;
    // Forces sessions to only use cookies.
    if (ini_set('session.use_only_cookies', 1) === FALSE) {
        header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
        exit();
    }
    // Gets current cookies params.
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params($cookieParams["lifetime"],
        $cookieParams["path"], 
        $cookieParams["domain"], 
        $secure,
        $httponly);
    // Sets the session name to the one set above.
    session_name($session_name);
    session_start();            // Start the PHP session 
    session_regenerate_id();    // regenerated the session, delete the old one. 
}



function login($email, $password, $mysqli) {
    // Using prepared statements means that SQL injection is not possible. 
    if ($stmt = $mysqli->prepare("SELECT id, username, password, email, level, salt 
        FROM members
       WHERE username = ?
        LIMIT 1")) {
        $stmt->bind_param('s', $email);  // Bind "$email" to parameter.
        $stmt->execute();    // Execute the prepared query.
        $stmt->store_result();

        // get variables from result.
        $stmt->bind_result($user_id, $username, $db_password, $email, $level, $salt);
        $stmt->fetch();

        // hash the password with the unique salt.
        $password = hash('sha512', $password . $salt);
        if ($stmt->num_rows == 1) {
            // If the user exists we check if the account is locked
            // from too many login attempts 
 
            if (checkbrute($user_id, $mysqli) == true) {
                // Account is locked 
                // Send an email to user saying their account is locked
                return false;
            } else {
                // Check if the password in the database matches
                // the password the user submitted.
                if ($db_password == $password) {
                    // Password is correct!
                    // Get the user-agent string of the user.
                    $user_browser = $_SERVER['HTTP_USER_AGENT'];
                    // XSS protection as we might print this value
                    $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                    $_SESSION['user_id'] = $user_id;
                    // XSS protection as we might print this value
                    $username = preg_replace("/[^a-zA-Z0-9_\-]+/", 
                                                                "", 
                                                                $username);
                    $_SESSION['username'] = $username;
                    $_SESSION['login_string'] = hash('sha512',$password . $user_browser);
					$_SESSION['email'] = $email;
					$_SESSION['level'] = $level;
					$_SESSION['session_status'] = $session_status;
                    $mysqli->query("SELECT * FROM login_success WHERE user_id = '$user_id'");
					if			  (mysql_num_rows($mysqli) > 0)
						{
						$mysqli->query("UPDATE login_success SET time = NOW() WHERE user_id = '$user_id'");
						}
					else
						{
						$mysqli->query("INSERT INTO login_success(user_id, time) VALUES ('$user_id', now()");
						}
					//UPDATE login_success SET time = now() where user_id = '$user_id'");							  
                    // Login successful.
                    return true;
                } else {
                    // Password is not correct
                    // We record this attempt in the database
                    //$now = time();
                    $mysqli->query("INSERT INTO login_attempts(user_id, time)
                                    VALUES ('$user_id', now())");
                    return false;
                }
            }
        } else {
            // No user exists.
            return false;
        }
    }
}



function checkbrute($user_id, $mysqli) {
    // Get timestamp of current time 
    $now = time();

    // All login attempts are counted from the past 2 hours. 
    $valid_attempts = $now - (2 * 60 * 60);

    if ($stmt = $mysqli->prepare("SELECT time 
                             FROM login_attempts 
                             WHERE user_id = ? 
                            AND time > '$valid_attempts'")) {
        $stmt->bind_param('i', $user_id);

        // Execute the prepared query. 
        $stmt->execute();
        $stmt->store_result();

        // If there have been more than 5 failed logins 
        if ($stmt->num_rows > 5) {
            return true;
        } else {
            return false;
        }
    }
}



function login_check($mysqli) 
	{
    // Check if all session variables are set 
    if (isset($_SESSION['user_id'], 
			  $_SESSION['username'], 
			  $_SESSION['login_string'],
			  $_SESSION['email'],
			  $_SESSION['level']
			  //$_SESSION['session_status']
			  )) 
	{

    $user_id = $_SESSION['user_id'];
    $login_string = $_SESSION['login_string'];
    $username = $_SESSION['username'];
	$email = $_SESSION['email'];
	$level = $_SESSION['level'];
	//$status = $_SESSON['session_status'];
		

        // Get the user-agent string of the user.
        $user_browser = $_SERVER['HTTP_USER_AGENT'];

        if ($stmt = $mysqli->prepare("SELECT password 
                                      FROM members 
                                      WHERE id = ? LIMIT 1")) {
            // Bind "$user_id" to parameter. 
            $stmt->bind_param('i', $user_id);
            $stmt->execute();   // Execute the prepared query.
            $stmt->store_result();

            if ($stmt->num_rows == 1) {
                // If the user exists get variables from result.
                $stmt->bind_result($password);
                $stmt->fetch();
                $login_check = hash('sha512', $password . $user_browser);

                if ($login_check == $login_string) {
                    // Logged In!!!! 
					//echo 'logged in';
                    return true;
                } else {
                    // Not logged in 
					echo 1;
                    return false;
                }
            } else {
                // Not logged in
					echo 2;
                return false;
            }
        } else {
            // Not logged in 
			echo 3;
            return false;
        }
    } else {
        // Not logged in 
		//echo 4;
        return false;
    }
}



function esc_url($url) {

    if ('' == $url) {
        return $url;
    }

    $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);

    $strip = array('%0d', '%0a', '%0D', '%0A');
    $url = (string) $url;

    $count = 1;
    while ($count) {
        $url = str_replace($strip, '', $url, $count);
   }

    $url = str_replace(';//', '://', $url);

    $url = htmlentities($url);

    $url = str_replace('&', '&', $url);
    $url = str_replace("'", ''', $url);

    if ($url[0] !== '/') {
        // We're only interested in relative links from $_SERVER['PHP_SELF']
        return '';
    } else {
        return $url;
    }
}





function crypto_rand_secure($min, $max) {
        $range = $max - $min;
        if ($range < 0) return $min; // not so random...
        $log = log($range, 2);
        $bytes = (int) ($log /  + 1; // length in bytes
        $bits = (int) $log + 1; // length in bits
        $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
        do {
            $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
            $rnd = $rnd & $filter; // discard irrelevant bits
        } while ($rnd >= $range);
        return $min + $rnd;
}

function getToken($length=32){
    $token = "";
    $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
    $codeAlphabet.= "0123456789";
    for($i=0;$i<$length;$i++){
        $token .= $codeAlphabet[crypto_rand_secure(0,strlen($codeAlphabet))];
    }
    return $token;
}






/* RESTRICTED ACCESS LEVEL MANAGEMENT */


	
	function checkLoginLevel() {
        $allowed = array(
            '0' => array('register.addinfo.php','process/*','includes/*','index.php','index.html'), /* NEW REGISTRATION ACCESS LEVELS */
            '1' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','walkin_form.php','walkin_delete.php'),		/* ACCESS LEVELS FROM RECEPTION */
            '2' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','first-page.php'),
            '3' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','retail_view.php','retail_viewer.php','walkin_form.php','retail_form.php'),
			'4' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','premier_form.php', 'second-page.php', 'third-page.php'), /* SUPERVISOR ACCESS LEVELS */
            '5' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','premier_form.php', 'second-page.php', 'third-page.php'), /* SUPERVISOR ACCESS LEVELS */
			'99' => true, /* ADMINISTRATION ACCESS LEVELS */
        );

    if(!isset($allowed[$_SESSION['level']])) {
        echo 'Your access level has not been set. Please return to the Login / Registration Page.';
        exit;
    }
	
	if($_SESSION['level'] == 0) {
	header('Location:register.addinfo.php');
	exit;
	}

    if(is_array($allowed[$_SESSION['level']])) {

        $file = $_SERVER["PHP_SELF"];
        $filearray = explode('/', $file);
        $filename = array_pop($filearray);
        $directory = array_pop($filearray);

        foreach($allowed[$_SESSION['level']] as $access) {
            if(strpos($access,'*')) {
                if($access == $directory . '/*') {
                    return true;
                }
            } elseif($access == $filename) {
                return true;
            }
        }
    }

    if(is_bool($allowed[$_SESSION['level']])) {
        return true;
    }

    echo 'You are not authorised to view this page. Please contact your manager to have your access level adjusted';
    exit;
}





//PSSWORD RESET FUNCTIONS




//define(PW_SALT,'(+3%_');
 
function checkUNEmail($username,$email)
{
    global $mysqli;
    $error = array('status'=>false,'user_id'=>0);
    if (isset($email) && trim($email) != '') {
        //email was entered
        if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE email = ? LIMIT 1"))
        {
            $stmt->bind_param('s',trim($email));
            $stmt->execute();
            $stmt->store_result();
            $numRows = $stmt->num_rows();
            $stmt->bind_result($user_id);
            $stmt->fetch();
            $stmt->close();
            if ($numRows >= 1) return array('status'=>true,'id'=>$user_id);
        } else { return $error; }
    } elseif (isset($username) && trim($username) != '') {
        //username was entered
        if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE username = ? LIMIT 1"))
        {
            $stmt->bind_param('s',trim($username));
            $stmt->execute();
            $stmt->store_result();
            $numRows = $stmt->num_rows();
            $stmt->bind_result($user_id);
            $stmt->fetch();
            $stmt->close();
            if ($numRows >= 1) return array('status'=>true,'id'=>$user_id);
        } else { return $error; }
    } else {
        //nothing was entered;
        return $error;
    }
}



function getSecurityQuestion($user_id)
{
    global $mysqli;
    $questions = array();
    $questions[0] = "What is your mother's maiden name?";
    $questions[1] = "What city were you born in?";
    $questions[2] = "What is your favorite colour?";
    $questions[3] = "What year did you graduate from High School?";
    $questions[4] = "What is your pet's name?";
    $questions[5] = "What is your favorite model of car?";
    if ($stmt = $mysqli->prepare("SELECT security_q FROM members WHERE id = ? LIMIT 1"))
    {
        $stmt->bind_param('i',$user_id);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($security_q);
        $stmt->fetch();
        $stmt->close();
		return $security_q;
    } else {
        return false;
    }
}
 
function checkSecAnswer($user_id, $security_a)
{
    global $mysqli;
    if ($stmt = $mysqli->prepare("SELECT username FROM members WHERE id = ? AND LOWER(security_a) = ? LIMIT 1"))
    {
        $security_a = strtolower($security_a);
        $stmt->bind_param('is',$user_id, $security_a);
        $stmt->execute();
        $stmt->store_result();
        $numRows = $stmt->num_rows();
        $stmt->close();
        if ($numRows >= 1) { return true; }
    } else {
        return false;
    }
}




function sendPasswordEmail($user_id)
{
    global $mysqli;
    if ($stmt = $mysqli->prepare("SELECT username, email, password FROM members WHERE id = ? LIMIT 1"))
    {
        $stmt->bind_param('i',$user_id);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($username, $email, $pword);
        $stmt->fetch();
        $stmt->close();
        $expFormat = mktime(date("H"), date("i"), date("s"), date("m")  , date("d")+3, date("Y"));
        $expDate = date("Y-m-d H:i:s",$expFormat);
        $security_key =  hash('sha512',$username . '_' . $email . rand(0,10000) .$expDate . $salt);
        if ($stmt = $mysqli->prepare("INSERT INTO password_reset (user_id, security_key, expiry_date) VALUES (?,?,?)"))
        {
            $stmt->bind_param('iss',$user_id, $security_key, $expDate);
            $stmt->execute();
            $stmt->close();
            $passwordLink = "<a href=\"?a=recover&email=" . $security_key . "&u=" . urlencode(base64_encode($user_id)) . "\">http://www.oursite.com/forgotPass.php?a=recover&email=" . $security_key . "&u=" . urlencode(base64_encode($user_id)) . "</a>";
            $message = "Dear $username,\r\n";
            $message .= "Please visit the following link to reset your password:\r\n";
            $message .= "-----------------------\r\n";
            $message .= "$passwordLink\r\n";
            $message .= "-----------------------\r\n";
            $message .= "Please be sure to copy the entire link into your browser. The link will expire after 3 days for security reasons.\r\n\r\n";
            $message .= "If you did not request this forgotten password email, no action is needed, your password will not be reset as long as the link above is not visited. However, you may want to log into your account and change your security password and answer, as someone may have guessed it.\r\n\r\n";
            $message .= "Thanks,\r\n";
            $message .= "-- Our site team";
            $headers .= "From: Our Site <webmaster@oursite.com
			
<script type='text/javascript'>
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>> \n";
            $headers .= "To-Sender: \n";
            $headers .= "X-Mailer: PHP\n"; // mailer
            $headers .= "Reply-To: webmaster@oursite.com<script type='text/javascript'>
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>\n"; // Reply address
            $headers .= "Return-Path: webmaster@oursite.com<script type='text/javascript'>
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>\n"; //Return Path for errors
            $headers .= "Content-Type: text/html; charset=iso-8859-1"; //Enc-type
            $subject = "Your Lost password";
            @mail($email,$subject,$message,$headers);
            return str_replace("\r\n","<br/ >",$message);
        }
    }
}


function checkEmailKey($security_key,$user_id)
{
    global $mysqli;
    $curDate = date("Y-m-d H:i:s");
    if ($stmt = $mysqli->prepare("SELECT user_id FROM password_reset WHERE security_key = ? AND user_id = ? AND expiry_date >= ?"))
    {
        $stmt->bind_param('sis',$security_key, $user_id, $curDate);
        $stmt->execute();
        $stmt->execute();
        $stmt->store_result();
        $numRows = $stmt->num_rows();
        $stmt->bind_result($user_id);
        $stmt->fetch();
        $stmt->close();
        if ($numRows > 0 && $user_id != '')
        {
            return array('status'=>true,'user_id'=>$user_id);
        }
    }
    return false;
}
 
function updateUserPassword($user_id, $password, $security_key)
{
    global $mysqli;
    if (checkEmailkey($security_key,$user_id) === false) return false;
    if ($stmt = $mysqli->prepare("UPDATE members SET password = ? WHERE id = ?"))
    {
        $password = hash('sha512',trim($password) . $salt);
        $stmt->bind_param('si',$password,$user_id);
        $stmt->execute();
        $stmt->close();
        $stmt = $mysqli->prepare("DELETE FROM password_reset WHERE security_key = ?");
        $stmt->bind_param('s',$security_key);
        $stmt->execute();
    }
}
 
function getUserName($user_id)
{
    global $mysqli;
    if ($stmt = $mysqli->prepare("SELECT username FROM members WHERE id = ?"))
    {
        $stmt->bind_param('i',$user_id);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($username);
        $stmt->fetch();
        $stmt->close();
    }
    return $username;
}


Hey there I have noticed your running accross the same issue as me, So maybe if I state what I have seen and accomplished someone will have an idea.

 

First, there is a conflict with our new password settings.  

define('PW_SALT','(+3%_');     <--- this is not the same as the one we are using in the registration process and its defined but you dont use it anywhere..

 

$password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);

    if (strlen($password) != 128) {

        // The hashed pwd should be 128 characters long.

        // If it's not, something really odd has happened

        $error_msg .= '<p class="error">Invalid password configuration.</p>';

    }

 

if (empty($error_msg)) {

        // Create a random salt

        $random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));

 

        // Create salted password

        $password = hash('sha512', $password . $random_salt);

 

these statements/values have been stored correctly into the database  ( password, salt )

 

note that when we use this function in the forgot password it does not use the same feature and it does not replace the ( salt ) statement/value in our table.

hence you will never login becasue the    [ password . random_salt]  =  [password . PW_SALT ]  these statements are not the same and do not produce the same varibles.

then we goto the 

 

["UPDATE `dbname` SET `tablename` = ? WHERE `id` = ?"]   

 

and look at this function 

 

$password = hash('sha512',trim($password) . PW_SALT);

$SQL->bind_param('si',$password,$userID);

 

 

"REMEMBER WHEN CHANGING THE 'bind_param' YOU ALSO HAVE TO CHANGE THE SUBMIT INPUT AS WELL"

 

case 3:

//we are submitting a new password (only for encrypted)

if ($_POST['user_id'] == '' || $_POST['security_key'] == '') header("location: ../index.php");

if (strcmp($_POST['pw0'],$_POST['pw1']) != 0 || trim($_POST['pw0']) == '')   

{

$error = true;

$show = 'recoverForm';

} else {

$error = false;

$show = 'recoverSuccess';

updateUserPassword($_POST['user_id'],$_POST['pw0'],$_POST['security_key']);   <--- NO SALT LISTED FOR INSERTIONINTO DBASE

}

 

we are not binding the new [salt]  value into the dbase so we have the incorrect hash or using the old salt from registration.

 

Now at my standing I have everything working except the new salt value being UPDATED into the table.

 

I also noticed the crypto and token your using are you also storing those values into the dbase or are they just a session value.

 

MY ISSUE IS BASICALLY THIS (NO NEW SALT BEING STORED INTO DBASE AFTER PASSWORD RESET)

 

 

[PASSWORDFORM]

            if ($_POST['userID'] == '' || $_POST['key'] == '') header("location: loginbus.php");

            if (strcmp($_POST['password'],$_POST['confirmpwd']) != 0 || trim($_POST['password']) == '')

            {

                $error = true;

                $show = 'recoverForm';

            } else {

                $error = false;

                $show = 'recoverSuccess';

                updateUserPassword($_POST['userID'],$_POST['password'],$_POST['key']);<-------------------$salt to be added here to but it is not a POST

            }

   

 

[FUNCTION]

function updateUserPassword($userID,$password,$key) <---------------$salt to be added here to

{

    global $mySQL;

    if (checkEmailKey($key,$userID) === false) return false;

    if ($SQL = $mySQL->prepare("UPDATE `members` SET `password` = ? WHERE `id` = ?"))<--------- UPDATE salt aswell

    

    {

        $password = hash('sha512',trim($password) . PW_SALT);

        $SQL->bind_param('si',$password,$userID);  <----------- Need to also add new $salt to the dbase also the 'si' = 'ssi'

        $SQL->execute();

        $SQL->close();

        $SQL = $mySQL->prepare("DELETE FROM `recoveryemails_enc` WHERE `Key` = ?");

        $SQL->bind_param('s',$key);

        $SQL->execute();

    }

}

 

 

I have tried to replace the PW_SALT with random_salt and also placed the same into the form but to no avail. I would get errors on no defined or amount of varibles incorrect.  I am showing the basic view of the start. I have been working on this part for about a week now. the reason for the need for these updates is the hash used for the login.

 

 ORIGINAL REGISTRATION PAGE (these are required to login)

if (empty($error_msg)) {

        // Create a random salt

        $random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));

 

        // Create salted password

        $password = hash('sha512', $password . $random_salt);

 

FUCTION LOGIN CHECK

 

// get variables from result.

        $stmt->bind_result($user_id, $username, $db_password, $salt);

        $stmt->fetch();

 

// hash the password with the unique salt.

        $password = hash('sha512', $password . $salt);

 

// If the user exists get variables from result.

                $stmt->bind_result($password);

                $stmt->fetch();

                $login_check = hash('sha512', $password . $user_browser);

 

THIS IS WHY IT IS NEEDED

 

THANK YOU SO MUCH FOR ANY HELP YOU CAN SUPPLY

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.