<?php
namespace App\Controller;
use Scheb\TwoFactorBundle\Security\TwoFactor\Provider\Google\GoogleAuthenticatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;
class SecurityController extends AbstractController
{
public function login(AuthenticationUtils $authenticationUtils, GoogleAuthenticatorInterface $googleAuthenticatorInterface): Response
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('backend/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
/**
* @Route("/2fa/inProgress", name="2fa_in_progress")
*/
public function accessibleDuring2fa()
{
return new Response('This page is accessible during 2fa');
}
/**
* @Route("/admin/2fa/qr", name="admin_2fa_qr")
*/
public function qr2fa(GoogleAuthenticatorInterface $googleAuthenticatorInterface)
{
$user = $this->getUser();
if($user->getGoogleAuthenticatorSecret() != null && $user->getGoogleAuthenticatorSecret() != ""){
return $this->redirectToRoute('admin_homepage');
}
else{
$entityManager = $this->getDoctrine()->getManager();
$secret = $googleAuthenticatorInterface->generateSecret();
$user->setGoogleAuthenticatorSecret($secret);
$entityManager->persist($user);
$entityManager->flush();
// GENERAR QR
$qrCodeContent = $googleAuthenticatorInterface->getQRContent($user);
$qrImage = Builder::create()
->writer(new PngWriter())
->writerOptions([])
->data($qrCodeContent)
->encoding(new Encoding('UTF-8'))
->size(200)
->margin(0)
->build();
return $this->render('backend/2fa_qr.html.twig', ["qrImage" => $qrImage->getDataUri()]);
}
}
}