我正在使用Laravel开发Web应用程序。我现在想做的是尝试获取GET或渲染视图中的登录尝试次数。我可以在LoginController的发布请求(validateLogin方法)中获取登录尝试的次数,如下所示。
$this->limiter()->attempts($this->throttleKey($request))
问题是validateLogin方法采用一个参数Request $ request。我想做的是,我想获取登录尝试失败的次数或LoginController的showLoginForm方法中的尝试次数。我覆盖了showLoginForm方法。我尝试过了。
$this->limiter()->attempts($this->throttleKey(request()))
但是它总是返回零。那么,如何获得LoginController的GET或showLoginForm方法中的登录尝试次数?
答案 0 :(得分:1)
登录失败时,增加数字,登录成功后,清除尝试。可以使用会话来完成。通过会话,您可以在刀片文件和控制器中使用它。
在您的app/Http/Controllers/Auth/LoginController.php
文件中:
use Illuminate\Http\Request;
/**
* Get the failed login response instance.
*
* @param \Illuminate\Http\Request $request
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \Illuminate\Validation\ValidationException
*/
protected function sendFailedLoginResponse(Request $request)
{
$attempts = session()->get('login.attempts', 0); // get attempts, default: 0
session()->put('login.attempts', $attempts + 1); // increase attempts
throw ValidationException::withMessages([
$this->username() => [trans('auth.failed')],
]);
}
/**
* The user has been authenticated.
*
* @param \Illuminate\Http\Request $request
* @param mixed $user
* @return mixed
*/
protected function authenticated(Request $request, $user)
{
session()->forget('login.attempts'); // clear attempts
}
然后在您的视图或控制器中,您可以从会话中获取该号码:
{{ session()->get('login.attempts', 0) }}
答案 1 :(得分:0)
When we have a look at the throttleKey
method, we see that it creates a key out of the email address the user used tried to log in with and the IP address of the user. The IP address should already be in the $request
object if you add it as a parameter to the showLoginForm
method, but the email address wouldn't be there. You could add it using the old
helper function.
public function showLoginForm(Request $request)
{
$request->merge(['email' => old('email')]);
Log::info($this->limiter()->attempts($this->throttleKey($request)));
return view('auth.login');
}
Edit:
Another way to do this would be to overwrite the sendFailedLoginResponse
method and add the number attempts to the error bag. For example, in your LoginController
:
protected function sendFailedLoginResponse(Request $request)
{
throw ValidationException::withMessages([
$this->username() => [trans('auth.failed')],
'attempts' => $this->limiter()->attempts($this->throttleKey($request)),
]);
}
Then you could get the number of attempts in your template with <strong>{{ $errors->first('attempts') }}</strong>