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

前端 未结 5 2092
春和景丽
春和景丽 2021-02-05 20:56

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         


        
5条回答
  •  既然无缘
    2021-02-05 21:32

    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.

提交回复
热议问题