Login only if user is active using Laravel

前端 未结 19 1579
孤城傲影
孤城傲影 2020-11-30 23:26

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 La

相关标签:
19条回答
  • 2020-11-30 23:57

    Probably not the best but, I think I found a cleaner way to override the login method. I tried this on Laravel 7

    in Auth\LoginController.php, put these classes

    use Illuminate\Support\Facades\Auth;
    use Illuminate\Validation\ValidationException;
    

    and then, add(override) these functions inside LoginController class:

    public function login(Request $request){        
        $this->validateLogin($request);
    
        if (method_exists($this, 'hasTooManyLoginAttempts') &&
            $this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);
    
            return $this->sendLockoutResponse($request);
        }
    
        if($this->guard()->validate($this->credentials($request))) {
            // Check if user is active, else return error message
            if(Auth::attempt(['email' => $request->email, 'password' => $request->password, 'status' => 'A'])) {
                return redirect()->intended('dashboard');
            }  else {
                // This will return the message required as desired
                return $this->inactiveCredential($request);
            }
        } else {            
            $this->incrementLoginAttempts($request);
            return $this->sendFailedLoginResponse($request);
        }
    }
    
    // Error massage for inactive credential
    private function inactiveCredential(Request $request){    
        throw ValidationException::withMessages([
            // auth.not-active can be added in resources/lang/en/auth.php
            $this->username() => [trans('auth.not-active')],
        ]);    
    }
    

    Then add this line in resources/lang/en/auth.php. If there are more than 1 language, you should put this line in there too.

    'not-active' => 'This account is already deleted. Contact administrator to revoke this account',
    

    Then you should have this response on the default laravel-ui login interface Login Credential

    0 讨论(0)
提交回复
热议问题