SuperSeller3000/src/Infrastructure/Http/Controller/TotpSetupController.php

73 lines
2.1 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace App\Infrastructure\Http\Controller;
use App\Domain\Auth\Repository\UserRepositoryInterface;
use App\Domain\Auth\User;
use Scheb\TwoFactorBundle\Security\TwoFactor\Provider\Totp\TotpAuthenticatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[Route('/totp', name: 'totp_')]
#[IsGranted('ROLE_USER')]
final class TotpSetupController extends AbstractController
{
public function __construct(
private readonly TotpAuthenticatorInterface $totpAuthenticator,
private readonly UserRepositoryInterface $userRepository,
) {
}
#[Route('/setup', name: 'setup', methods: ['GET'])]
public function setup(): Response
{
$user = $this->getUser();
\assert($user instanceof User);
if ($user->isTotpAuthenticationEnabled()) {
return $this->redirectToRoute('totp_manage');
}
$secret = $this->totpAuthenticator->generateSecret();
$user->setTotpSecret($secret);
$this->userRepository->save($user);
$qrCodeUrl = $this->totpAuthenticator->getQRContent($user);
return $this->render('totp/setup.html.twig', [
'secret' => $secret,
'qr_code_url' => $qrCodeUrl,
]);
}
#[Route('/manage', name: 'manage', methods: ['GET'])]
public function manage(): Response
{
$user = $this->getUser();
\assert($user instanceof User);
return $this->render('totp/manage.html.twig', [
'totp_enabled' => $user->isTotpAuthenticationEnabled(),
]);
}
#[Route('/disable', name: 'disable', methods: ['POST'])]
public function disable(): Response
{
$user = $this->getUser();
\assert($user instanceof User);
$user->setTotpSecret(null);
$this->userRepository->save($user);
$this->addFlash('success', 'Two-factor authentication has been disabled.');
return $this->redirectToRoute('totp_manage');
}
}