mewkhaleel/laravel-otp-mongodb

一个简单的用于生成和验证一次性密码(OTP)的包

dev-master 2022-09-03 11:36 UTC

This package is auto-updated.

Last update: 2024-09-30 01:41:09 UTC


README

简介 🖖

这是一个简单的用于生成和验证一次性密码(OTP)的包。这通常用于身份验证的实现。

感谢 https://github.com/jenssegers/laravel-mongodb

原始 https://github.com/ichtrojan/laravel-otp 感谢你,老兄 <3

安装 💽

通过composer安装

composer require mewkhaleel/laravel-otp-mongodb

将服务提供者添加到 config/app.php 文件中

<?php
   /*
    |--------------------------------------------------------------------------
    | Autoloaded Service Providers
    |--------------------------------------------------------------------------
    |
    | The service providers listed here will be automatically loaded on the
    | request to your application. Feel free to add your own services to
    | this array to grant expanded functionality to your applications.
    |
    */

    'providers' => [
        ...
        mewkhaleel\Otp\OtpServiceProvider::class,
    ];
...

将别名添加到 config/app.php 文件中

<?php

   /*
    |--------------------------------------------------------------------------
    | Class Aliases
    |--------------------------------------------------------------------------
    |
    | This array of class aliases will be registered when this application
    | is started. However, feel free to register as many as you wish as
    | the aliases are "lazy" loaded so they don't hinder performance.
    |
    */

    'aliases' => [
        ...
        'Otp' => mewkhaleel\Otp\Otp::class,
    ];
...

运行迁移

php artisan migrate

使用 🧨

注意
响应以对象的形式返回。您可以使用箭头操作符(->)访问其属性

生成OTP

<?php

Otp::generate(string $identifier, int $digits = 4, int $validity = 10)
  • $identifier: 将与OTP关联的身份。
  • $digit (可选 | 默认 = 4): 要生成的数字数量,可以是4、5或6。
  • $validity (可选 | 默认 = 10): OTP的有效期(分钟)。

示例

<?php

$otp = Otp::generate('michael@okoh.co.uk', 6, 15);

这将生成一个六位数的OTP,有效期为15分钟,成功的响应将是

{
  "status": true,
  "token": "282581",
  "message": "OTP generated"
}

验证OTP

<?php

Otp::validate(string $identifier, string $token)
  • $identifier: 与OTP关联的身份。
  • $token: 与身份关联的令牌。

示例

<?php

$otp = Otp::validate('michael@okoh.co.uk', '282581');

响应

成功时

{
  "status": true,
  "message": "OTP is valid"
}

不存在

{
  "status": false,
  "message": "OTP does not exist"
}

无效*

{
  "status": false,
  "message": "OTP is not valid"
}

已过期

{
  "status": false,
  "message": "OTP Expired"
}

删除过期的令牌

您可以通过运行以下artisan命令来删除过期的令牌

php artisan otp:clean

您还可以将此artisan命令添加到 app/Console/Kernel.php 中,以在计划的时间自动清理

<?php

protected function schedule(Schedule $schedule)
{
    $schedule->command('otp:clean')->daily();
}

贡献

如果您发现此包有任何问题或建议,请帮忙。我并不完美。