首页 > 解决方案 > Laravel:在自定义登录控制器中使用节流阀

问题描述

这是我的登录控制器功能

   use ThrottlesLogins;
   protected $maxLoginAttempts = 3;
   protected $lockoutTime = 300;

 public function login(Request $request)
    {       

        if ($this->hasTooManyLoginAttempts($request))
        {
        $this->fireLockoutEvent($request);
        return $this->sendLockoutResponse($request);
        }

        $validator = Validator::make(Input::all() , ['credential' => 'required|min:2|max:255', 'password' => 'required|string|min:8', ]);
        $cred = $request->credential;
        $pw = $request->password;
        $remember = (Input::has('remember')) ? true : false;

        if (filter_var($cred, FILTER_VALIDATE_EMAIL))
          {
          if (Auth::guard('customers')->attempt(['email' => $cred, 'password' => $pw, 'verified' => 1], $remember))
            {
            return redirect()->route('front');
            }
            else
            {
            return redirect()->route('customer-login-page')->with('error', 'Your credentials do not match');
            }
          }
          else
          {
            if (Auth::guard('customers')->attempt(['contact' => $cred, 'password' => $pw], $remember))
             {
              return redirect()->intended(route('front'));
             }
            else
            {
            return redirect()->route('customer-login-page')->with('error', 'Your credentials do not match');
            }
          }

    }



  protected function hasTooManyLoginAttempts(Request $request)
    {
       return $this->limiter()->tooManyAttempts(
           $this->throttleKey($request), $this->maxLoginAttempts, $this->lockoutTime
       );
    }

它不工作。我已经尝试了超过 3 次失败的登录尝试,但仍然没有受到限制。并且即使我发布了正确的凭据,登录和重定向仍然有效,但是当我检查请求时,我得到了

302 发现错误

在网络选项卡中

标签: phplaravelthrottling

解决方案


$this->incrementLoginAttempts($request)您需要通过调用(参见代码)让 trait 知道您正在执行登录尝试。您可以在现有的油门检查之后立即拨打此电话:

if ($this->hasTooManyLoginAttempts($request))
{
    $this->fireLockoutEvent($request);
    return $this->sendLockoutResponse($request);
}

$this->incrementLoginAttempts($request);

// other code

推荐阅读