morcen / laravel-otp-generator
为您的 Laravel 应用生成 OTP
v1.1.0
2022-03-15 16:55 UTC
Requires
- php: ^8.0
- laravel/framework: ^8.0 | ^9.0
- spatie/laravel-package-tools: ^1.9.2
Requires (Dev)
- nunomaduro/collision: ^6.0
- nunomaduro/larastan: ^2.0.1
- orchestra/testbench: ^7.0
- pestphp/pest: ^1.21
- pestphp/pest-plugin-laravel: ^1.1
- pestphp/pest-plugin-mock: ^1.0
- phpstan/extension-installer: ^1.1
- phpstan/phpstan-deprecation-rules: ^1.0
- phpstan/phpstan-phpunit: ^1.0
- phpunit/phpunit: ^9.5
- spatie/laravel-ray: ^1.26
This package is auto-updated.
Last update: 2024-09-10 01:04:55 UTC
README
为您的 Laravel 应用生成 OTP
此包需要 Laravel >= 8.x。
安装
-
通过 composer 安装包
composer require morcen/laravel-otp-generator
-
使用以下命令发布配置文件
php artisan vendor:publish --tag="otp-generator-config"打开
config/otp.php并更新以下内容identifier- 这将是此包用于在数据库中查询 OTP 记录的内容set- 这定义了用于代码的字符。可能的值有numbers- 从零到九(0 到 9)lowercase- 英文字母从a到zuppercase- 英文字母从A到Zothers- 默认为空字符串。您可以将任何其他希望作为 OTP 代码一部分的字符放入其中。all- 使用所有字母和数字,包括others选项中的字符。这是默认选项。
lifetime- 定义 OTP 有效期。默认为15分钟。length- 定义 OTP 的默认长度。尽管可以在调用generate或generateFor方法时简单地覆盖此值。默认长度为4。encrypt- 如果设置为true,则将在返回的对象中具有附加属性hash。如果与generateFor()方法一起使用,则将在数据库中保存的值将是加密值。自v1.1.0起可用。alg- 这将是用于 OTP 代码的散列算法。这仅在encrypt设置为true时生效。有效选项是sha1和md5。自v1.1.0起可用。
-
使用以下命令发布迁移
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'); });
-
使用以下命令运行迁移
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)。请参阅许可证文件以获取更多信息。