Password hashing: how to log in after registering a hashed password on Database?

I’m trying to insert a hashed password on Database. The code to hash the text works, but I don’t know how to write a code that can verify the hash registered on Database and then log in.

In other words…

  • I registered a password named ‘pass’
  • The code hashed it and registered on DB as something like ‘kjgdvhfjgsdkjfgsdklfjgakjsdgfksghcvkly7e89634ryhner8’;
  • Now I want to log in to my system with the original password ‘pass’.

AddNewAdmin.php

  //Query to insert new admin in DB when everything is fine...
        $HashPass = password_hash($Password, PASSWORD_DEFAULT);
        global $ConnectingDB;
        $sql = "INSERT INTO admins(datetime,username,password,aname,addedby)";
        $sql .= "VALUES(:dateTime,:userName,:password,:aName,:adminName)";
        $stmt = $ConnectingDB->prepare($sql);
        $stmt->bindValue(':dateTime', $DateTime);
        $stmt->bindValue(':userName', $UserName);
        $stmt->bindValue(':password', $HashPass);
        $stmt->bindValue(':aName', $Name);
        $stmt->bindValue(':adminName', $Admin);
        $Execute = $stmt->execute();
        if ($Execute) {
            $_SESSION["SuccessMessage"] = "Admin added successfully!";
            Redirect_to("AddNewAdmin.php");
        } else {
            $_SESSION["ErrorMessage"] = "Something went wrong. Try again.";
            Redirect_to("AddNewAdmin.php");
        }

AdminLogin.php

if (isset($_SESSION["UserId"])) {
    Redirect_to("Dashboard.php?page=1");
}

if (isset($_POST["Submit"])) {
    $UserName = $_POST["Username"];
    $Password = $_POST["Password"];
    if (empty($UserName) || empty($Password)) {
        $_SESSION["ErrorMessage"] = "All fields must be filled out.";
        Redirect_to("AdminLogin.php");
    } else {
        // code for checking username and password from Database
        $Found_Account = Login_Attempt($UserName, $Password);
        if ($Found_Account) {
            $_SESSION["UserId"] = $Found_Account["id"];
            $_SESSION["UserName"] = $Found_Account["username"];
            $_SESSION["AdminName"] = $Found_Account["aname"];
            $_SESSION["SuccessMessage"] = "Welcome " . $_SESSION["AdminName"] . "!";
            if (isset($_SESSION["TrackingURL"])) {
                Redirect_to($_SESSION["TrackingURL"]);
            }
            Redirect_to("Dashboard.php?page=1");
        } else {
            $_SESSION["ErrorMessage"] = "Incorrect username or password.";
            Redirect_to("AdminLogin.php");
        }
    }
}

You would build and execute a prepared SELECT query to find if there is a row of data matching the submitted username. If there is a row of data, you would use password_verify() to test if the submitted password matches the saved hash value.

As to the code you have shown, there are a number of issues, but the biggest one is having a database table named admins. An administrator is a user with a particular set of permissions. By having this table and potentially a table for regular users, you will have duplicate UserId values. This will create confusion and a security issue for anyone trying to maintain this code, and will result in a bad User eXperience (UX) for those trying to log into the web site. All user information should be stored in one table and all logins to a site should be handled the same. The only user information you store in a session variable should be the UserId. To get any other user information or the user’s permissions, query on each page request to get that data.

1 Like

Here’s an example on one of my pages:

if ((isset($_SESSION['last_login']) && $_SESSION['last_login'])) {
    $username = $login->username($_SESSION['id']);
}

The only information stored in session is non-personal information that way if anyone were to hack the website that the only information they would get. Most people don’t like getting their addresses, email, telephone numbers and even their own names getting into the wrong hands. I suppose username wouldn’t be too bad, but some people might use that username all over on the internet and one less thing a hacker would have to know about the person. I’m even paranoid when a person logins that I unset the password after a successful login even though it isn’t stored in sessions, plus regenerate the sessions id.

    unset($this->result->password);
    unset($password);
    session_regenerate_id();

A person on another forum even writes his own hash routine so he doesn’t have to deal with it as he doesn’t trust password_hash and password_verify, but I think that is going a little too far, plus then you are starting to develop your own security code which in my opinion should be done by security professionals.

That is redundant. You only need

if ($_SESSION['last_login']){
//do something
}

Not really, as it’s on a page that a person doesn’t have to be logged in and the only set when one is logged in:

Notice** : Undefined index: last_login in /Applications/MAMP/htdocs/mainsite_08182020/index.php on line **33

Though (isset($_SESSION['last_login])) should work looking at it. Taken from an old tutorial I don’t know why the person who did the the tutorial that way? Though I might had lifted it where he was doing something else, but still? Hmm? Though to be honest I like the tutorial, but didn’t like he how handled true if statements as he made thinking about what true in an if statement really meant. He made it confusing is what I mean as true wasn’t clearcut with him.

YES, really.

Try this with and without a value.

<?php

$var = 'x';

if (isset($var) && $var) {
    echo "This will print one.<br>";
}

if ($var) {
    echo "This will print two.";
}

Actually, there’s no table users, but only admins, since It’s a blog website where the only people who can be registered and log in are the admins.

Sponsor our Newsletter | Privacy Policy | Terms of Service