Search code examples
phplaravelpassword-hash

Hash:check() doesn't return result expected Laravel 10


I'm traing to check a password validation without do login in a Laravel 10 project, but the function 'check' returns false, moreover, I can do login with the same password. I Don't know why return false.

Thanks.

    public function recharge_by_client(Request $request){

        $telf      = $request->telf;
        $password  = $request->password;
        $credit    = $request->credit;

        try {
            $client = Client::where('telf', $telf)->first();

            //if verification data is false, returning 0. 
            if ($client && Hash::check($password, $client->password)) {
                \Log::info('Entramos a update');
                HomeHelper::recharge_money($client->id, $credit);
            }else{
                \Log::info('NO entramos a update');
                return ['credit_updated' => 0];
            }
        } catch (\Exception $e) {
            \Log::info($e->getMessage());
            //A exception has ocurre, returning 0.
            return ['credit_updated' => 0];
        }

        //Returning current credit.
        return ['credit_updated' => Client::find($client->id)->credit];
    }

Solution

  • Here are the troubleshooting steps that will help solve this.

    1 Try a Test with Known Values: You should be able to reproduce this by testing the Hash::check() with known values. using a test route you can Manually hash a password, and then attempt to check it with the same password to see if Hash::check() still returns false. here is a sample code that can help with that.

    $knownPassword = 'password123';
    $hashed = Hash::make($knownPassword);
    
    if (Hash::check($knownPassword, $hashed)) {
        echo 'Password check succeeded.';
    } else {
        echo 'Password check failed.';
    }
    
    
    1. Hash Format Consistency: Check your database to ensure the hash format is stored correctly and hasn't been altered or truncated (due to field size). ideally i set this to varchar(100) or longer

    2. White Spaces or Special Characters: Confirm there are no extra white spaces or special characters in the password hash. are you trimming the input from the user request?

    3. Confirm the user/record information is retrieved: confirm this section of code (Client::where('telf', $telf)->first()) is indeed fetching the right record, you can run a dd() to confirm the record.

    I think one of these should help you with debugging and solving this. Cheers