buckhamduffy/laravel-two-factor

This is my package laravel-two-factor

v0.1.8 2024-04-30 03:25 UTC

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

An opinionated two factor authentication package for Laravel.

Installation

You can install the package via composer:

composer require buckhamduffy/laravel-two-factor

You can publish and run the migrations with:

php artisan vendor:publish --tag="two-factor-migrations"
php artisan migrate

You can publish the config file with:

php artisan vendor:publish --tag="two-factor-config"

This is the contents of the published config file:

return [
];

Optionally, you can publish the views using

php artisan vendor:publish --tag="two-factor-views"

Add the trait and interface to the user model

    use BuckhamDuffy\LaravelTwoFactor\Traits\HasTwoFactor;
    use BuckhamDuffy\LaravelTwoFactor\Interfaces\HasTwoFactorInterface;

    class User extends Model implements HasTwoFactorInterface {
        use HasTwoFactor;
    }

Add the middleware to your Kernel.php

    protected $middlewareAliases = [
        // ...
        '2fa' => \BuckhamDuffy\LaravelTwoFactor\Http\Middleware\TwoFactorMiddleware::class,
    ];
    Route::middleware('2fa')->group(function(){
        // Your routes here
    });

SMS (Not Implemented Yet)

When a code is requested via SMS, an event will be dispatched that you can listen for to send the SMS. You can listen for the TwoFactorCodeRequested event and send the SMS using your preferred SMS provider.

    use \BuckhamDuffy\LaravelTwoFactor\Events\TwoFactorCodeRequested;
    
    class EventProvider extends ServiceProvider {
        protected $listen = [
            // ...
            TwoFactorCodeRequested::class => [
                \App\Listeners\SendTwoFactorCode::class,
            ],
        ];
    }
    namespace App\Listeners;

    use BuckhamDuffy\LaravelTwoFactor\Events\TwoFactorCodeRequested;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Illuminate\Queue\InteractsWithQueue;

    class SendTwoFactorCode implements ShouldQueue
    {
        use InteractsWithQueue;

        public function handle(TwoFactorCodeRequested $event): void
        {
           $user = $event->getUser();
           
           $user->sendTwoFactorSms($event->getCode());
        }
    }

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.