Huy Le
Huy Le

Reputation: 389

Laravel 5.1: How to authenticate only active users

I want to add another condition in AuthController but I don't know how to do it.

In my Users table, I have a Active field. If a User has Active == 0, i want to not let he/she login into the system. I don't know where to add that condition in Laravel 5.1 AuthController.

Please help me with that. Thanks a lot guys!

Upvotes: 1

Views: 774

Answers (3)

Liyosi
Liyosi

Reputation: 609

Instead of overriding the whole postLogin function, add this to your AuthController

protected function getCredentials(Request $request)
{
    $crendentials=$request->only($this->loginUsername(), 'password');
    $crendentials['active']=1;
    return $crendentials;
}

Upvotes: 0

Moppo
Moppo

Reputation: 19285

You can override the postLogin method of the AuthenticatesUsers trait in your AuthController:

public function postLogin(Request $request)
{ 
    /* PLACE HERE VALIDATION CODE... */  

    //attempt login but not log in the user
    if ( ! Auth::attempt($credentials, false, false) )
    {
        //wrong credentials: redirect to login
    }   

    //CREDENTIALS OK

    //get user model from last attempt
    $user = Auth::getLastAttempted();

    //if user is not active... 
    if (! $user->active)
    {
        //do whathever you want: for example redirect to login    
    }

    //USER IS ACTIVE

    //login the user
    Auth::login($user, $request->has('remember')); 

    //redirect where you need
}

Check the original: vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers::postLogin method, to see if you need other instructions inside your overrided method (for example input validation)

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 420

You can add your custom postLogin() function in your Auth controller which overrides the default postLogin function with this condition

Auth::attempt(array('email' => $email, 'password' => $password, 'active' => 1))

This way you will only do auth of active users only

Cheers!!

Upvotes: 0

Related Questions