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

2Fa Email Laravel Package

scheb/2fa-email

Adds email-based two-factor authentication to Symfony apps using Scheb’s 2FA bundle. Generates and delivers one-time codes via email, supports custom mailers/templates, code validation and trusted devices, for an extra login security layer.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require scheb/2fa-email
    

    Ensure scheb/2fa-bundle is already installed (this package extends it).

  2. Configuration Add to your config/2fa.php:

    'providers' => [
        'email' => [
            'enabled' => true,
            'template' => 'emails.two_factor_auth_code', // Customize in resources/views
        ],
    ],
    
  3. First Use Case Trigger 2FA for a user:

    use Scheb\TwoFactorBundle\Security\TwoFactorAuthenticatorInterface;
    
    $authenticator = $this->get('scheb_two_factor.authenticator');
    $code = $authenticator->generateCode(); // Generates a 6-digit code
    $authenticator->sendEmailCode($user, $code); // Sends email with code
    
  4. Verify Code

    $isValid = $authenticator->checkCode($user, $inputCode);
    

Implementation Patterns

Workflow: User Registration/First Login

  1. Enable 2FA for New Users

    // In User registration controller
    $user->setTwoFactorEnabled(true);
    $user->save();
    
    $authenticator->sendEmailCode($user, $authenticator->generateCode());
    
  2. Post-Registration Redirect

    return redirect()->route('verify.2fa.email')->with('user', $user);
    
  3. Verification Blade Template

    <form method="POST" action="{{ route('verify.2fa.email') }}">
        @csrf
        <input type="text" name="code" placeholder="6-digit code">
        <button type="submit">Verify</button>
    </form>
    

Integration with Laravel Auth

  1. Custom Guard Extension Extend SchebTwoFactorGuard in config/guard.php:

    'guards' => [
        'web' => [
            'provider' => 'users',
            'authenticator' => 'scheb_two_factor.authenticator',
        ],
    ],
    
  2. Middleware for Protected Routes

    use Scheb\TwoFactorBundle\Security\TwoFactorMiddleware;
    
    protected $middleware = [
        TwoFactorMiddleware::class,
    ];
    
  3. Session-Based Code Storage Store the code in the user’s session after generation:

    $request->session()->put('2fa_email_code', $code);
    

Customization

  1. Override Email Template Publish the template:

    php artisan vendor:publish --tag=scheb-two-factor-email-templates
    

    Modify resources/views/vendor/scheb_two_factor/email/code.txt.twig.

  2. Dynamic Recipient Logic Override Scheb\TwoFactorBundle\Security\EmailAuthenticator:

    public function sendCode(UserInterface $user, $code)
    {
        Mail::to($this->getCustomEmail($user))->send(new TwoFactorEmail($code));
    }
    
    protected function getCustomEmail(User $user)
    {
        return $user->alternateEmail ?: $user->email;
    }
    

Gotchas and Tips

Pitfalls

  1. Rate Limiting

    • Default email sending may trigger spam filters. Use a queue:
      $authenticator->sendEmailCode($user, $code)->onQueue('emails');
      
  2. Session Expiry

    • Codes expire after 10 minutes by default. Reset the session if users report issues:
      $request->session()->forget(['2fa_email_code', '2fa_email_attempts']);
      
  3. Testing

    • Mock Scheb\TwoFactorBundle\Security\EmailAuthenticator in tests:
      $this->partialMock(EmailAuthenticator::class, ['sendCode']);
      
  4. Configuration Overrides

    • Ensure scheb/2fa-bundle is configured before scheb/2fa-email in config/2fa.php to avoid provider conflicts.

Debugging Tips

  1. Check Logs Enable debug mode in config/2fa.php:

    'debug' => env('APP_DEBUG', false),
    

    Logs will appear in storage/logs/laravel.log.

  2. Verify Email Dispatch Use Laravel’s mail preview:

    php artisan mail:preview Scheb\TwoFactorBundle\Mail\TwoFactorEmail --code=123456
    
  3. Common Issues

    • Codes not sending? Check MAIL_DRIVER in .env (must be smtp, mailgun, etc.).
    • Codes invalid? Ensure user_id is correctly stored in the session.

Extension Points

  1. Custom Providers Extend Scheb\TwoFactorBundle\Security\Provider\EmailProvider to add:

    • Attachment support.
    • Localization for email templates.
  2. Event Listeners Listen for scheb.two_factor.code.sent and scheb.two_factor.code.verified:

    Event::listen('scheb.two_factor.code.sent', function ($user, $code) {
        // Log or notify admins
    });
    
  3. API Integration For SPAs, return the code via API:

    Route::post('/2fa/email/send', function (Request $request) {
        $authenticator = app(EmailAuthenticator::class);
        $code = $authenticator->generateCode();
        $authenticator->sendCode($request->user(), $code);
        return response()->json(['status' => 'sent']);
    });
    
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit