Login only if user is active using Laravel

Micael Sousa picture Micael Sousa · Jun 24, 2015 · Viewed 67k times · Source

I'm currently working on my Laravel app and to prevent spam I decided that only active users are able to login. I'm currently using Laravel's login system just like in Laravel's official website tutorial, here's my form action:

<form class="form-horizontal" role="form" method="POST" action="{{ url('/auth/login') }}">

This works completely fine, however I'd like to check the user's active, if not active it would be redirected to the activation page, otherwise it would login. Is there a simple way to do this or am I obligated to make a new controller, routes and more verifications? Thank you.

Edit: Forgot to mention that I have a 'active' column in my database.

Answer

BrokenBinary picture BrokenBinary · Jun 24, 2015

Laravel 5.4 / 5.5

Override the default login() function by placing this function in your LoginController:

public function login(\Illuminate\Http\Request $request) {
    $this->validateLogin($request);

    // If the class is using the ThrottlesLogins trait, we can automatically throttle
    // the login attempts for this application. We'll key this by the username and
    // the IP address of the client making these requests into this application.
    if ($this->hasTooManyLoginAttempts($request)) {
        $this->fireLockoutEvent($request);
        return $this->sendLockoutResponse($request);
    }

    // This section is the only change
    if ($this->guard()->validate($this->credentials($request))) {
        $user = $this->guard()->getLastAttempted();

        // Make sure the user is active
        if ($user->active && $this->attemptLogin($request)) {
            // Send the normal successful login response
            return $this->sendLoginResponse($request);
        } else {
            // Increment the failed login attempts and redirect back to the
            // login form with an error message.
            $this->incrementLoginAttempts($request);
            return redirect()
                ->back()
                ->withInput($request->only($this->username(), 'remember'))
                ->withErrors(['active' => 'You must be active to login.']);
        }
    }

    // If the login attempt was unsuccessful we will increment the number of attempts
    // to login and redirect the user back to the login form. Of course, when this
    // user surpasses their maximum number of attempts they will get locked out.
    $this->incrementLoginAttempts($request);

    return $this->sendFailedLoginResponse($request);
}

Overriding the login() method in this way is recommended over many of the other answers on this question because it allows you to still use many of the more advanced authentication functionality of Laravel 5.4+ such as login throttling, multiple authentication guard drivers/providers, etc. while still allowing you to set a custom error message.


Laravel 5.3

Change or override your postLogin() function in your AuthController to look like this:

public function postLogin(Request $request)
{
    $this->validate($request, [
        'email' => 'required|email', 'password' => 'required',
    ]);

    $credentials = $this->getCredentials($request);

    // This section is the only change
    if (Auth::validate($credentials)) {
        $user = Auth::getLastAttempted();
        if ($user->active) {
            Auth::login($user, $request->has('remember'));
            return redirect()->intended($this->redirectPath());
        } else {
            return redirect($this->loginPath()) // Change this to redirect elsewhere
                ->withInput($request->only('email', 'remember'))
                ->withErrors([
                    'active' => 'You must be active to login.'
                ]);
        }
    }

    return redirect($this->loginPath())
        ->withInput($request->only('email', 'remember'))
        ->withErrors([
            'email' => $this->getFailedLoginMessage(),
        ]);

}

This code redirects back to the login page with an error message about the user being inactive. If you want to redirect to an authentication page you would change the line I marked with the comment Change this to redirect elsewhere.