-2

This login code is worked, but how did '$hashedpass' with hashed pass "$2y$10$..." variable?

Again. I need variable function '$hashedpass'. How give '$hashedpass'from DATABASE? Every user has variable pass/hash.

<?php
$data['error_message'] = $lang['error_empty_login'];

$loginId = $escapeObj->stringEscape($_POST['login_id']);

$hash = password_hash($_POST['login_password'], PASSWORD_DEFAULT);
$hashedpass='$2y$10$.............'; 
$crypto_pass = password_verify($hash, $hashedpass);

$userId = getUserId($conn, $loginId);

if ($userId)
{
$query = $conn->query("SELECT id,username,email_verified FROM " . DB_ACCOUNTS . " WHERE id=$userId AND password='$hashedpass' AND type='user' AND active=1");
$data['error_message'] = $lang['error_bad_login'];

if ($query->num_rows == 1)
{
$fetch = $query->fetch_array(MYSQLI_ASSOC);
$continue = true;

if ($config['email_verification'] == 1 && $fetch['email_verified'] == 0)
{
    $continue = false;
    $data['error_message'] = $lang['error_verify_email'];
}

if ($continue == true)
{
    $_SESSION['user_id'] = $fetch['id'];
    $_SESSION['user_pass'] = $hashedpass;

    if (isset($_POST['keep_logged_in']) && $_POST['keep_logged_in'] == true)
    {
        setcookie('sk_u_i', $_SESSION['user_id'], time() + (60 * 60 * 24 * 7));
        setcookie('sk_u_p', $_SESSION['user_pass'], time() + (60 * 60 * 24 * 7));
    }

    $data['status'] = 200;
    $data['redirect_url'] = smoothLink('index.php?tab1=home');
}
}
else
{
$data['error_message'] = $lang['incorrect_password'];
}
}
else
{
$data['error_message'] = $lang['no_user_found'];
}

header("Content-type: application/json; charset=utf-8");
echo json_encode($data);
$conn->close();
exit();

Thank you.

1 Answers1

3

You're doing it wrong. password_verify() expects the raw user-entered password string as its first argument, e.g.

$pw = $_POST['password'];
$user = $_POST['username'];

$info = get_user_information_from_database($user);

if(password_verify($pw, $info['storedhash'])) { 
   ... password matched hash ...
} else {
   ... incorrect pw/user
}

In other words, when the user record is created, you save the hash generated by password_hash(). When you go to verify/login the user, your retrieve the hash, then use the hash and the entered password with password_verify().

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • And in your case $Info['storedhash'] would be $fetch['password'], i.e. drop `AND password='$hashedpass'` from your WHERE clause and instead fetch that field from the record having `id=$userId`. – VolkerK Feb 24 '16 at 18:02