<?php
namespace App\Controller;
use App\Entity\User;
use App\Form\NewUserType;
use App\Repository\UserRepository;
use App\Services\UploadImageService;
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
{
private UserRepository $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
#[Route('/login', name: 'app_login', methods: ['GET', 'POST'])]
public function login(AuthenticationUtils $authenticationUtils): Response
{
if($this->getUser() instanceof User) {
return $this->redirectToRoute('app_login');
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error
]);
}
/**
* @Route("/logout", name="app_logout")
*/
public function logout()
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
#[Route('/register', name: 'register')]
public function register(Request $request, UserPasswordHasherInterface $passwordHasher, UploadImageService $imageService): Response
{
if($this->getUser() instanceof User) {
return $this->redirectToRoute('home');
}
$user = new User();
$form = $this->createForm(NewUserType::class, $user);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$user
->setPassword($passwordHasher->hashPassword($user, $user->getPassword()))
->setImage($imageService->uploadImage($user->getImageFile(), $this->getParameter('profile_images_directory')))
;
$this->userRepository->save($user, true);
return $this->redirectToRoute('home');
}
return $this->render('security/register.twig', [
'form' => $form->createView(),
'errors' => $form->getErrors()
]);
}
}