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

Я просмотрел новейшие документы laravel, и я попробовал это таким образом в AuthenticatesUsers.php

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

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

1
user6073700 4 Сен 2016 в 01:26

4 ответа

Лучший ответ

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

Насколько я понимаю, ваши вопросы таковы, что это не совсем то, что вам нужно.

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

Переопределите метод 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);
}
1
tam5 4 Сен 2016 в 02:19

Чтобы основываться на ответе тама, я добавил перенаправление, основанное на неудачном статусе «забанен», потому что в противном случае я все равно вошел бы в систему, даже если условие было ложным. Вот переопределение функции входа в систему, которая сработала для меня, помещенная в 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);
}  
3
user3703567 26 Окт 2016 в 04:37

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

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');      
    }       
}
1
Sanzeeb Aryal 4 Сен 2016 в 03:08

Вместо того, чтобы переопределить функцию login(), как в принятом ответе, вероятно, лучше переопределить функцию credentials(). Ожидается, что эта функция вернет массив значений для проверки в базе данных.

При сравнении с фиксированным значением, как в исходном вопросе, просто создайте массив и объедините его:

protected function credentials(Request $request)
{
    return array_merge(
        $request->only($this->username(), "password"),
        ["ban_status" => 0]
    );
}

Или, чтобы сравнить с динамическим значением (например, в форме входа есть <input type="hidden" name="your_field" value="42"/>), вы можете просто добавить его в список возвращаемых полей запроса.

protected function credentials(Request $request)
{
    return $request->only($this->username(), "password", "your_field");
}

Почему так лучше? Пользователь никогда не аутентифицируется в системе - запрос к базе данных не вернет результат, если не будут выполнены все условия. В принятом ответе пользователь сначала передает попытку входа в систему. Как выяснил user3703567, это может вызвать проблемы.

1
miken32 28 Авг 2018 в 02:34