Laravel:在自定义登录中集成限制

如果我不使用laravel给出的默认LoginController,如何集成laravel油门?

这是我的控制器:

  use AuthenticatesUsers;

  //function for login
  public function login(Request $requests){
    $username = $requests->username;
    $password = $requests->password;

    /**to login using email or username**/
    if(filter_var($username, FILTER_VALIDATE_EMAIL)) {

      Auth::attempt(['email' => $username, 'password' => $password]);
    } else {

      Auth::attempt(['username' => $username, 'password' => $password]);
    }


    if(Auth::check()){
      if(Auth::user()->type_user == 0){

        return view('users.dashboard');

      }
      else{
        return view('admin.dashboard');
      }
    }
    else{

      return Redirect::back()->withInput()->withErrors(['message'=>$login_error],'login');

    }
  }

我想限制失败的登录,但我似乎无法使用自己的控制器使其工作。你们能帮帮我吗?


答案 1

在方法中添加以下代码。让它成为第一件事

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

现在添加以下代码,其中登录失败。这将增加失败的尝试计数。

$this->incrementLoginAttempts($request);

成功登录后,添加以下代码以使其重置。

$this->clearLoginAttempts($request);

答案 2

尝试向控制器的构造函数添加限制,如下所示:

/**
 * Create a new login controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('throttle:3,1')->only('login');
}

不幸的是,Laravel文档对节流没有太多说明:https://laravel.com/docs/6.x/authentication#login-throttling

但是,字符串的部分对应于最多 3 次尝试,衰减时间为 1 分钟。3,1

throttle可以在数组中定义,如下所示:
。Laravel文档在这里解释了这种方法:https://laravel.com/docs/6.x/middleware#assigning-middleware-to-routes/project-root/laravel/app/Http/Kernel.phprouteMiddleware'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,


推荐