PHP code example of dakataa / 2fa

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

    

dakataa / 2fa example snippets




// ....

#[Route('/2fa')]
class TwoFactorController extends AbstractController
{
    #[Route('/form', name: 'auth_2fa_form')]
    public function form(AuthenticationUtils $authenticationUtils): Response
    {
        return $this->render('auth/2fa/form.html.twig', [
            'error' => $authenticationUtils->getLastAuthenticationError(),
        ]);
    }

    #[Route('/check', name: 'auth_2fa_check')]
    public function check(): Response
    {
        throw new Exception('Please setup  2FA key "check_path" in configuration.');
    }

	#[IsGranted('ROLE_USER')]
    #[Route('/setup/{authenticator}', name: "auth_2fa_setup")]
    public function setup(#[CurrentUser] UserInterface $user, TwoFactorAuthenticatorProvider $twoFactorAuthenticatorProvider, string $authenticator = null): Response
    {
        if($authenticator) {
            $entity = $twoFactorAuthenticatorProvider->setupProvider($user, $authenticator);
            $twoFactorAuthenticatorProvider->getAuthenticator($user)?->dispatch($entity);

            return match($authenticator) {
                'otp' =>  $this->render('auth/2fa/setup_otp.html.twig', [
                    'parameters' => $entity->getTwoFactorParameters()
                ]),
                default => new RedirectResponse($this->generateUrl('auth_2fa_form'))
            };
        }

        return $this->render('auth/2fa/setup.html.twig');
    }
}



// ...

class TwoFactorEventHandler
{

    public function __construct(private readonly CacheItemPoolInterface $twoFactorTemporaryStorage)
    {

    }

    #[AsEventListener(event: TwoFactorEntityInvokingEvent::class)]
    public function onTwoFactorEntityInvokingEvent(TwoFactorEntityInvokingEvent $event): void
    {
        $user = $event->getUser();
        $cacheKey = sha1($user->getUserIdentifier());
        if(!$this->twoFactorTemporaryStorage->hasItem($cacheKey)) {
            return;
        }

        $data = $this->twoFactorTemporaryStorage->getItem($cacheKey)->get();
        if(empty($data) || !is_array($data)) {
            return;
        }

        [
            'authenticator' => $authenticator,
            'parameters' => $parameters,
            'active' => $active
        ] = $data + [
            'authenticator' => null,
            'parameters' => null,
            'active' => false
        ];


        if(!$authenticator) {
            return;
        }

        $entity = new TwoFactorAuthenticatorEntity($user->getUserIdentifier(), $authenticator, $parameters, $active);

        $event->setEntity($entity);
    }

    #[AsEventListener(event: TwoFactorSetupEvent::class)]
    public function onTwoFactorSetupEvent(TwoFactorSetupEvent $event): void
    {
        $cacheKey = sha1($event->getUser()->getUserIdentifier());
        $cacheItem = $this->twoFactorTemporaryStorage->getItem($cacheKey);
        $cacheItem->set([
            'authenticator' => $event->getEntity()->getTwoFactorAuthenticator(),
            'parameters' => $event->getEntity()->getTwoFactorParameters(),
            'active' => false
        ]);
        $this->twoFactorTemporaryStorage->save($cacheItem);
    }

    #[AsEventListener(event: TwoFactorActivateEvent::class)]
    public function onTwoFactorActivateEvent(TwoFactorActivateEvent $event): void
    {
        $cacheKey = sha1($event->getUser()->getUserIdentifier());
        $cacheItem = $this->twoFactorTemporaryStorage->getItem($cacheKey);
        if(empty($data = $cacheItem->get())) {
            return;
        }

        $data = [...$data, 'active' => true];
        $cacheItem->set($data);
        $this->twoFactorTemporaryStorage->save($cacheItem);

        $event->setResponse(new RedirectResponse('/'));
    }

}



namespace App\Component\MessageHandler;

use Dakataa\Security\TwoFactorAuthenticator\Notification\EmailNotification;
use Dakataa\Security\TwoFactorAuthenticator\Notification\SmsNotification;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

class TwoFactorMessageHandler extends AbstractController
{
    #[AsMessageHandler]
    public function smsNotificationHandler(SmsNotification $message)
    {
       // Send SMS with code
       // $message->getCode();
    }

    #[AsMessageHandler]
    public function emailNotificationHandler(EmailNotification $message)
    {
       // Send Email with code
       // $message->getCode();
    }

}