<?php
namespace App\Controller;
use App\Form\PasswordResetType;
use App\Model\User\Authtype\Authtype;
use App\Model\User\UserFacade;
use App\Repository\ResetPasswordHolderRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Contracts\Translation\TranslatorInterface;
class SecurityController extends AbstractController
{
public function __construct(private readonly EntityManagerInterface $entityManager)
{
}
#[Route(path: '/login/{authtype}', name: 'app_login')]
public function login(AuthenticationUtils $authenticationUtils, ?string $authtype = null): Response
{
if ($this->getUser()) {
return $this->redirectToRoute('dashboard');
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
$authtypes = $this->entityManager->getRepository(Authtype::class)->findBy( [], ['isPrimary'=>'DESC', 'id'=>'DESC']);
$selectedAuthtype = null;
if ($authtype) {
$selectedAuthtype = $this->entityManager->getRepository(Authtype::class)->findOneBy([
'name' => $authtype
]);
}
return $this->render('security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
'authtypes' => $authtypes,
'selectedAuthtype' => $selectedAuthtype,
]
);
}
#[Route(path: '/password-reset', name: 'password_reset')]
public function passwordReset(Request $request, ResetPasswordHolderRepository $rep,
TranslatorInterface $translator, EntityManagerInterface $em, UserFacade $userFacade)
{
$userId = $request->get("userId");
$hex= $request->get("hex");
$resetPassword = $rep->get($userId, $hex);
if($resetPassword === null)
{
$this->addFlash("error", $translator->trans("The URL is not correct, please try resetting your password again"));
return $this->redirectToRoute("app_login");
}
$form = $this->createForm(PasswordResetType::class);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
$resetPassword->setActivatedAt(new \DateTime());
$em->flush();
$userFacade->setNewPassword($resetPassword->getUser(), $form->get("password")->getData());
$em->flush();
$this->addFlash("info", $translator->trans("Password reset, please log in"));
return $this->redirectToRoute("app_login");
}
return $this->render(
"security/resetPassword.html.twig", [
'form' => $form->createView()
]
);
}
#[Route(path: '/logout', name: 'app_logout')]
public function logout(): never
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
}