haheute haheute - 22 days ago 9
PHP Question

extend laravel 5 built-in authentication to login only "if user == active"

I use the included authentication of laravel 5.1.6 and want to know how I can extend it, to work like this:

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


If the user is not "active", the login should not be possible. I have an 'active' column in the users table , with 0 or 1 as value. How can i do this while still using the built in authentication with login throtteling.

edit:

I don't have a postLogin function in the AuthController, only a
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
, a
__construct()
, a
validator()
and a
create()
function. Do I have to change something in the trait in
Illuminate\Foundation\Auth\..
or must I add the the
postLogin()
function in the AuthController ?

Answer

You can just override the getCredentials() method in your AuthController:

class AuthController extends Controller
{
    use AuthenticatesAndRegistersUsers;

    public function getCredentials($request)
    {
        $credentials = $request->only($this->loginUsername(), 'password');

        return array_add($credentials, 'active', '1');
    }
}

This will add the active = 1 constraint when trying to authenticate a user.

EDIT: If you want a separate error message like BrokenBinary says, then Laravel allows you to define a method called authenticated that is called after a user has been authenticated, but before the redirect, allowing you to do any post-login processing. So you could utilise this by checking if the authenticated user is active, and throw an exception or display an error message if not:

class AuthController extends Controller
{
    use AuthenticatesAndRegistersUsers;

    public function authenticated(Request $request, User $user)
    {
        if ($user->active) {
            return redirect()->intended($this->redirectPath());
        } else {
            // Raise exception, or redirect with error saying account is not active
        }
    }
}

Don’t forget to import the Request class and User model class.

Comments