PHP code example of inlayphp / two-factor-authentication

1. Go to this page and download the library: Download inlayphp/two-factor-authentication 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/ */

    

inlayphp / two-factor-authentication example snippets


use Illuminate\Foundation\Auth\User as Authenticatable;
use Inlay\TwoFactorAuthentication\Concerns\HasTwoFactorAuthentication;
use Inlay\TwoFactorAuthentication\Contracts\TwoFactorAuthenticatable;

final class User extends Authenticatable implements TwoFactorAuthenticatable
{
    use HasTwoFactorAuthentication;

    protected function casts(): array
    {
        return [
            'two_factor_confirmed_at' => 'datetime',
            'two_factor_recovery_codes' => 'array',
        ];
    }
}

use Laravel\Fortify\TwoFactorAuthenticatable as FortifyTwoFactorAuthenticatable;
use Inlay\TwoFactorAuthentication\Concerns\UsesFortifyTwoFactorAuthentication;
use Inlay\TwoFactorAuthentication\Contracts\TwoFactorAuthenticatable;

final class User extends Authenticatable implements TwoFactorAuthenticatable
{
    use FortifyTwoFactorAuthenticatable;
    use UsesFortifyTwoFactorAuthentication;
}

use Inlay\TwoFactorAuthentication\TwoFactorManager;

$enrollment = app(TwoFactorManager::class)->beginEnrollment(
    auth()->user(),
    auth()->user()->email,
);

return response()->json([
    'secret' => $enrollment->secret,
    'otpauth_uri' => $enrollment->otpauthUri,
    'recovery_codes' => $enrollment->recoveryCodes,
]);

if (! app(TwoFactorManager::class)->confirmEnrollment($user, $request->string('code')->toString())) {
    return back()->withErrors(['code' => 'The authenticator code is invalid.']);
}

use Inlay\TwoFactorAuthentication\Contracts\TwoFactorQrCodeRenderer;

$this->app->bind(TwoFactorQrCodeRenderer::class, fn (): TwoFactorQrCodeRenderer => new MyQrRenderer);

use Inlay\Panel;
use Inlay\TwoFactorAuthentication\TwoFactorAuthenticationPlugin;
use Inlay\TwoFactorAuthentication\TwoFactorLoginStep;

public function panel(Panel $panel): Panel
{
    return $panel
        ->id('admin')
        ->path('admin')
        ->plugin(TwoFactorAuthenticationPlugin::make())
        ->loginStep(TwoFactorLoginStep::class);
}

use Inlay\TwoFactorAuthentication\Fortify\FortifyChallengeBridge;

public function boot(): void
{
    FortifyChallengeBridge::register(
        action: route('two-factor.login.store'),
    );
}

use Inlay\TwoFactorAuthentication\Fortify\FortifySettingsBridge;

public function boot(): void
{
    FortifyChallengeBridge::register();
    FortifySettingsBridge::register(
        path: 'settings/two-factor',
        guard: 'web',
    );
}
bash
./vendor/bin/pest --compact tests/TwoFactorAuthenticationTest.php