Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel 2Fa Laravel Package

hydrat-agency/laravel-2fa

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require hydrat-agency/laravel-2fa
    php artisan vendor:publish --provider="HydratAgency\Laravel2FA\Laravel2FAServiceProvider"
    php artisan migrate
    
    • Publishes config (config/2fa.php) and creates the two_factor_tokens table.
  2. Enable for a User

    use HydratAgency\Laravel2FA\Facades\Laravel2FA;
    
    // Generate and send a 2FA token (e.g., via email/SMS)
    Laravel2FA::generateAndSendToken($user);
    
  3. First Use Case: Login Flow

    • Use the Laravel2FA::check() middleware in your Authenticate middleware group:
      $middleware->append(\HydratAgency\Laravel2FA\Middleware\CheckTwoFactor::class);
      
    • Redirect users to a 2FA verification page if triggered.

Implementation Patterns

Core Workflows

  1. Token Generation & Delivery

    • Default Channels: Email (via Notifiable) or SMS (via Nexmo/Vonage).
    • Custom Channels: Extend HydratAgency\Laravel2FA\Notifications\TwoFactorToken:
      class CustomTokenNotification extends TwoFactorToken {
          public function via($notifiable) {
              return ['slack', 'custom_webhook'];
          }
      }
      
    • Configure in config/2fa.php:
      'notification' => \App\Notifications\CustomTokenNotification::class,
      
  2. Conditional Checks

    • Skip 2FA for trusted devices/IPs via policies (e.g., TrustedDevicePolicy):
      use HydratAgency\Laravel2FA\Contracts\TwoFactorPolicy;
      
      class TrustedDevicePolicy implements TwoFactorPolicy {
          public function applies($user, $request) {
              return $request->ip() === $user->trusted_ip;
          }
      }
      
    • Register in config/2fa.php:
      'policies' => [
          \HydratAgency\Laravel2FA\Policies\TrustedDevicePolicy::class,
          \App\Policies\TrustedDevicePolicy::class,
      ],
      
  3. Manual Verification

    • Force 2FA check mid-flow:
      if (Laravel2FA::shouldCheck($user, $request)) {
          $token = Laravel2FA::generateAndSendToken($user);
          return redirect()->route('verify.2fa')->with('token', $token);
      }
      
  4. Token Validation

    • Verify a submitted token:
      if (Laravel2FA::verifyToken($user, $request->input('token'))) {
          // Grant access or proceed
      }
      

Integration Tips

  • Laravel Fortify/Passport: Use the CheckTwoFactor middleware after authentication but before session creation.
  • APIs: Combine with ThrottleRequests to rate-limit 2FA attempts:
    Route::middleware(['throttle:6,1'])->group(function () {
        Route::post('/verify', [TwoFactorController::class, 'verify']);
    });
    
  • Admin Panels: Exclude 2FA for super-admins via a custom policy:
    public function applies($user, $request) {
        return !$user->is_super_admin;
    }
    

Gotchas and Tips

Pitfalls

  1. Token Expiry

    • Tokens expire after 10 minutes by default (config/2fa.php token_lifetime).
    • Fix: Extend lifetime for sensitive operations:
      Laravel2FA::setTokenLifetime($user, 30); // 30 minutes
      
  2. Database Locks

    • Concurrent token generation/validation may cause race conditions.
    • Fix: Use database transactions:
      DB::transaction(function () use ($user) {
          Laravel2FA::generateAndSendToken($user);
      });
      
  3. Notification Failures

    • If the notification channel fails (e.g., SMTP down), tokens are still generated but not delivered.
    • Fix: Log failures and implement a fallback (e.g., in-app toast notification):
      try {
          Laravel2FA::generateAndSendToken($user);
      } catch (\Exception $e) {
          Log::error("2FA Notification Failed: " . $e->getMessage());
          session()->flash('2fa_fallback', true);
      }
      
  4. Middleware Order

    • Placing CheckTwoFactor before Authenticate will block all unauthenticated users.
    • Fix: Ensure it runs after authentication:
      $middleware->append(\App\Http\Middleware\Authenticate::class);
      $middleware->append(\HydratAgency\Laravel2FA\Middleware\CheckTwoFactor::class);
      

Debugging

  • Token Storage: Check the two_factor_tokens table for stale entries:
    SELECT * FROM two_factor_tokens WHERE expires_at < NOW();
    
  • Policy Debugging: Temporarily disable policies to isolate issues:
    config(['2fa.policies' => []]);
    
  • Event Listeners: Listen for TwoFactorGenerated events to debug token delivery:
    Laravel2FA::listen(function ($user, $token) {
        Log::debug("Token for {$user->email}: {$token}");
    });
    

Extension Points

  1. Custom Drivers

    • Store tokens in Redis instead of the database by implementing HydratAgency\Laravel2FA\Contracts\TokenDriver:
      class RedisTokenDriver implements TokenDriver {
          public function store($userId, $token, $expiresAt) {
              Redis::set("2fa:{$userId}", $token, 'EX', $expiresAt->timestamp);
          }
          // Implement other methods...
      }
      
    • Register in config/2fa.php:
      'driver' => \App\Services\RedisTokenDriver::class,
      
  2. Dynamic Policies

    • Fetch trusted IPs from an external service:
      class DynamicTrustedPolicy implements TwoFactorPolicy {
          public function applies($user, $request) {
              $trustedIps = $this->fetchTrustedIpsFromAPI($user);
              return in_array($request->ip(), $trustedIps);
          }
      }
      
  3. Backup Codes

    • Generate and store backup codes (like Google Authenticator):
      $codes = Laravel2FA::generateBackupCodes($user, 5); // 5 backup codes
      Laravel2FA::storeBackupCodes($user, $codes);
      

Config Quirks

  • Default Token Length: Hardcoded to 6 digits in TokenGenerator. Override by extending the class.
  • Notification Retries: No built-in retry logic for failed notifications. Implement via Laravel’s ShouldQueue:
    class TwoFactorToken implements ShouldQueue {
        public function handle() {
            // Retry on failure
            $this->notify($this->notifiable);
        }
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle