salehhashemi/laravel-otp-manager

v1.5.2 2024-09-08 13:11 UTC

README

Laravel OTP 管理器

Latest Version on Packagist Total Downloads GitHub Actions GitHub Actions codecov PHPStan PHP Version Require

Header Image

OtpManager 类负责发送和验证一次性密码 (OTP)。它提供了一套全面的方法来生成、发送、验证和管理 OTP,并且与 Laravel 缓存系统集成,以限制 OTP 的发送并提供一个跟踪 OTP 请求的安全层。

功能

  • 主要功能
    • 生成 OTP 码
    • 通过手机号码发送 OTP
    • 带内置节流的重新发送 OTP
    • 验证 OTP 码
    • 跟踪 OTP 请求
  • 安全
    • OTP 生成尝试的速率限制 (OtpRateLimiter 中间件)
    • 多次验证失败后 OTP 无效
    • 验证成功后自动删除 OTP 码
  • 配置
    • 自定义速率限制阈值、最大允许尝试次数和自动删除
  • 灵活性
    • 支持使用枚举的多重 OTP 类型
    • 可定制的手机号码验证

需求

  • PHP: ^8.1
  • Laravel 框架: ^9

安装

要安装此包,您可以运行以下命令

composer require salehhashemi/laravel-otp-manager

用法

发送 OTP

use Salehhashemi\OtpManager\Facade\OtpManager;

$sentOtp = OtpManager::send("1234567890");

重新发送 OTP

如果尝试在等待时间过期前重新发送 OTP,则 sendAndRetryCheck 方法将抛出 ValidationException

$sentOtp = OtpManager::sendAndRetryCheck("1234567890");

验证 OTP

$isVerified = OtpManager::verify("1234567890", 123456, "uuid-string");

删除验证码

$isDeleted = OtpManager::deleteVerifyCode("1234567890");

处理和监听 OtpPrepared 事件

OtpManager 包在生成新的 OTP 时会触发 OtpPrepared 事件。您可以监听此事件并执行自定义逻辑,例如通过短信或电子邮件发送 OTP。

以下是设置事件监听器的步骤

步骤 1: 注册事件和监听器

首先,您需要将 OtpPrepared 事件及其相应的监听器注册到您的 EventServiceProvider 文件中,通常位于 app/Providers/EventServiceProvider.php,并将事件和监听器添加到 $listen 数组中。

protected $listen = [
    \Salehhashemi\OtpManager\Events\OtpPrepared::class => [
        \App\Listeners\SendOtpNotification::class,
    ],
];

步骤 2: 创建监听器

如果监听器不存在,您可以使用以下 Artisan 命令生成它

php artisan make:listener SendOtpNotification

步骤 3: 实现监听器

现在打开生成的 SendOtpNotification 监听器文件,通常位于 app/Listeners/。您将看到一个 handle 方法,您可以在其中添加发送 OTP 的自定义逻辑。

以下是一个示例实现

use Salehhashemi\OtpManager\Events\OtpPrepared;

class SendOtpNotification
{
    public function handle(OtpPrepared $event)
    {
        $mobile = $event->mobile;
        $otpCode = $event->code;

        // Send the OTP code to the mobile number
        // You can use your preferred SMS service here.
    }
}

步骤 4: 测试事件监听器

设置监听器后,通过 OtpManager 包生成新的 OTP,以确保 OtpPrepared 事件被捕获并且相应的监听器逻辑被执行。

就是这样!您已在 OtpManager 包中成功设置了 OtpPrepared 事件的监听器。

使用枚举定义 OTP 类型

您可以利用枚举来定义您的 OTP 类型。枚举提供了一种更易于表达的方式来管理不同类别的 OTP。

如何定义 OTP 枚举

use Salehhashemi\OtpManager\Contracts\OtpTypeInterface;

enum MyOtpEnum: string implements OtpTypeInterface
{
    case SIGNUP = 'signup';
    case RESET_PASSWORD = 'reset_password';

    public function identifier(): string
    {
        return $this->value;
    }
}

用法

定义枚举后,您可以像使用其他 OTP 类型一样使用它

OtpManager::send('1234567890', MyOtpEnum::SIGNUP);
OtpManager::verify('1234567890', $otpCode, $trackingCode, MyOtpEnum::SIGNUP);

配置

要发布配置文件,请运行以下命令

php artisan vendor:publish --provider="Salehhashemi\OtpManager\OtpManagerServiceProvider" --tag="config"

要发布语言文件,请运行

php artisan vendor:publish --provider="Salehhashemi\OtpManager\OtpManagerServiceProvider" --tag="lang"

发布后,请确保清除配置缓存以应用您的更改

php artisan config:clear

然后,您可以在 config/otp.php 中调整 waiting_time、code_min 和 code_max

中间件保护

奥tpManager 包包含内置中间件(OtpRateLimiter),用于保护您的应用路由免受过多的 OTP 请求。这有助于防止潜在滥用。

应用中间件

注册中间件:\Salehhashemi\OtpManager\Middleware\OtpRateLimiter::class 添加到您的 app\Http\Kernel.php 文件中的 middlewareAliases 数组。

分配中间件到路由:您可以将它应用于特定的路由或路由组,您想在其中实施速率限制。

示例

Route::middleware('otp-rate-limiter')->group(function () {
    // Routes that require OTP rate limiting go here
});

自定义手机号码验证

该包包含默认的手机号码验证器,但您可以使用自己的。

以下是操作方法

  1. 首先创建自定义验证器类,创建一个实现 MobileValidatorInterface 的类。此接口期望您定义一个验证方法。
    use Salehhashemi\OtpManager\Contracts\MobileValidatorInterface;
    
    class CustomMobileValidator implements MobileValidatorInterface
    {
        public function validate(string $mobile): void
        {
            // Your validation logic here
        }
    }
  2. 更新配置,接下来,打开您的 OTP 配置文件,将 mobile_validation_class 选项更新为使用您的自定义验证器类
    'mobile_validation_class' => CustomMobileValidator::class,

异常

  • 如果手机号码为空,将抛出 \InvalidArgumentException
  • 对于一般异常,如 OTP 生成失败,将抛出 \Exception
  • 对于速率限制,将抛出 \Illuminate\Validation\ValidationException
  • 对于被限制的请求,将抛出 \Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException

Docker 设置

此项目使用 Docker 进行本地开发和测试。在继续之前,请确保您的系统已安装 Docker 和 Docker Compose。

构建 Docker 镜像

docker-compose build

启动服务

docker-compose up -d

要访问 PHP 容器,您可以使用

docker-compose exec php bash

测试

composer test

变更日志

有关最近更改的更多信息,请参阅 CHANGELOG

贡献

有关详细信息,请参阅 CONTRIBUTING

致谢

许可

MIT 许可证(MIT)。有关更多信息,请参阅 许可文件