machaven/track-attempts

跟踪并限制任何认证、OTP或任何其他类型的操作。

2.0.3 2020-11-21 22:18 UTC

This package is auto-updated.

Last update: 2024-09-12 14:52:28 UTC


README

一个方便的库,可以跟踪任何类型的操作并限制在一定时间范围内的尝试次数。

需要跟踪和限制的有用事物

  • 登录尝试。
  • 一次性密码(OTP)尝试。
  • 您想要限制或监控的其他任何事物。

特性

  • 跟踪您想要的任何度量,如电子邮件、用户名等。
  • 可配置的限制。
  • 多个后端驱动
    • Redis (Predis 客户端)
    • Laravel (缓存外观)

安装

如果与Laravel驱动一起使用

当与Laravel版本小于5.8一起使用时,使用1.x版本标签

composer require machaven/track-attempts:^1.0

当与Laravel版本5.8+一起使用时,使用2.x版本标签

composer require machaven/track-attempts:^2.0

如果使用predis驱动

composer require machaven/track-attempts:^2.0

类配置

最小配置

$config = ['driver' => 'predis', userIdentifier' => $username];
$attempts = (new \Machaven\TrackAttempts\TrackAttempts($config))->getDriver();

完整配置

$config = [
    'driver' => 'predis', // Driver to use ('predis' or 'laravel')
    'userIdentifier' => $username, // A variable with a unique identifier for the session/user
    'maxAttempts' => 3, // Max attempts limit
    'systemName' => 'my-website', // System Identifier used in cache key prefix.
    'ttlInMinutes' => 5, // Keep track of attempts in a five minute period.
    'actionName' => 'login', // The name of the action you are tracking.
    ];
$attempts = (new \Machaven\TrackAttempts\TrackAttempts($config))->getDriver();

上述配置将创建一个名为:my-website:login:$username的密钥。

Predis 驱动配置

Predis 驱动需要在项目根目录下的.env文件中配置redis设置。

示例 .env

REDIS_SCHEME=tcp
REDIS_HOST=localhost
REDIS_PASSWORD=
REDIS_PORT=6379
REDIS_DB=0
REDIS_PROFILE=3.2

用法

保持计数

>>> $attempts->increment();
=> true

获取计数

>>> $attempts->getCount();
=> 1

检查是否达到限制

>>> $attempts->isLimitReached();
=> false

清除所有尝试

>>> $attempts->clear();
=> true

检查计数过期前剩余时间(以秒为单位)

>>> $attempts->getTimeUntilExpired();
=> 188

增加尝试

>>> $attempts->increment();

使用增量跟踪和检查(例如最大尝试次数为3次)

>>> $attempts->incrementAndCheckLimit();
=> true
>>> $attempts->incrementAndCheckLimit();
=> true
>>> $attempts->incrementAndCheckLimit();
=> true
>>> $attempts->incrementAndCheckLimit();
=> false