PHP code example of assghard / laravel-2fa

1. Go to this page and download the library: Download assghard/laravel-2fa library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

assghard / laravel-2fa example snippets


'providers' => [
    TwoFactorVerificationServiceProvider::class,
]

config/2fa.php #2FA config

# migrations
migrations/create_user_2fa_codes_table.php
migrations/add_phone_number_field_to_users_table.php

# translations: add or delete languages you don't need
lang/en/2fa.php
lang/pl/2fa.php


/*
 * =========================================
 * Basic usage
 * =========================================
 */

use Assghard\Laravel2fa\Traits\UserTwoFactorVerificationTrait; # Add trait in use section
use Assghard\Laravel2fa\Enums\TwoFactorVerificationMethodsEnum; # available 2FA methods Enum
...

class User extends Authenticatable implements MustVerifyEmail
{
    use UserTwoFactorVerificationTrait; // Use trait for 2FA
    ...

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [ # Add fillable fields
        ...
        'phone_number', # only if you are going to send 2FA codes via SMS message
    ];

use Assghard\Laravel2fa\Services\TwoFactorVerificationService;
use Assghard\Laravel2fa\Enums\TwoFactorVerificationMethodsEnum;
...
class AuthenticatedSessionController extends Controller
{
    ...

    $sent = (new TwoFactorVerificationService())->sendUserTwoFactorVerificationCode($user, $verificationMethodFromEnum);
    dd($sent);
    // And do everything you want after sending code


    Route::middleware('auth')->group(function () {
        ...
        Route::group(['prefix' => '2fa'], function () {
            Route::get('verify', [TwoFactroVerificationAuthController::class, 'verify'])->name('2fa.verify');
            Route::post('verify', [TwoFactroVerificationAuthController::class, 'confirm'])->name('2fa.verify.confirm')->middleware('throttle:2fa_verify_confirm');
            Route::get('resend', [TwoFactroVerificationAuthController::class, 'resend'])->name('2fa.resend-code');
    });

    // 2fa_verify_confirm is a name of throttle and middleware
    RateLimiter::for('2fa_verify_confirm', function (Request $request) {
        return Limit::perMinute(5)->by($request->user()?->id ?: $request->ip());
    });

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class User2faCodeVerified
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        // And do something like this or not :)
        // Database, session or other approach - the choice is yours

        $user = auth()->user();
        if ($user->two_factor_verification_codes()->count() > 0) {
            return redirect()->route('2fa.verify');
        }

/*
 * =========================================
 * NOT Basic usage (Example of customization)
 * =========================================
 */

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        ...
        'tfa_method' // 2FA method
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        ...
        'tfa_method' => TwoFactorVerificationMethodsEnum::class, // leverage enums for 2FA method casting
    ];

    /**
     * Enable 2FA for Users. After enabling this feature 2FA will be 2FA method
     * TwoFactorVerificationMethodsEnum::cases()
     */
    'default_method' => TwoFactorVerificationMethodsEnum::Email,

    /**
     * After successful login all user codes are deleting, so user will have limit reseted
     */
    'daily_user_codes_limit' => 25,

    /**
     * Single code valid time in minutes.
     * expires_at = now() + user_code_valid_time
     */
    'user_code_valid_time' => 10,

    'code' => [
        /**
         * Default 2FA code length
         */
        'length' => 6,
    
        /**
         * Default 2FA code length
         */
        'use_letters' => false,
    ],

    /**
     * SMS API config
     */
    'sms' => [
        /**
         * API token from https://www.smsapi.com/en
         */
        'api_token' => env('SMS_API_TOKEN', null),

        /**
         * Sender name
         */
        'name_from' => env('SMS_API_NAME_FORM', null),
    ],