2016-09-03 4 views
1

Я пытаюсь выполнить аутентификацию пользователя с очевидным адресом электронной почты и паролем, а также если ban_status установлен в 0 в базе данных.Добавить дополнительное условие для входа в laravel 5.3

Я имел взгляд на новейшую Laravel документы и я попробовал это так в AuthenticateUsers.php

protected function validateLogin(Request $request) 
{ 
    $this->validate($request, [ 
     $this->username() => 'required', 'password' => 'required', 'ban_status' => '0', 
    ]); 
} 

Это не делает ничего, насколько я могу сказать и войти пользователь независимо от того, является ли статус запрета 0 или нет, где я должен делать это дополнительное условие?

ответ

1

Чтобы сделать длинный рассказ коротким, то, что вы на самом деле пытаетесь сделать в коде, который вы отправили, - это проверить значение ban_status, передаваемое с $request, или, другими словами, форму входа.

Мое понимание ваших вопросов в том, что на самом деле это не то, что вы хотите.

Вместо этого, попробуйте следующее:

Override login метод AuthenticatesUsers, определив его в LoginController со следующим небольшим добавлением проверить для ban_status:

public function login(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 ($lockedOut = $this->hasTooManyLoginAttempts($request)) { 
     $this->fireLockoutEvent($request); 

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

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

    if ($this->guard()->attempt($credentials, $request->has('remember'))) { 
     if ($this->guard()->user()->ban_status === 0) { // ADDED THIS CHECK 
      return $this->sendLoginResponse($request); 
     } 
    } 

    // 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. 
    if (! $lockedOut) { 
     $this->incrementLoginAttempts($request); 
    } 

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

Как бы я переопределить это? Могу ли я сделать маршрут для запроса на отправку/логин для входа в LoginController @ login? – user6073700

+0

На самом деле все, что вам нужно сделать, это скопировать и вставить новый код в свой LoginController. Все остальное может оставаться неизменным. Что мы делаем, это «переопределение» метода входа в систему с атрибутом AuthenticatesUsers. Если вы не знакомы с этой концепцией, проверьте [это] (http://php.net/manual/en/language.oop5.inheritance.php), а затем [это] (http://php.net/manual/en /language.oop5.traits.php). – tam5

+0

Ах да, это сработало, моя проблема была в том, что я использовал неправильный запрос, где бы я определил, куда пользователь идет, если сбой входа? i.e там ban_status не 0 – user6073700

1

Вы также можете вручную проверять подлинность пользователей :

public function authenticate(Request $request) 
{ 
    $password=$request->get('password'); 
    $email=$request->get('email'); 
    if (Auth::attempt(['email' => $email, 'password' => $password,'ban_status'=>0])) 
    {  
     return redirect()->intended('/'); 
    } 
    else 
    { 
     return redirect('/login');  
    }  
} 
+0

вы теряете дросселирование, если вы это делаете – tam5

2

Чтобы построить ответ на tam, я добавил перенаправление на основе отказавшего " banned ", потому что в противном случае я все равно войду в систему, хотя условие было ложным. Вот отмена функции входа, которая работала для меня, размещена в LoginController.php:

public function login(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); 
    } 

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

    if ($this->guard()->attempt($credentials, $request->has('remember'))) 
    {   
     if ($this->guard()->user()->ban_status === 0) { // ADDED THIS CHECK 
      return $this->sendLoginResponse($request); 
     } else { // logout and redirect if failed 
      $this->guard()->logout(); 
      return redirect()->back() 
       ->withInput($request->only($this->username(), 'remember')) 
       ->withErrors([ 
        $this->username() => 'You have been banned', 
       ]);   
     } 
    } 

    // 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); 
}