<?php
namespace App\Controller;
use App\Entity\User;
use App\Form\AuthType;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends AbstractController
{
#[Route(path: '/login', name: 'app_login')]
public function login(AuthenticationUtils $authenticationUtils): Response
{
if ($this->getUser()) {
return $this->redirectToRoute('app_home');
}
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render(
'security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error
]
);
}
#[Route(path: '/logout', name: 'app_logout')]
public function logout(): void
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
#[Route('/register', name: 'app_register')]
public function register(
ManagerRegistry $managerRegistry,
Request $request,
UserPasswordHasherInterface $passwordHasher
): Response
{
$user = new User();
$form = $this->createForm(AuthType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$user->setFirstName($data['firstName']);
$user->setLastName($data['lastName']);
$user->setEmail($data['email']);
$hashedPassword = $passwordHasher->hashPassword(
$user,
$data['password']
);
$user->setPassword($hashedPassword);
$user->setStatus(0);
$user->setRoles(['ROLE_USER']);
$entityManager = $managerRegistry->getManager();
$entityManager->persist($user);
$entityManager->flush();
return $this->redirectToRoute('app_login');
}
return $this->render('security/register.html.twig', [
'form' => $form->createView(),
]);
}
}