How to check the hash value in the database in Laravel tests?



  • I need to check the hash of the user's password in the database in the test.

    Laravel has a seeInDatabase method, it checks if a record exists in a table using an array of key-values. With its help, it is impossible to check the field with a hashed value, because the bcrypt function returns different values ​​each time.

    Test code:

    public function testResetFinancePasswordAPI ()
    {
        / ** @var array $ users * /
        $ users = $ this-> seedUsers ();
    
        foreach ($ users as $ user) {
            / ** @var \ App \ Models \ User $ user * /
    
            $ this-> be ($ user);
    
            $ request = [
                'current_finance_password' => $ this-> financePassword,
                'new_finance_password' => $ this-> newFinancePassword,
            ];
    
            $ this-> post ('/ lk / settings / reset_finance_password', $ request);
    
            $ this-> assertResponseOk ();
            $ this-> seeJson ();
            $ this-> seeInDatabase ('users', [
                'id' => $ user-> id,
                'finance_password' => bcrypt ($ this-> newFinancePassword),
            ]);
        }
    }
    

    P.S. Laravel version is 5.3



  • From the documentation we see that the standard authorization uses the Hash facade, and there is a method there:

    if (Hash :: check ('plain-text', $ hashedPassword)) {
         // The passwords match ...
    }
    

    Accordingly, you need to do $ this-> assertTrue (Hash :: check ($ this-> newFinancePassword, $ user-> password)), only the selection from the database will have to be repeated, otherwise there may be a cache



  • Thanks! I thought of doing the same a few minutes before your answer πŸ˜‚ I just assumed that perhaps Laravel has some standard solution in the form of a method like assertHash or something like that ... As a result, I extended the TestCase class and added the required method with this functionality.



  • @elysha Yes, this happens πŸ™‚ Suffering for a long time, ask a question, and then understand how to do it without an answer πŸ™‚



Suggested Topics