mikailfaruqali / guardian
Modern Laravel two-factor authentication package with dual authentication system: email-based 2FA for master users and Google Authenticator for regular users. Features beautiful Tailwind CSS UI, multilingual support (English/Kurdish/Arabic) with RTL layout, configurable logo/fonts, rate limiting, an
Requires
- php: >=7.4
- illuminate/contracts: >=5.0
- pragmarx/google2fa: ^8.0
- simplesoftwareio/simple-qrcode: ^4.2
Requires (Dev)
- driftingly/rector-laravel: ^2.0
- laravel/pint: ^1.14
- orchestra/testbench: ^8.22 || ^9.0
README
Guardian is a powerful and elegant Laravel security package that provides dual two-factor authentication (2FA) with a modern Tailwind CSS interface and comprehensive multilingual support. It offers email-based 2FA for master users and Google Authenticator for regular users, ensuring flexible security for different user types.
โจ Key Features
๐ Dual Authentication System
- Master Password Authentication โ Email-based 2FA codes
- Regular Users โ Google Authenticator 2FA
- Automatic detection of authentication method
- Session-based verification management
- Rate limiting with configurable throttling
๐จ Modern UI & Customization
- Tailwind CSS design system with responsive layout
- Configurable logo and custom fonts support
- RTL layout support for Arabic and Kurdish languages
- Beautiful gradients and modern design elements
- Customizable branding through configuration
๐ Comprehensive Internationalization
- English (en) - Primary language
- Kurdish (ku) - Right-to-left (RTL) support
- Arabic (ar) - Right-to-left (RTL) support
- Dynamic language detection and direction switching
- Localized error messages and UI text
๐ง Advanced Security Features
- QR Code generation for Google Authenticator setup
- Rate limiting on verification attempts
- Middleware protection for routes
- Configurable routes and security settings
- Session management and verification tracking
๐ฆ Installation
1. Install via Composer
composer require mikailfaruqali/guardian
2. Publish Configuration
php artisan vendor:publish --tag=snawbar-guardian-config
3. Publish Views (Optional)
php artisan vendor:publish --tag=snawbar-guardian-views
4. Publish Translations (Optional)
php artisan vendor:publish --tag=snawbar-guardian-lang
5. Database Migration
Add these columns to your users
table:
Schema::table('users', function (Blueprint $table) { $table->string('google2fa_secret')->nullable(); $table->boolean('google2fa_verified')->default(false); $table->string('two_factor_code')->nullable(); });
Or create a new migration:
php artisan make:migration add_guardian_columns_to_users_table
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddGuardianColumnsToUsersTable extends Migration { public function up() { Schema::table('users', function (Blueprint $table) { $table->string('google2fa_secret')->nullable(); $table->boolean('google2fa_verified')->default(false); $table->string('two_factor_code')->nullable(); }); } public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn(['google2fa_secret', 'google2fa_verified', 'two_factor_code']); }); } }
โ๏ธ Configuration
Basic Configuration (config/guardian.php
)
<?php return [ // Enable/Disable Guardian 2FA 'enabled' => env('GUARDIAN_ENABLED', true), // Master password for email-based 2FA 'master-password' => env('GUARDIAN_MASTER_PASSWORD', ''), // Email recipients for master users 'master-emails' => [ 'admin@example.com', 'security@example.com', ], // UI Customization 'logo-path' => env('GUARDIAN_LOGO_PATH', ''), 'font-path' => env('GUARDIAN_FONT_PATH', ''), // Database column mapping 'columns' => [ 'google2fa_secret' => 'google2fa_secret', 'google2fa_verified' => 'google2fa_verified', 'two_factor_code' => 'two_factor_code', ], // Routes to skip Guardian protection 'skipped-routes' => [ 'login', ], ];
Environment Variables (.env
)
# Guardian Configuration GUARDIAN_ENABLED=true GUARDIAN_MASTER_PASSWORD="$2y$10$your_hashed_password_here" # UI Customization GUARDIAN_LOGO_PATH="/images/logo.png" GUARDIAN_FONT_PATH="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" # Email Configuration MAIL_MAILER=smtp MAIL_HOST=smtp.gmail.com MAIL_PORT=587 MAIL_USERNAME=your-email@gmail.com MAIL_PASSWORD=your-app-password MAIL_ENCRYPTION=tls MAIL_FROM_ADDRESS=your-email@gmail.com MAIL_FROM_NAME="Your App Name"
Generate Master Password Hash
// In Laravel Tinker php artisan tinker // Generate password hash bcrypt('your-master-password') // or Hash::make('your-master-password')
๐ Usage
Authentication Flow
For Master Users:
- User logs in with master password
- Guardian detects master password and redirects to email verification
- Sends 6-digit code to configured emails
- User enters code to complete authentication
For Regular Users:
- User logs in normally
- Guardian redirects to Google Authenticator verification
- First-time users see QR code setup
- User enters 6-digit code from authenticator app
Automatic Middleware Registration
Guardian automatically registers middleware that protects all authenticated routes. The middleware:
- Detects login attempts and captures master passwords
- Sets language direction based on locale (RTL for Arabic/Kurdish)
- Redirects to appropriate 2FA method based on user type
- Handles rate limiting with configurable throttling
- Manages session verification state
Route Protection
All authenticated routes are automatically protected except:
- Routes in
skipped-routes
configuration - Guardian's own routes (
guardian.*
) - Login and authentication routes
๐ Package Structure
guardian/
โโโ config/
โ โโโ guardian.php # Main configuration file
โโโ lang/ # Language files
โ โโโ en/
โ โ โโโ guardian.php # English translations
โ โโโ ku/
โ โ โโโ guardian.php # Kurdish translations (RTL)
โ โโโ ar/
โ โโโ guardian.php # Arabic translations (RTL)
โโโ routes/
โ โโโ web.php # Package routes with rate limiting
โโโ src/
โ โโโ Components/
โ โ โโโ Guardian.php # Core Guardian component
โ โโโ Controllers/
โ โ โโโ GuardianController.php # Main controller with validation
โ โโโ Mail/
โ โ โโโ CodeMail.php # Email template class
โ โโโ Middleware/
โ โ โโโ GuardianEnforcer.php # Authentication middleware
โ โโโ GuardianServiceProvider.php # Service provider
โโโ views/
โโโ layout.blade.php # Base Tailwind layout with RTL support
โโโ authenticator.blade.php # Google Authenticator page
โโโ email.blade.php # Email verification page
โโโ mail/
โโโ code.blade.php # Email template
๐จ UI Components & Customization
Modern Tailwind CSS Design
Guardian features a beautiful, responsive interface built with Tailwind CSS:
- Responsive design optimized for mobile and desktop
- Modern gradients and clean styling
- Accessible forms with proper focus states
- Loading states and smooth transitions
- RTL support for Arabic and Kurdish languages
Logo Customization
// In your .env file GUARDIAN_LOGO_PATH="/images/my-logo.png" // Or in config/guardian.php 'logo-path' => '/images/my-logo.png',
Font Customization
// Google Fonts GUARDIAN_FONT_PATH="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;600&display=swap" // Local font file GUARDIAN_FONT_PATH="/fonts/custom-font.woff2"
๐ Internationalization
Supported Languages
Language | Code | Direction | Status |
---|---|---|---|
English | en |
LTR | โ Complete |
Kurdish | ku |
RTL | โ Complete |
Arabic | ar |
RTL | โ Complete |
Language Keys
All UI text is translatable through language files:
// lang/en/guardian.php return [ 'login' => 'Login', 'resend' => 'Resend Code', 'enter-email-code' => 'Enter the 6-digit code from your email', 'invalid-code' => 'Sorry, the code is incorrect!', 'install-app' => 'Install Google Authenticator', 'enter-auth-code' => 'Enter the 6-digit code from your app', 'email-sent' => 'Code sent to your email successfully!', ];
RTL Layout Support
Guardian automatically detects RTL languages and adjusts:
- Text direction and layout flow
- Font selection optimized for each language
- UI components properly aligned for RTL reading
๐ง Email Configuration
Gmail Setup (Recommended)
- Enable 2-Factor Authentication on your Google account
- Generate App Password:
- Go to Google Account Settings
- Security โ 2-Step Verification
- App Passwords โ Generate new password
- Update .env file:
MAIL_MAILER=smtp MAIL_HOST=smtp.gmail.com MAIL_PORT=587 MAIL_USERNAME=your-email@gmail.com MAIL_PASSWORD=your-16-digit-app-password MAIL_ENCRYPTION=tls MAIL_FROM_ADDRESS=your-email@gmail.com MAIL_FROM_NAME="Your App Name"
Email Template Features
- HTML format with clean, professional design
- Gmail-optimized for reliable inbox delivery
- Responsive layout for mobile email clients
- Security notices and proper branding
- Localized content in multiple languages
๐ Security Features
Rate Limiting
Guardian includes built-in rate limiting on all verification endpoints:
// Email sending: 3 attempts per minute Route::post('/email/send', [GuardianController::class, 'sendEmail']) ->middleware('throttle:3,1'); // Code verification: 5 attempts per minute Route::post('/email/verify', [GuardianController::class, 'verifyEmail']) ->middleware('throttle:5,1');
Security Best Practices
- Bcrypt hashing for master passwords
- Session-based verification tracking
- CSRF protection on all forms
- Input validation with custom error messages
- Automatic middleware protection
๐ ๏ธ Advanced Usage
Custom Validation Messages
// In your controller private function validateCode(Request $request): void { $request->validate([ 'code' => 'required|string|size:6', ], [ 'code.*' => __('snawbar-guardian::guardian.invalid-code'), ]); }
Extending the Middleware
// Create your own middleware extending GuardianEnforcer class CustomGuardianEnforcer extends GuardianEnforcer { protected function shouldBypass(Request $request): bool { // Add custom bypass logic return parent::shouldBypass($request) || $this->isCustomRoute($request); } }
๐งช Testing
Feature Testing
<?php namespace Tests\Feature; use Tests\TestCase; use Illuminate\Foundation\Testing\RefreshDatabase; class GuardianTest extends TestCase { use RefreshDatabase; public function test_guardian_redirects_unverified_users() { $user = User::factory()->create(); $response = $this->actingAs($user)->get('/dashboard'); $response->assertRedirect(route('guardian.authenticator')); } public function test_master_user_redirected_to_email_verification() { // Test master password detection and email flow } public function test_rate_limiting_on_verification_attempts() { // Test throttling middleware } }
๐ Troubleshooting
Common Issues
Email Not Delivered
Problem: Gmail refuses to deliver emails Solution:
- Use Gmail App Password (not regular password)
- Ensure proper SMTP configuration
- Check spam folder
- Verify sender domain reputation
QR Code Not Displaying
Problem: QR code fails to generate Solution:
- Install required packages:
simplesoftwareio/simple-qrcode
- Check PHP GD extension is installed
- Verify internet connection for external QR services
RTL Languages Not Working
Problem: Arabic/Kurdish text displays incorrectly Solution:
- Ensure UTF-8 encoding in language files
- Check CSS direction attribute in layout
- Verify proper font support for the language
๐ Performance
Optimization Tips
- Cache configuration: Guardian config is cached by Laravel
- Database indexing: Add indexes to Guardian columns
- Rate limiting: Prevents abuse and improves performance
- Session storage: Use Redis for better session performance
Database Indexes
Schema::table('users', function (Blueprint $table) { $table->index('google2fa_secret'); $table->index('google2fa_verified'); $table->index('two_factor_code'); });
๐ค Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Setup
git clone https://github.com/mikailfaruqali/guardian.git
cd guardian
composer install
Code Style
We follow PSR-12 coding standards. Run the formatter:
vendor/bin/pint
๐ License
The MIT License (MIT). Please see License File for more information.
๐ Credits
- Snawbar - Package author and maintainer
- PragmaRX Google2FA - Google Authenticator implementation
- SimpleSoftwareIO QrCode - QR code generation
- Tailwind CSS - Modern utility-first CSS framework
- Laravel - The amazing framework that makes it all possible
๐ Support
- GitHub Issues: Report bugs or request features
- Email: alanfaruq85@gmail.com
- Documentation: Full documentation
Guardian - Protecting your Laravel applications with elegant two-factor authentication. ๐ก๏ธ