How to configure users ban for more maxAttempts in login?

296 views Asked by At

I work in Laravel 7

I adjust loginController as needed; maxAttempts and decayMinutes

public function maxAttempts()
{
        return General::first()->max_attempts;
}

public function decayMinutes()
{
        return General::first()->decay_minutes;
}

How to ban users for more than maxAttempts

example => maxAttempts = 4

I want ban user for 5 failed attempts

$user->is_block = true
2

There are 2 answers

0
Ali On BEST ANSWER

I tested it and it was right.

  • First of all create two event listeners in your EventServiceProvider. SuccessfulLogin and FailedLogin
protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
        'Illuminate\Auth\Events\Login' => [
            'App\Listeners\SuccessfulLogin',
        ],

        'Illuminate\Auth\Events\Failed' => [
            'App\Listeners\FailedLogin',
        ],
    ];
  • in SuccessfulLogin :
public function handle(Login $event)
    {
        
        $event->user->user_last_login_date = Carbon::now();
        $event->user->unsuccessful_login_count = 0;
        $event->user->save();

    }
  • in FailedLogin :
$event->user->unsuccessful_login_count += 1 ;
        $unsuccessful_count =   General::first()->max_attempts;

        if ($event->user->unsuccessful_login_count == $unsuccessful_count ) {
            $event->user->three_attempt_timestamp = Carbon::now()->toDateString();
        }
        if ($event->user->unsuccessful_login_count > $unsuccessful_count ) {
            $event->user->is_block = 1;
        }

        $event->user->save();
1
Lajos Arpad On

You will need to create a column for users which would count their unsuccessful login attempts. At every unsuccessful attempt you would increment this value and block the user if a certain limit has reached.

If the login has been successful, then set the counter to 0.