Javacadabra
Javacadabra

Reputation: 5758

Laravel Auth::attempt failing each time

I have created a test user on my laravel app. The details are

user: [email protected] pass: 123456

When I go through the registration process everything works as expected and an entry is made into the users table of the database

Once this is finished I redirect the user to the dashboard.

public function postCreate(){
        //Rules
        $rules = array(
        'fname'=>'required|alpha|min:2',
        'lname'=>'required|alpha|min:2',
        'email'=>'required|email|unique:users',
        'password'=>'required|alpha_num|between:6,12|confirmed',
        'password_confirmation'=>'required|alpha_num|between:6,12'
        );
        
        $validator = Validator::make(Input::all(), $rules);
        if($validator->passes()){
            //Save in DB - Success
            $user = new User;
            $user->fname = Input::get('fname'); //Get the details of form
            $user->lname = Input::get('lname');
            $user->email = Input::get('email');
            $user->password = Hash::make(Input::get('password'));//Encrypt the password
            $user->save();
            return Redirect::to('/books')->with('Thank you for Registering!');
        }else{
            //Display error - Failed
            return Redirect::to('/')->with('message', 'The Following Errors occurred')->withErrors($validator)->withInput();
        }
    }

I then navigate back to the landing page and attempt to log in using the credentials above and I keep getting told that Auth::attempt() is failing hence my user cannot log into the application.

public function login(){
        if(Auth::attempt(array('email'=>Input::get('email'), 'password'=>Input::get('password')))){
            //Login Success
            echo "Success"; die();
            return Redirect::to('/books');
        }else{
            //Login failed
            echo "Fail"; die();
            return Redirect::to('/')->with('message', 'Your username/password combination was incorrect')->withInput();
        }
    }

Does anyone know why this is happening? This is the Schema for my users table:

Schema::create('users', function($table){ 
            $table->increments('id'); 
            $table->integer('type')->unsigned(); 
            $table->string('fname', 255); 
            $table->string('lname', 255); 
            $table->string('email')->unique(); 
            $table->string('password', 60); 
            $table->string('school', 255); 
            $table->string('address_1', 255); 
            $table->string('address_2', 255); 
            $table->string('address_3', 255); 
            $table->string('address_4', 255);
            $table->string('remember_token', 100);
            $table->timestamps(); 
        });

Any help is much appreciated.

'View for Login':

<div class="page-header">
    <h1>Home page</h1>
</div>

<!-- Register Form -->
<form   action="{{ action('UsersController@postCreate') }}" method="post" role="form">
    <h2 class="form-signup-heading">Register</h2>
    <!-- Display Errors -->
    <ul>
        @foreach($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
    </ul>

    <!-- First Name -->
    <div class="form-group">
        <label>First Name</label>
        <input type="text" class="form-control" name="fname" /> 
    </div>
    <!-- Last Name -->
    <div class="form-group">
        <label>Last Name</label>
        <input type="text" class="form-control" name="lname" /> 
    </div>
    <!-- Email -->
    <div class="form-group">
        <label>Email</label>
        <input type="text" class="form-control" name="email" /> 
    </div>
    <!-- Password-->
    <div class="form-group">
        <label>Password</label>
        <input type="password" class="form-control" name="password" />  
    </div>
    <!-- Confirm Password -->
    <div class="form-group">
        <label>Confirm Password</label>
        <input type="password" class="form-control" name="password_confirmation" /> 
    </div>
    <input type="submit" value="Register" class="btn btn-primary"/>
</form>

<!-- Login Form -->
<form   action="{{ action('UsersController@login') }}" method="post" role="form">
    <h2 class="form-signup-heading">Login</h2>
    <!-- Email -->
    <div class="form-group">
        <label>Email</label>
        <input type="text" class="form-control" name="email" /> 
    </div>
    <!-- Password-->
    <div class="form-group">
        <label>Password</label>
        <input type="password" class="form-control" name="password" />  
    </div>
    <input type="submit" value="Login" class="btn btn-primary"/>
</form>

Upvotes: 6

Views: 14720

Answers (6)

Ivan Kamas
Ivan Kamas

Reputation: 39

I faces recently very same issue as is described.

My problem was that I did not have connected correct db - so indeed the user was not there. I was checking in from DB on docker (I imporeted into mysql instead of laravel which was defined in .env).

So make sure you are connected to correct DB.

Upvotes: 0

yaddly
yaddly

Reputation: 360

Good day, here is what I discovered when I encountered the same error: A simple string compare will reveal that the two hashing methods produce two different hashed values.

echo strcmp(Hash::make('password'),bcrypt('password'));

My assumption is that Auth::attempt([]) uses bcrypt() to hash out passwords which produces a different value to what you used Hash:make().

Upvotes: -1

Martin Zeitler
Martin Zeitler

Reputation: 76679

With password hashing enabled, the User model must override these methods:

public function getAuthIdentifierName()
{
    return 'email';
}

public function getAuthIdentifier()
{
    return request()->get('email');
}

public function getAuthPassword()
{
    return Hash::make(request()->get('password'));
}

Upvotes: 2

Laurence
Laurence

Reputation: 60048

Can you run this function below - and tell me where the error occurs? It will diagnose the problem:

public function testLogin()
{
     $user = new User;
     $user->fname = 'joe';
     $user->lname = 'joe';
     $user->email = '[email protected]';
     $user->password = Hash::make('123456');

     if ( ! ($user->save()))
     {
         dd('user is not being saved to database properly - this is the problem');          
     }

     if ( ! (Hash::check('123456', Hash::make('123456'))))
     {
         dd('hashing of password is not working correctly - this is the problem');          
     }

     if ( ! (Auth::attempt(array('email' => '[email protected]', 'password' => '123456'))))
     {
         dd('storage of user password is not working correctly - this is the problem');          
     }

     else
     {
         dd('everything is working when the correct data is supplied - so the problem is related to your forms and the data being passed to the function');
     }
}

Edit: one thought - are you sure the user is being correctly saved in the database? Have you tried to 'empty/delete' your database and try your code again? In your current code, it will fail if you keep registering with [email protected] - because it is unique. But you dont catch the error anywhere. So empty the database and try again...

Edit 2: I found another question you posted with the same problem - and in there you mentioned that the following code is your user model?

use Illuminate\Auth\UserTrait; 
use Illuminate\Auth\UserInterface; 
use Illuminate\Auth\Reminders\RemindableTrait; 
use Illuminate\Auth\Reminders\RemindableInterface; 

class User extends Eloquent implements UserInterface, RemindableInterface { 

use UserTrait, RemindableTrait; 

/** 
* The database table used by the model. 
* 
* @var string 
*/ 
protected $table = 'users'; 

/** 
* The attributes excluded from the model's JSON form. 
* 
* @var array 
*/ 
protected $hidden = array('password'); 

public function getAuthIdentifier() { 

} 

public function getAuthPassword() { 
} 

public function getRememberToken() { 

} 

public function getRememberTokenName() { 

} 

public function getReminderEmail() { 

} 

public function setRememberToken($value) { 

} 
}

Is that EXACTLY your current user model? Because if so - it is wrong - none of those functions should be blank.

This is what a CORRECT user model should look like for Laravel 4.2

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');

}

Upvotes: 14

kfriend
kfriend

Reputation: 2614

What is the value for strlen(Hash::make(Input::get('password')))? If it is greater than 60, then this would cause the authentication to fail each time, as the stored password is not the full hash.

Upvotes: 0

Alireza Rahmani Khalili
Alireza Rahmani Khalili

Reputation: 2954

You would make sure about:

  • your model:

mine looks like:

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

        protected $table = 'users';

        protected $hidden = array('password');

        public function getAuthIdentifier()
        {
            Return $this->getKey ();
        }
        public function getAuthPassword()
        {
            return $this->password;
        }
    }
  • make sure your app/config/auth.php is configured correctly
  • make sure app/config/app.php has service provider

'Illuminate\Auth\AuthServiceProvider',

  • Make sure your controller class has auth. before writing class you have used Auth (I mean include Auth class)

That all could make Auth doesn't work well

Upvotes: 2

Related Questions