Bigfella
Bigfella

Reputation: 27

How do I check a Password_Verify hash when logging in?

I have it where when a user creates a new account it will hash their password and store the hashed password into my database. I was using MD5 for just coding and working, but I'm wanting to hash passwords now. The registration is hashed but I have looked around on different sites but haven't found a way to hash my logins.

Heres my Registration:

// REGISTER USER
function register(){
    global $db, $errors;

    // receive all input values from the form
    $username    =  e($_POST['username']);
    $email       =  e($_POST['email']);
    $password_1  =  e($_POST['password_1']);
    $password_2  =  e($_POST['password_2']);
    $ipaddress =   $_SERVER['REMOTE_ADDR'];

    // form validation: ensure that the form is correctly filled
    if (empty($username)) { 
        array_push($errors, "Username is required"); 
    }
    if (empty($email)) { 
        array_push($errors, "Email is required"); 
    }
    if (empty($password_1)) { 
        array_push($errors, "Password is required"); 
    }
    if ($password_1 != $password_2) {
        array_push($errors, "The two passwords do not match");
    }

    // register user if there are no errors in the form
    if (count($errors) == 0) {
        //$password = md5($password_1);//encrypt the password before saving in the database
            $hashPassword = password_hash($password1,PASSWORD_BCRYPT);

        if (isset($_POST['user_type'])) {
            $user_type = e($_POST['user_type']);
            $query = "INSERT INTO users (username, email, user_type, password, registered_ipaddress) 
                      VALUES('$username', '$email', '$user_type', '$hashPassword', '$ipaddress')";
            mysqli_query($db, $query);
            $_SESSION['success']  = "New user successfully created!!";
            header('location: index.php');
        }else{
            $query = "INSERT INTO users (username, email, user_type, password, registered_ipaddress) 
                      VALUES('$username', '$email', 'user', '$hashPassword','$ipaddress')";
            mysqli_query($db, $query);

            // get id of the created user
            $logged_in_user_id = mysqli_insert_id($db);

            $_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
            $_SESSION['success']  = "You are now logged in";
            header('location: index.php');              
        }

    }

}

Heres the Login:

// LOGIN USER
    function login(){
        global $db, $username, $errors;

        // grap form values
        $username = e($_POST['username']);
        $password = e($_POST['password']);

        // make sure form is filled properly
        if (empty($username)) {
            array_push($errors, "Username is required");
        }
        if (empty($password)) {
            array_push($errors, "Password is required");
        }
        // attempt login if no errors on form
        if (count($errors) == 0) {
            $password = ($password);


            $query = "SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1";
            $results = mysqli_query($db, $query);

            if (mysqli_num_rows($results) == 1) { // user found
                // check if user is admin or user
                $logged_in_user = mysqli_fetch_assoc($results);
                if ($logged_in_user['user_type'] == 'admin') {

                    $_SESSION['user'] = $logged_in_user;
                    $_SESSION['success']  = "You are now logged in";
                    header('location: admin/index.php');          
                }else{
                    $_SESSION['user'] = $logged_in_user;
                    $_SESSION['success']  = "You are now logged in";

                    header('location: index.php');
                }
            }else {
                array_push($errors, "Wrong username/password combination");
            }
        }
    }

This is What I've Tried when trying to see if the password is correct, but it still doesn't log me in:

// attempt login if no errors on form
        if (count($errors) == 0) {
            $password = ($password);


        $passwordunlocked = (password_verify($password, $hashPassword));

            $query = "SELECT * FROM users WHERE username='$username' AND password='$passwordunlocked' LIMIT 1";
            $results = mysqli_query($db, $query);

            if (mysqli_num_rows($results) == 1) { // user found
                // check if user is admin or user

Any Ideas on How I can verify the hash of the password that is stored in my database? Thank You In Advance!

Upvotes: 1

Views: 1540

Answers (3)

LKKP4ThX
LKKP4ThX

Reputation: 236

Your code is vulnerable to SQL-Injection

Please use Prepared Statements instead of inserting your variables directly into your database queries.

Your login query is faulty. You can't select the user from database with the password he entered, because you saved the hash in the database, not the plaintext-password. So the query will never return any result.

Try this instead in your login:

$query = "SELECT * FROM users WHERE username='$username' LIMIT 1";
$results = mysqli_query($db, $query);

if (mysqli_num_rows($results) == 1) { // user found
$logged_in_user = mysqli_fetch_assoc($results);

  // check if entered password matches hash from database
  if(password_verify($password, $logged_in_user['password'])) {

    // check if user is admin or user         
    if ($logged_in_user['user_type'] == 'admin') {

Also, your third part of code ($passwordunlocked) won't work, because password_verify() returns a boolean (true/false), not any comparable hash.

Upvotes: 1

parsa
parsa

Reputation: 995

you have to do these functions on every input they give in registration for password. the inputs will be saved in database hashed. so if you want to extract the password from database to check with their login just extract the data from database(which is hashed) and hash the login input and check both together to see if the user who wants to login is authenticated: heres the code:

function passHashingLogin($string)
{
    if(!empty($string))
    {
        $password = password_hash($string,PASSWORD_BCRYPT,['cost'=>11 , 'salt'=>'oewfo%$#&*hjfs124hikdendei']);
    }
    else
    {
        $newPassword = substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil(10/strlen($x)) )),1,10);
        $password = password_hash($newPassword,PASSWORD_BCRYPT,['cost'=>11 , 'salt'=>'oewfo%$#&*hjfs124hikdendei']);
    }
    return $password;
}

function sanitizeStringLogin($string)
{
    $string = stripslashes($string);
    $string = htmlentities($string);
    $string = strip_tags($string);
    return $string;
}//sanitizeString method

Upvotes: 0

Jignesh Bhavani
Jignesh Bhavani

Reputation: 393

You might wanna check php documentation. password_verify

In your case compare the hash that stored in database.

$password_that_user_entered = $_POST['password'];

if (password_verify( $password_that_user_entered , $hash_stored_in_database)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

Upvotes: 0

Related Questions