litepie/otp
Composer 安装命令:
composer require litepie/otp
包简介
A comprehensive Laravel package for generating, signing and managing OTP codes with multiple channels support
README 文档
README
A comprehensive Laravel package for generating, signing and managing OTP (One-Time Password) codes with multiple channels support.
📋 Requirements
- PHP 8.2 or higher
- Laravel 10.0, 11.0, or 12.0
🚀 Features
- ✅ Secure OTP Generation - Generate cryptographically secure OTP codes
- ✅ Digital Signing - Sign OTP codes for enhanced security and verification
- ✅ Multiple Delivery Channels - Email, SMS, Database, and custom channels
- ✅ Flexible Configuration - Customizable length, format, and expiration
- ✅ Rate Limiting - Built-in protection against abuse
- ✅ Multiple OTP Types - Login, email verification, password reset, 2FA, etc.
- ✅ Event System - Complete lifecycle events for monitoring and logging
- ✅ Queue Support - Background processing for sending OTPs
- ✅ Auto-cleanup - Automatic removal of expired OTPs
- ✅ Laravel 12 Ready - Full compatibility with the latest Laravel versions
- ✅ Production Ready - Thoroughly tested and optimized for production use
📦 Installation
You can install the package via Composer:
composer require litepie/otp
Publish Configuration
Publish the configuration file:
php artisan vendor:publish --provider="Litepie\Otp\OtpServiceProvider" --tag="config"
Run Migrations
Run the migrations to create the OTPs table:
php artisan migrate
Set Up Automatic Cleanup (Optional)
Add the following to your app/Console/Kernel.php file to automatically clean up expired OTPs:
protected function schedule(Schedule $schedule) { $schedule->command('otp:cleanup')->daily(); }
🔧 Configuration
The configuration file config/otp.php allows you to customize:
- Default OTP Settings - Length, format, expiration, channels
- OTP Types - Specific settings for different use cases
- Rate Limiting - Prevent abuse with configurable limits
- Digital Signing - Secure OTP verification
- Channel Configuration - Email, SMS, and custom channel settings
- Automatic Cleanup - Keep your database clean
Environment Variables
Add these to your .env file:
# OTP Signing Secret (defaults to APP_KEY) OTP_SIGNING_SECRET=your-secret-key # SMS Provider Configuration OTP_SMS_PROVIDER=log # Options: log, nexmo, twilio # Nexmo/Vonage NEXMO_KEY=your-nexmo-key NEXMO_SECRET=your-nexmo-secret NEXMO_FROM=YourApp # Twilio TWILIO_SID=your-twilio-sid TWILIO_TOKEN=your-twilio-token TWILIO_FROM=your-twilio-number
📖 Usage
Quick Start
use Litepie\Otp\Facades\Otp; // Generate and send OTP $otp = Otp::generate() ->for('user@example.com') ->type('login') ->send(); // Verify OTP $isValid = Otp::verify('123456', 'user@example.com', 'login'); if ($isValid) { // OTP is valid, proceed with authentication return response()->json(['message' => 'Login successful']); }
Advanced Usage
// Custom OTP with specific settings $otp = Otp::generate() ->for('user@example.com') ->type('password_reset') ->length(8) // 8 digits ->format('alphanumeric') // Letters and numbers ->expiresIn(900) // 15 minutes ->via(['email', 'sms']) // Multiple channels ->with(['user_id' => 123]) // Additional data ->send(); // Check if OTP exists before generating new one if (!Otp::exists('user@example.com', 'login')) { $otp = Otp::generate() ->for('user@example.com') ->type('login') ->send(); } // Invalidate existing OTP Otp::invalidate('user@example.com', 'login');
Exception Handling
use Litepie\Otp\Exceptions\TooManyAttemptsException; use Litepie\Otp\Exceptions\RateLimitExceededException; try { $isValid = Otp::verify($code, $email, 'login'); } catch (TooManyAttemptsException $e) { return response()->json(['error' => 'Too many failed attempts'], 429); } catch (RateLimitExceededException $e) { return response()->json(['error' => 'Rate limit exceeded'], 429); }
🎯 OTP Types
The package supports multiple OTP types with individual configurations:
Built-in Types
| Type | Use Case | Default Length | Default Expiry |
|---|---|---|---|
login |
User authentication | 6 digits | 5 minutes |
email_verification |
Email verification | 6 digits | 10 minutes |
password_reset |
Password reset | 8 characters | 15 minutes |
two_factor |
2FA authentication | 6 digits | 3 minutes |
phone_verification |
Phone verification | 6 digits | 5 minutes |
Custom Types
Define custom OTP types in your configuration:
// config/otp.php 'types' => [ 'transaction_verify' => [ 'length' => 8, 'format' => 'alphanumeric', 'expires_in' => 600, // 10 minutes 'max_attempts' => 3, 'channels' => ['email', 'sms'], 'rate_limit' => [ 'max_attempts' => 2, 'decay_minutes' => 30, ], ], ],
📡 Delivery Channels
Email Channel
Sends OTP via email using Laravel's notification system or traditional mail.
Otp::generate() ->for('user@example.com') ->via('email') ->send();
SMS Channel
Send OTPs via SMS using various providers:
Otp::generate() ->for('+1234567890') ->via('sms') ->send();
Supported SMS Providers:
- Log (for testing)
- Nexmo/Vonage
- Twilio
- Custom providers (extensible)
Database Channel
Store OTP in database for manual retrieval:
Otp::generate() ->for('user@example.com') ->via('database') ->send(); // Retrieve from database $otpRecord = \Litepie\Otp\Otp::where('identifier', 'user@example.com') ->where('type', 'login') ->valid() ->first();
Multiple Channels
Send via multiple channels simultaneously:
Otp::generate() ->for('user@example.com') ->via(['email', 'sms', 'database']) ->send();
Custom Channels
Create custom delivery channels:
use Litepie\Otp\Contracts\OtpChannelInterface; class SlackChannel implements OtpChannelInterface { public function send(string $identifier, string $code, array $data = []): bool { // Implementation for Slack delivery return true; } public function canHandle(string $identifier): bool { return str_starts_with($identifier, '@slack:'); } } // Register the custom channel Otp::extend('slack', function () { return new SlackChannel(); });
📊 Events
The package fires comprehensive events for monitoring and logging:
Available Events
OtpGenerated- When an OTP is generatedOtpSent- When an OTP is sent via a channelOtpVerified- When an OTP is successfully verifiedOtpFailed- When OTP verification fails
Event Listeners
// In EventServiceProvider protected $listen = [ \Litepie\Otp\Events\OtpGenerated::class => [ \App\Listeners\LogOtpGenerated::class, ], \Litepie\Otp\Events\OtpVerified::class => [ \App\Listeners\LogOtpVerified::class, \App\Listeners\SendWelcomeEmail::class, ], \Litepie\Otp\Events\OtpFailed::class => [ \App\Listeners\LogFailedOtpAttempt::class, ], ];
Example Listener
class LogOtpGenerated { public function handle(\Litepie\Otp\Events\OtpGenerated $event) { Log::info('OTP generated', [ 'identifier' => $event->otp->identifier, 'type' => $event->otp->type, 'expires_at' => $event->otp->expires_at, ]); } }
🛠️ Artisan Commands
Cleanup Expired OTPs
# Clean up expired OTPs (default: 7 days) php artisan otp:cleanup # Clean up OTPs older than specific days php artisan otp:cleanup --days=3 # Force cleanup without confirmation php artisan otp:cleanup --force
🔒 Security Features
- Digital Signing - All OTPs are digitally signed using HMAC-SHA256
- Rate Limiting - Configurable rate limiting per identifier and type
- Secure Generation - Cryptographically secure random code generation
- Attempt Tracking - Track and limit verification attempts
- Automatic Cleanup - Remove expired OTPs automatically
- Timing Attack Protection - Use
hash_equals()for secure comparisons
🧪 Testing
Running Tests
# Run all tests composer test # Run tests with coverage composer test-coverage # Run specific test vendor/bin/phpunit tests/Unit/OtpTest.php
Test Example
use Litepie\Otp\Facades\Otp; use Illuminate\Support\Facades\Mail; public function test_otp_generation_and_verification() { Mail::fake(); // Generate OTP $otp = Otp::generate() ->for('test@example.com') ->type('login') ->send(); // Verify OTP $this->assertTrue( Otp::verify($otp->code, 'test@example.com', 'login') ); // Assert mail was sent Mail::assertSent(\Litepie\Otp\Notifications\OtpNotification::class); }
📚 Documentation
- Examples - Comprehensive usage examples
- Contributing - How to contribute
- Security - Security policy
- Changelog - Version history
🤝 Contributing
We welcome contributions! Please see CONTRIBUTING.md for details.
Development Setup
git clone https://github.com/litepie/otp.git cd otp composer install composer test
🔐 Security
If you discover a security vulnerability, please send an email to security@litepie.com. All security vulnerabilities will be promptly addressed.
📄 License
The MIT License (MIT). Please see License File for more information.
💖 Support
- ⭐ Star this repo if you find it helpful
- 🐛 Report issues on GitHub Issues
- 💡 Request features via GitHub Discussions
- 📧 Contact us at support@litepie.com
Made with ❤️ by Litepie
litepie/otp 适用场景与选型建议
litepie/otp 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 10 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 08 月 30 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「security」 「Authentication」 「email」 「sms」 「two-factor」 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 litepie/otp 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 litepie/otp 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 litepie/otp 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Automatically logs-in users if they are already authenticated by a remote source. (e.g. environment variable REMOTE_USER)
GraphQL authentication for your headless Craft CMS applications.
Provide a way to secure accesses to all routes of an symfony application.
Laravel middleware to restrict a site or specific routes using HTTP basic authentication
It's a barebone security class written on PHP
Email Toolkit Plugin for CakePHP
统计信息
- 总下载量: 10
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 23
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-08-30