Home > Net >  Lock out user for given amount of time
Lock out user for given amount of time

Time:09-28

I have the following custom login controller;

But I want to lock the user out for an hour, at the moment it just locks them out for about 60 seconds or so, is this possible?

public function login(Request $request)
{
     if (RateLimiter::tooManyAttempts(optional($request->user())->id ?: $request->ip(), 5)) {
          return response()->json([
               'message' => 'Account locked for an hour'
          ]);
     }

     $credentials = request(['email', 'password']);

     if (! Auth::attempt($credentials)) {
          RateLimiter::hit(optional($request->user())->id ?: $request->ip());

          return response()->json([
               'status_code' => 401,
               'message' => 'Unauthorized',
          ]);
     } else {

          RateLimiter::clear(optional($request->user())->id ?: $request->ip());

          return response()->json([
               'status_code' => 200,
               'message' => 'Welcome',
          ]);
     }
}

CodePudding user response:

The rate limiting documentation seems very centered around the idea of a specific number of requests allowed per minute.

Digging into the API articles for RateLimiter there is a $decaySeconds parameter after the which can be specified on the attempt() and hit() functions. This value comes in after the parameter you are using as your identification key to rate limit. In your case $credentials

So you should be able to do something like this...

//Second parameter of attempt is how long until the attempt 'decays' from the system.
if (! Auth::attempt($credentials, 5, null, 3600)) {
          RateLimiter::hit(optional($request->user())->id ?: $request->ip());

          return response()->json([
               'status_code' => 401,
               'message' => 'Unauthorized',
          ]);
}

Notably the rate limiter just appears to a pre-configured set of functions using the Cache API in Laravel.

So alternatively you could build your own rate limited methodology as well by using Cache::put() and Cache::has() methods with custom logic and expiry times that are tailored to whatever you're trying to limit.

CodePudding user response:

You can set timeout in seconds in Authcontroller where default timeout is 60 seconds.

=> Step to implement custom locking time functionality in Laravel :

1. Go to App\Http\Controllers\Auth\AuthController.php.

2. protected $maxLoginAttempts = 10; // Amount of bad attempts user can make
protected $lockoutTime = 300; // Time for which user is going to be blocked in seconds

With help of these variables, you can do whatever you need.

https://i.stack.imgur.com/31F6D.png

  • Related