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 Two Factor Authentication Laravel Package

stephenjude/filament-two-factor-authentication

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup Steps

  1. Install the Package

    composer require stephenjude/filament-two-factor-authentication
    

    Publish the migration and config:

    php artisan vendor:publish --provider="StephenJude\FilamentTwoFactorAuthentication\FilamentTwoFactorAuthenticationServiceProvider" --tag="migrations"
    php artisan vendor:publish --provider="StephenJude\FilamentTwoFactorAuthentication\FilamentTwoFactorAuthenticationServiceProvider" --tag="config"
    php artisan migrate
    
  2. Register the Plugin Add to app/Providers/Filament/AdminPanelProvider.php:

    public function panel(Panel $panel): Panel
    {
        return $panel
            ->plugins([
                \StephenJude\FilamentTwoFactorAuthentication\FilamentTwoFactorAuthenticationPlugin::make(),
            ]);
    }
    
  3. First Use Case: Enable 2FA for a User

    • Navigate to User Management in Filament.
    • Select a user and click "Enable Two-Factor Authentication" in the actions dropdown.
    • Follow the QR code setup for Google Authenticator or enable passkeys via the built-in UI.

Implementation Patterns

Core Workflows

  1. Enabling 2FA for New Users

    • Use the EnableTwoFactorAuthentication action in Filament’s user table.
    • Customize the action via the plugin’s configure() method:
      FilamentTwoFactorAuthenticationPlugin::make()
          ->enableForAllUsers() // Optional: Auto-enable for all users
          ->showOnNavigation()  // Optional: Add to Filament sidebar
      
  2. Passkey Authentication Flow

    • Users can register passkeys via the "Add Passkey" button in their profile.
    • Leverage the Passkey model events (created, verified) for custom logic:
      \StephenJude\FilamentTwoFactorAuthentication\Models\Passkey::created(function ($passkey) {
          // Log passkey creation or notify admins
      });
      
  3. Conditional 2FA Enforcement

    • Restrict access to admin panels based on 2FA status:
      public function check(): bool
      {
          return auth()->user()->hasTwoFactorEnabled();
      }
      
  4. Customizing the 2FA UI

    • Override the plugin’s views by publishing them:
      php artisan vendor:publish --tag="filament-two-factor-authentication-views"
      
    • Extend the TwoFactorAuthPage class to modify behavior:
      use StephenJude\FilamentTwoFactorAuthentication\Pages\TwoFactorAuthPage;
      
      class CustomTwoFactorAuthPage extends TwoFactorAuthPage
      {
          protected static ?string $navigationIcon = 'heroicon-o-shield-check';
          protected static string $navigationLabel = 'Custom 2FA';
      }
      
  5. Integrating with Laravel 13

    • Ensure your config/app.php includes Laravel 13’s updated service providers and aliases.
    • If using Filament 3.x, confirm compatibility with Laravel 13’s new features (e.g., app()->runningInConsole() changes):
      if (app()->runningInConsole()) {
          // Laravel 13-specific console logic
      }
      
  6. Integrating with Existing Auth Logic

    • Hook into the two-factor-authenticated event to trigger post-2FA actions:
      \StephenJude\FilamentTwoFactorAuthentication\Events\TwoFactorAuthenticated::listen(function ($user) {
          // Grant additional permissions or log the event
      });
      

Gotchas and Tips

Common Pitfalls

  1. Migration Conflicts

    • If using a custom users table, ensure the two_factor_secret and two_factor_recovery_codes columns exist. Override the migration:
      use StephenJude\FilamentTwoFactorAuthentication\Database\Migrations\CreateTwoFactorAuthenticationTables;
      
      class CustomMigration extends CreateTwoFactorAuthenticationTables
      {
          public function up()
          {
              $this->schema->table('users', function (Blueprint $table) {
                  $table->string('two_factor_secret')->nullable()->after('password');
                  $table->json('two_factor_recovery_codes')->nullable()->after('two_factor_secret');
              });
          }
      }
      
  2. Passkey Browser Support

    • Passkeys require modern browsers (Chrome 120+, Edge 120+, Safari 16.4+). Test thoroughly in staging with:
      if (!\StephenJude\FilamentTwoFactorAuthentication\Support\Passkey::isSupported()) {
          // Fallback to TOTP or notify users
      }
      
  3. Recovery Codes Management

    • Recovery codes are stored as JSON in the two_factor_recovery_codes column. To regenerate them:
      $user->regenerateTwoFactorRecoveryCodes();
      $user->save();
      
  4. Laravel 13 Compatibility

    • If upgrading from Laravel 12, ensure your bootstrap/app.php is updated to Laravel 13’s new structure:
      // bootstrap/app.php
      $app->bind(\Illuminate\Contracts\Http\Kernel::class, \App\Http\Kernel::class);
      
    • Update any custom service providers or middleware to use Laravel 13’s new container methods.
  5. Caching Issues

    • Clear Filament’s cache after enabling/disabling 2FA for a user:
      php artisan filament:cache:clear
      

Debugging Tips

  • Log 2FA Events: Enable debug logging in config/filament-two-factor-authentication.php:
    'debug' => env('APP_DEBUG', false),
    
  • Verify Secrets: Use the laravel-debugbar package to inspect the two_factor_secret during setup.
  • Test Recovery Codes: Manually trigger recovery code usage:
    $user->verifyTwoFactorRecoveryCode('123456'); // Replace with a valid code
    

Extension Points

  1. Custom Authenticator Providers

    • Extend the Authenticator interface to support additional providers (e.g., Authy):
      use StephenJude\FilamentTwoFactorAuthentication\Contracts\Authenticator;
      
      class AuthyAuthenticator implements Authenticator
      {
          public function verify($secret, $code): bool
          {
              // Custom Authy verification logic
          }
      }
      
    • Register the provider in config/filament-two-factor-authentication.php:
      'authenticators' => [
          'google' => \StephenJude\FilamentTwoFactorAuthentication\Authenticators\GoogleAuthenticator::class,
          'authy' => \App\Authenticators\AuthyAuthenticator::class,
      ],
      
  2. Webhook Events

    • Listen for 2FA-related events to integrate with third-party services:
      \StephenJude\FilamentTwoFactorAuthentication\Events\TwoFactorEnabled::listen(function ($user) {
          // Send Slack notification or update CRM
      });
      
  3. Rate Limiting

    • Customize rate limits for 2FA attempts in app/Providers/AppServiceProvider.php:
      use Illuminate\Support\Facades\RateLimiter;
      
      public function boot()
      {
          RateLimiter::for('two-factor-attempts', function ($request) {
              return Limit::perMinute(5)->by($request->user()->id);
          });
      }
      
  4. Laravel 13-Specific Features

    • Leverage Laravel 13’s new features like Model Macros or Improved Route Caching for enhanced 2FA logic:
      // Example: Adding a macro to the User model for 2FA checks
      \App\Models\User::macro('isTwoFactorVerified', function () {
          return $this->two_factor_confirmed_at !== null;
      });
      
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager