morcen/laravel-otp-generator

为您的 Laravel 应用生成 OTP

v1.1.0 2022-03-15 16:55 UTC

README

为您的 Laravel 应用生成 OTP

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

此包需要 Laravel >= 8.x。

安装

  1. 通过 composer 安装包

    composer require morcen/laravel-otp-generator
  2. 使用以下命令发布配置文件

    php artisan vendor:publish --tag="otp-generator-config"

    打开 config/otp.php 并更新以下内容

    • identifier - 这将是此包用于在数据库中查询 OTP 记录的内容
    • set - 这定义了用于代码的字符。可能的值有
      • numbers - 从零到九(0 到 9)
      • lowercase - 英文字母从 az
      • uppercase - 英文字母从 AZ
      • others- 默认为空字符串。您可以将任何其他希望作为 OTP 代码一部分的字符放入其中。
      • all - 使用所有字母和数字,包括 others 选项中的字符。这是默认选项。
    • lifetime - 定义 OTP 有效期。默认为 15 分钟。
    • length - 定义 OTP 的默认长度。尽管可以在调用 generategenerateFor 方法时简单地覆盖此值。默认长度为 4
    • encrypt - 如果设置为 true,则将在返回的对象中具有附加属性 hash。如果与 generateFor() 方法一起使用,则将在数据库中保存的值将是加密值。自 v1.1.0 起可用。
    • alg - 这将是用于 OTP 代码的散列算法。这仅在 encrypt 设置为 true 时生效。有效选项是 sha1md5。自 v1.1.0 起可用。
  3. 使用以下命令发布迁移

    php artisan vendor:publish --tag="otp-generator-migrations"

    并更新它以包括前面步骤中提到的 identifier 字段。例如,如果您有

    'identifier' => 'email'

    在您的 config/otp.php 中,您必须在创建的迁移文件中添加此行

    Schema::create('otps', function (Blueprint $table) {
        $table->id();
        $table->string('email');  // <-- this is the line added to match the `identifier`
        $table->string('code');
        $table->unsignedInteger('expiration');
        $table->timestamp('created_at');
    });
  4. 使用以下命令运行迁移

     php artisan migrate

用法

要生成一个之后可以验证的 OTP,请使用 generatedFor() 方法。它接受两个参数

  • $identifierValue(必需)- 将与 identifier 进行匹配的值
  • $length(可选)- 要使用的代码长度。如果未提供,它将使用在 config/otp.php 中设置的默认 length 选项。

例如,我们想要为电子邮件 abcd@example.com 创建一个 OTP

use Morcen\LaravelOtpGenerator\Facades\Otp;

$otp = Otp::generateFor('abcd@example.com');

$otp 返回 OTP 对象,例如

{
    "email": "abcd@example.com",
    "code": "028988",
    "hash": "6120a26f84406f452c1b27509505093ba4aa263d",
    "expiration": 1647363156
}

然后,为了验证,请使用 validateFor 方法,接受 $identifierValue 和 OTP 作为参数并返回 bool

Otp::validateFor('abcd@example.com', '028988'); // returns `true`

*注意:如果 encrypt 设置为 true,则 OTP 对象中仅出现 hash 属性。

仅生成和接收 OTP 代码

use Morcen\LaravelOtpGenerator\Facades\Otp;

$otp = Otp::generate();

$otp 只返回 OTP 对象,如下所示

{
    "code": "234198",
    "hash": "858edae3093a5b6f5b7812cff2e2e369da0a2290"
}

*注意:如果 encrypt 设置为 true,则 OTP 对象中仅出现 hash 属性。

要覆盖 OTP 的默认 length,请传递长度作为参数。例如,要生成一个 10 个字符长的 OTP

$otp = Otp::generateFor('abcd@example.com', 10); 

$otp = Otp::generate(10); 

测试

composer test

变更日志

请参阅 CHANGELOG 了解最近更改的更多信息。

贡献

请参阅 CONTRIBUTING 了解详细信息。

安全漏洞

请查看我们的安全策略,了解如何报告安全漏洞。

致谢

许可证

MIT许可证(MIT)。请参阅许可证文件以获取更多信息。