Laravel: Integrating Throttle in Custom Login

Viewed 17476

How to integrate laravel throttle if I did not use the default LoginController given by laravel?

here's my controller:

  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');

    }
  }

I want to limit the failed logins but I can't seem to make it work using my own controller. Can you guys help me please?

7 Answers

add the following code inside your method. make it the first thing

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

now add the following code where log in fails. this will increment the failed attempt count.

$this->incrementLoginAttempts($request);

on successful login, add the following code so it resets.

$this->clearLoginAttempts($request);

Try adding throttling to your controller's constructor, like so:

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

Unfortunately, the Laravel docs don't say much about throttling: https://laravel.com/docs/6.x/authentication#login-throttling

However, the 3,1 part of the string corresponds to a maximum of 3 tries with a decay time of 1 minute.

throttle could be defined in /project-root/laravel/app/Http/Kernel.php in the routeMiddleware array like so:
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,. The Laravel documentation explains this method here: https://laravel.com/docs/6.x/middleware#assigning-middleware-to-routes

use Trait ThrottlesLogins present in Illuminate\Foundation\Auth and override the 2 functions as mentioned below. I have tested it on Laravel 5.6 and working fine.

public function maxAttempts()
{
    //Lock out on 5th Login Attempt
    return 5;
}

public function decayMinutes()
{
    //Lock for 1 minute
    return 1;
}
Related