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

Filament 2Fa Laravel Package

tfsthiagobr98/filament-2fa

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require tfsthiagobr98/filament-2fa
    php artisan vendor:publish --tag="filament-2fa-migrations"
    php artisan migrate
    

    Ensure filament >= 2.10.40 is installed.

  2. User Model Setup: Add the trait to your user model:

    use TFSThiagoBR98\FilamentTwoFactor\TwoFactorAuthenticatable;
    class User extends Authenticatable { use TwoFactorAuthenticatable; }
    
  3. Configure Filament: Update config/filament.php to use the custom login page:

    "auth" => [
        "pages" => [
            "login" => \TFSThiagoBR98\FilamentTwoFactor\Http\Livewire\Auth\Login::class,
        ],
    ],
    
  4. First Use Case:

    • A user logs in via Filament’s login page.
    • If 2FA is enabled, they’ll be prompted for a TOTP code (e.g., from Google Authenticator).
    • If disabled, they bypass 2FA entirely.

Implementation Patterns

Core Workflows

  1. Login Flow:

    • The package replaces Filament’s default login with a 2FA-aware version.
    • After successful credentials, it checks for 2FA enrollment (hasTwoFactorEnabled()).
    • Redirects to a TOTP input form if enabled.
  2. 2FA Setup:

    • Use <livewire:filament-two-factor-form> in a profile page (e.g., Jetstream theme).
    • The component handles:
      • QR code generation for TOTP apps.
      • Backup code provisioning.
      • Recovery code storage (encrypted in two_factor_backup_codes).
    • Example integration:
      <livewire:filament-two-factor-form
          :user="$user"
          wire:ignore
      />
      
  3. Recovery Codes:

    • Generate and display recovery codes via:
      $recoveryCodes = $user->generateTwoFactorRecoveryCodes();
      
    • Store them securely (e.g., encrypted in the DB or hashed).
  4. Middleware Integration:

    • Protect routes with TwoFactorAuthenticatable trait methods:
      if ($user->hasTwoFactorEnabled()) {
          $this->middleware('two-factor.auth');
      }
      

Advanced Patterns

  • Custom TOTP Providers: Extend the TwoFactorAuthenticatable trait to support alternative providers (e.g., YubiKey):

    use PragmaRX\Google2FA\Google2FA as Google2FA;
    use PragmaRX\Google2FA\TwoFactorAuth;
    
    protected function twoFactor(): TwoFactorAuth {
        return new TwoFactorAuth(new Google2FA());
    }
    
  • Conditional 2FA: Skip 2FA for specific roles/IPs by overriding shouldUseTwoFactor():

    public function shouldUseTwoFactor(): bool {
        return $this->role === 'admin' && !request()->ip()->isLocal();
    }
    
  • Event Hooks: Listen for 2FA events (e.g., TwoFactorEnabled, TwoFactorDisabled) to log or notify:

    event(new TwoFactorEnabled($user));
    

Gotchas and Tips

Pitfalls

  1. Migration Conflicts:

    • The two_factor_secret and two_factor_backup_codes columns may conflict with existing migrations.
    • Fix: Run php artisan vendor:publish --tag="filament-2fa-migrations" before other migrations.
  2. Caching Issues:

    • TOTP secrets are cached; clear cache after setup:
      php artisan cache:clear
      php artisan config:clear
      
  3. Backup Code Security:

    • Recovery codes are stored unencrypted by default. Override getTwoFactorBackupCodesAttribute() to encrypt them:
      public function getTwoFactorBackupCodesAttribute($value) {
          return encrypt($value);
      }
      
  4. Time Sync:

    • TOTP relies on device time. Users must enable auto-time sync in their OS or use a TOTP app.
  5. Filament Version Lock:

    • The package requires filament >= 2.10.40. Downgrading may break functionality.

Debugging Tips

  • Verify TOTP Codes: Use the verifyTwoFactorCode() method to debug:

    $valid = $user->verifyTwoFactorCode('123456');
    // Logs: `TwoFactorCodeVerified` or `TwoFactorCodeInvalid`
    
  • Check Enrollment: Ensure hasTwoFactorEnabled() returns true after setup. If not, check:

    • The two_factor_secret column is populated.
    • No silent exceptions during QR generation.
  • Livewire Errors: Wrap <livewire:filament-two-factor-form> in a @error block:

    @error('two_factor_code')
        <div class="text-red-500">{{ $message }}</div>
    @enderror
    

Extension Points

  1. Custom Views: Publish and override views:

    php artisan vendor:publish --tag="filament-2fa-views"
    

    Modify resources/views/vendor/filament-2fa/... to change UI (e.g., QR size, button labels).

  2. Email Notifications: Extend the TwoFactorEnabled event to send emails:

    TwoFactorEnabled::listen(function ($user) {
        Notification::route('mail', $user->email)
            ->notify(new TwoFactorEnabledNotification());
    });
    
  3. Rate Limiting: Add rate limiting to the TOTP endpoint in app/Http/Middleware/ThrottleNodes.php:

    protected function limits() {
        return [
            'two-factor' => ['max', 5, 1], // 5 attempts per minute
        ];
    }
    
  4. Multi-Factor Logic: Combine with other auth packages (e.g., laravel-fortify) by extending the Login controller:

    public function authenticate() {
        if ($this->attemptLogin()) {
            if ($this->user->hasTwoFactorEnabled()) {
                return redirect()->route('two-factor.verify');
            }
            return redirect()->intended();
        }
    }
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope