murkrow / simple-otp
此包最新版本(1.0.8)没有可用的许可证信息。
1.0.8
2024-05-28 09:48 UTC
Requires
README
此包提供了一种简单的方法来管理您的应用程序用户的单次密码(OTP)。此包包括在Laravel应用程序中为您的用户模型生成、验证和管理OTP的功能。
安装
要安装Simple OTP包,请运行以下命令
composer require murkrow/simple-otp
运行迁移
请记住运行迁移以创建otps
表。
php artisan migrate
(可选)发布供应商文件
您可以使用以下命令发布配置文件和迁移:
php artisan vendor:publish
使用方法
将特性添加到您的用户模型
要为您的用户模型启用OTP功能,请向模型添加HasOtps
特性。通常,这将是在您的User
模型中。
namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use Murkrow\Otp\Traits\HasOtps; class User extends Authenticatable { use HasOtps; // Your user model code here }
生成OTP
要生成OTP,请使用OtpBuilder
类。您可以自定义OTP长度、是否为字母数字、其过期时间以及将其与用户关联。
use Murkrow\Otp\Builders\OtpBuilder; $otp = (new OtpBuilder()) ->forUser($user) // User object ->length(6) // Length of the OTP ->alphaNumeric(true) // Alphanumeric or numeric ->tag('login') // Optional tag ->expiresInMinutes(30) // Expiration time in minutes ->create();
验证OTP
要验证OTP,请使用由HasOtps
特性提供的validateOtp
方法。
$user = User::find(1); // User object $isValid = $user->validateOtp($otp, 'login'); // OTP and optional tag if ($isValid) { // OTP is valid } else { // OTP is invalid }
验证并删除OTP
要在验证成功后验证并删除OTP,请使用validateAndRemoveOtp
方法。
$isValid = $user->validateAndRemoveOtp($otp, 'login'); // OTP and optional tag if ($isValid) { // OTP is valid and removed } else { // OTP is invalid }
示例
以下是如何为用户生成OTP、验证它并在成功验证后删除它的示例
use App\Models\User; use Murkrow\Otp\Builders\OtpBuilder; // Assume $user is an instance of the User model $user = User::find(1); // Generate an OTP $otpBuilder = new OtpBuilder(); $otp = $otpBuilder ->forUser($user) ->length(6) ->alphaNumeric(true) ->expiresInMinutes(30) ->create(); // Validate the OTP $isValid = $user->validateOtp($otp->code, 'login'); if ($isValid) { echo "OTP is valid!"; } else { echo "Invalid OTP!"; } // Validate and remove the OTP $isValidAndRemoved = $user->validateAndRemoveOtp($otp->code, 'login'); if ($isValidAndRemoved) { echo "OTP is valid and has been removed!"; } else { echo "Invalid OTP!"; }
配置
每个用户OTP的最大数量
默认情况下,一个用户一次可以有最多5个OTP。如果用户超过此限制,最旧的OTP将被删除。您可以通过在otp
配置文件中设置max_otps_per_user
配置值来更改此行为。
// config/otp.php max_otps_per_user' => 5,
许可证
此包是开源软件,许可证为GNU通用公共许可证v3.0。