Add login condition to laravel ui auth

2k views Asked by At

I am using laravel ui auth package for my login. But i want to add new condition for the user to login besides email and password which is isBanned boolean. However, i dont know where and files for me to edit to add the new condition.

1

There are 1 answers

10
lagbox On

You should have a Controller in app/Http/Controllers/Auth named LoginController. This Controller uses a trait AuthenticatesUsers. What you want to do is adjust the credentials passed to attempt that is happening. This can be done by overriding the credentials method on LoginController:

use Illuminate\Http\Request;

...

protected function credentials(Request $request)
{
    return $request->only($this->username(), 'password') + [
        'isBanned' => false
    ];
}

This is adding isBanned to the credentials which are all "where" conditions on a query to find the user (except for the 'password' field).

UPDATE:

If you want to be able to know if the user had bad credentials or if they are banned then you don't need to override the credentials method and you can just override the attemptLogin method and the sendFailedLoginResponse method on LoginController:

protected function attemptLogin(Request $request)
{
    return $this->guard()->attemptWhen(
        $this->credentials($request),
        fn ($user) => ! $user->isBanned,
        $request->filled('remember')
    )
}


protected function sendFailedLoginResponse(Request $request)
{
    $user = $this->guard()->getLastAttempted();

    throw ValidationException::withMessages([
        $this->username() => [
            $user && $this->guard()->getProvider()->validateCredentials($user, $this->credentials($request))
                ? 'You are banned'
                : trans('auth.failed')
        ]
    ]);
}

We are not adjusting the credentials so we are letting the User Provider get the user based on their credentials (username/email and password). The call to attemptWhen lets us add a callback condition to see if we want to log them in after we have retrieved the user by their credentials and validated them. We create a callback that checks if the user is banned. In the sendFailedLoginResponse we are checking to see if the guard has a lastAttempted set (did the User Provider retrieve a user based on credentials). If it does have a User and the credentials are valid then they must be banned otherwise they would have been logged in. All other cases we return the auth failed message.