Vojta
Vojta

Reputation: 379

Laravel Authenticating A User With Conditions

I have a question to Authenticating A User With Conditions part in Laravel documentation.

In which controller and method should I insert this condition to make it work across the application. I didn't quite catch it. Is it constructor of app/Http/Controllers/Auth/LoginController ?

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1]))
{
    // The user is active, not suspended, and exists.
}

Thank you

Upvotes: 0

Views: 92

Answers (1)

Devon Bessemer
Devon Bessemer

Reputation: 35337

It depends which version you're using. You linked to a 5.0 doc, so I'm not sure if you're actually using that.

In recent versions, you can either override the entire LoginController::login method or you can drill down to just the LoginController::attemptLogin method. Both of which are actually defined in the AuthenticateUsers trait.


I tend to handle this differently. If a user is inactive or suspended, I like to display a different message to them than just a generic failed login. I'd prefer to use a middleware to check their status and redirect them with message about their account.

class CheckActiveMiddleware 
{
    public function handle($request, Closure $next)
    {
        // Check that the user is still active
        if($request->user()->active)
        {
            return $next($request);
        }
        return redirect('/login')->withErrors('Your account has been deactivated.');
    }
}

This also allows you to deactivate users that are still logged in. Since with your method, a logged in user that selected 'Remember Me' would still be able to use the application until they log out since your check is only on the log in.

Upvotes: 1

Related Questions