0

I am writing an API for a login page, where the password is encrypted and stored in the database as: "$2y$08$NwjkR19Vafs28PuSmVrd6OIpL2ix2hUZn4cFwwJqseUQJZqJIXpia". How do I verify this against the password entered by using an sql query , below is my API code:

if (isset($postdata)) {

    $request = json_decode($postdata);

    $username = $request->username;
    $password = $request->password;

    if( $username === NULL && $password === NULL) {
        $json = array("status" => 0, "message" => "Please enter username and password");
    }
    else {

        $select_sql = "SELECT `id`, `first_name`, `last_name`, `email`, `phone`, `username`, `password`, `created_on`, `active`, `activation_code` FROM `users` WHERE `email` = '".$username."' AND `password` = '".$password."';";
        $select_query = mysqli_query($con,$select_sql);
        $count = mysqli_num_rows($select_query);
        $fetch_obj = mysqli_fetch_array($select_query,MYSQLI_BOTH);
        if($count>0) {

            $userId = $fetch_obj["id"];
            $userEmail = $fetch_obj["email"];
            $userDisplayName = $fetch_obj["first_name"]." ".$fetch_obj["last_name"];
            $userPhone = $fetch_obj["phone"];
            $userName = $fetch_obj["username"];
            $userPass = $fetch_obj["password"];
            $userCreatedOn = $fetch_obj["created_on"];
            $userActive = $fetch_obj["active"];
            $userActivationCode = $fetch_obj["activation_code"];

            $userDetails = array( "UserID" => "$userId", "UserDisplayName" => "$userDisplayName", "UserEmail" => "$userEmail", "UserPhone" => "$userPhone", "UserName" => "$userName", "UserPassword" => "$userPass", "UserCreatedOn" => "$userCreatedOn","UserActive" => "$userActive", "UserActivationCode" => "$userActivationCode");

            $json = array("status" => 1, "message" => "Login success.", "UserDetails" => $userDetails);
        }
        else {
            $json = array("status" => 0, "message" => "Invalid username or password.", "query" => $select_sql );
        }
    }
}
mysqli_close($con);

I have tried using the below code but no matter what password I enter here it shows as Valid password,

 <?php

  echo $password = "John@798";
  echo $hash =  password_hash($password, PASSWORD_BCRYPT);
  if (password_verify($password, $hash)) {
  echo 'Password is valid!';
  } else {
  echo 'Invalid password.';
  }
  ?>

Is there any way I can check the password entered and then redirect the user to the homepage? Please help me, am stuck with this since past 2 days. Thanks in advance

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • What is the encryption method you used to encrypt password? – ashanrupasinghe May 04 '17 at 07:40
  • 1
    **WARNING**: Writing your own access control layer is not easy and there are many opportunities to get it severely wrong. Please, do not write your own authentication system when any modern [development framework](http://codegeekz.com/best-php-frameworks-for-developers/) like [Laravel](http://laravel.com/) comes with a robust [authentication system](https://laravel.com/docs/5.4/authentication) built-in. – tadman May 04 '17 at 07:58
  • **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST`, `$_GET` or **any** user data directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman May 04 '17 at 08:00
  • Also **PLEASE** do not drop user entered data directly into a query without any form of sanitization, treatment etc. Read more [Here](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) or [Here](http://stackoverflow.com/questions/11839523/secure-against-sql-injection-pdo-mysqli) – nageeb May 04 '17 at 08:02
  • Thanks for those suggestions –  May 04 '17 at 13:49

1 Answers1

1

Please format your code better next time.

This function

<?php
echo $password = "John@798";
echo $hash = password_hash($password, PASSWORD_BCRYPT);
if (password_verify($password, $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}
?>

always show valid password because you set the hash based on the password and verify that password with the result hash. If you want it to return invalid password, set it to be something else, like this

echo $password = "Wrong Password";
echo $hash = password_hash("John@798", PASSWORD_BCRYPT);

For your first code block, $password is the hash you store in the database, $userPass is the password that user enters in the form and you need to verify it. Here is the code to check if it's a valid password.

if (password_verify($userPass, $password)) {
    echo "Correct Password";
} else {
    echo "Invalid Password";
}
  • @Nguyen So you mean, the $userPass corresponds to the password entered by user in the app (say for eg: "Pass1234" is the password entered) and then how will it be equal to the $password field which is the hash value stored in the database? Am sorry if this is confusing you –  May 04 '17 at 14:00
  • The $userPass won't be equal to the $password field that you store in the database. That's why you need to use password_verify function to check if the user input string ($userPass) is the correct password comparing to the hash string ($password). – Ngoc Nguyen May 17 '17 at 04:57