Laravel:增加第二次登录尝试的时间 [英] Laravel : Increase time on second time login attempts

查看:70
本文介绍了Laravel:增加第二次登录尝试的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前有五次登录尝试将用户阻止1分钟,并且使用以下代码可以正常工作:

Currently five login attempts blocks user for 1 minute and its working fine with the following code :

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

我想要的是,当用户在第一次尝试后再次解除阻止时,在第二次尝试时,阻止时间应增加到3分钟.

我四处搜寻,但找不到任何东西,有什么办法吗?

I searched around, But could not found anything, Is there any way around it ?

推荐答案

我建议您尝试以下代码.请询问是否不清楚.

I would suggest you try the following code. Please ask if anything is unclear.

$minutes = 3;
$key = $this->throttleKey($request);
$rateLimiter = $this->limiter();

if ($this->hasTooManyLoginAttempts($request)) {

    $attempts = $rateLimiter->attempts($key); 
    if ($attempts > 1) {
        $attempts === 2 && $rateLimiter->clear($key);
        $this->decayMinutes = ($attempts - 1) * $minutes;
        $attempts === 2 && $this->incrementLoginAttempts($request);
        $this->incrementLoginAttempts($request);
    }

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

用于增量阻止的代码:

$minutes = 3;
$key = $this->throttleKey($request);
$rateLimiter = $this->limiter();

if ($this->hasTooManyLoginAttempts($request)) {

    $attempts = $rateLimiter->attempts($key);
    $rateLimiter->clear($key);
    $this->decayMinutes = $attempts === 1 ? 1 : ($attempts - 1) * $minutes;

    for ($i = 0; $i < $attempts; $i++) {
        $this->incrementLoginAttempts($request);
    }

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

使用缓存进行增量阻止的代码:

Code for incremental blocking with cache:

$minutes = 3;
$key = $this->throttleKey($request);
$rateLimiter = $this->limiter();

if ($this->hasTooManyLoginAttempts($request)) {

    $attempts = $rateLimiter->attempts($key);
    $rateLimiter->clear($key); // might have to add logic here

    $reflection = new \ReflectionClass($rateLimiter);
    $property = $reflection->getProperty('cache');
    $property->setAccessible(true);
    $cache = $property->getValue($rateLimiter);
    $reflectionMethod = new \ReflectionMethod($rateLimiter, 'availableAt');
    $reflectionMethod->setAccessible(true);

    $blockMinutes = $attempts === 1 ? 1 : $attempts > 1 ? ($attempts - 1) * $minutes : 1;
    $cache->add($key.':timer', $reflectionMethod->invoke($rateLimiter, $blockMinutes * 60), $blockMinutes);
    $added = $cache->add($key, 0, $blockMinutes);
    $hits = (int) $cache->increment($key, $attempts);
    if (! $added && $hits === 1) {
        $cache->put($key, 1, $blockMinutes);
    }

    $reflectionMethod->setAccessible(false);
    $property->setAccessible(false);

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

这篇关于Laravel:增加第二次登录尝试的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆