Part-DB.Part-DB-server/src/Controller/WebauthnKeyRegistrationController.php

60 lines
2 KiB
PHP
Raw Normal View History

<?php
namespace App\Controller;
2022-10-04 00:08:58 +02:00
use App\Entity\UserSystem\WebauthnKey;
use Doctrine\ORM\EntityManagerInterface;
use Jbtronics\TFAWebauthn\Services\TFAWebauthnRegistrationHelper;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
2022-10-04 00:08:58 +02:00
use function Symfony\Component\Translation\t;
class WebauthnKeyRegistrationController extends AbstractController
{
/**
* @Route("/webauthn/register", name="webauthn_register")
*/
2022-10-04 00:08:58 +02:00
public function register(Request $request, TFAWebauthnRegistrationHelper $registrationHelper, EntityManagerInterface $em)
{
//If form was submitted, check the auth response
if ($request->getMethod() === 'POST') {
$webauthnResponse = $request->request->get('_auth_code');
//Retrieve other data from the form, that you want to store with the key
$keyName = $request->request->get('keyName');
2022-10-04 00:08:58 +02:00
if (empty($keyName)) {
$keyName = 'Key ' . date('Y-m-d H:i:s');
}
//Check the response
2022-10-04 00:08:58 +02:00
try {
$new_key = $registrationHelper->checkRegistrationResponse($webauthnResponse);
} catch (\Exception $exception) {
$this->addFlash('error', t('tfa_u2f.add_key.registration_error'));
return $this->redirectToRoute('webauthn_register');
}
$keyEntity = WebauthnKey::fromRegistration($new_key);
$keyEntity->setName($keyName);
$keyEntity->setUser($this->getUser());
$em->persist($keyEntity);
$em->flush();
$this->addFlash('success', 'Key registered successfully');
2022-10-04 00:08:58 +02:00
return $this->redirectToRoute('user_settings');
}
return $this->render(
2022-10-04 00:08:58 +02:00
'Security/Webauthn/webauthn_register.html.twig',
[
'registrationRequest' => $registrationHelper->generateRegistrationRequestAsJSON(),
]
);
}
}