<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use App\Form\UserType;
use App\Form\ProfileType;
use App\Entity\User;
use App\Service\Breadcrumb;
use Symfony\Contracts\Translation\TranslatorInterface;
class SecurityController extends AbstractController
{
private $breadcrumb;
public function __construct(Breadcrumb $breadcrumb){
$this->breadcrumb = $breadcrumb;
}
/**
* @Route("/login", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
// 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("/register", name="app_register")
*/
public function register(Request $request, UserPasswordEncoderInterface $passwordEncoder): Response
{
$user = new User();
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$passwordEncoder->encodePassword(
$user,
$form->get('plainPassword')->getData()
)
);
//$user->setBirthDate(new \Datetime(date('Y-m-d',strtotime($request->get('user')['birthDate']))));
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
// do anything else you need here, like send an email
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->container->get('security.token_storage')->setToken($token);
$this->container->get('session')->set('_security_main', serialize($token));
return $this->redirectToRoute('dashboard');
}
return $this->render('security/register.html.twig', [
'form' => $form->createView(),
]);
}
/**
* @Route("/profile", name="app_profile")
*/
public function profile(Request $request,TokenStorageInterface $tokenStorage, TranslatorInterface $translator): Response
{
$this->breadcrumb->set([
$translator->trans('Tableau de bord') => 'dashboard',
'Profile' => NULL
]);
$user = $tokenStorage->getToken()->getUser();
$form = $this->createForm(ProfileType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//$user->setBirthDate(new \Datetime(date('Y-m-d',strtotime($request->get('user')['birthDate']))));
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
return $this->redirectToRoute('dashboard');
}
return $this->render('security/profile.html.twig', [
'form' => $form->createView(),
]);
}
/**
* @Route("/logout", name="app_logout", methods={"GET"})
*/
public function logout(): Response
{
// controller can be blank: it will never be executed!
throw new \Exception('Don\'t forget to activate logout in security.yaml');
}
/**
* @Route("/forgotten_password", name="app_forgotten_password")
*/
public function forgottenPassword(
Request $request,
UserPasswordEncoderInterface $encoder,
\Swift_Mailer $mailer,
TokenGeneratorInterface $tokenGenerator ): Response
{
if ($request->isMethod('POST')) {
$email = $request->request->get('email');
$entityManager = $this->getDoctrine()->getManager();
$user = $entityManager->getRepository(User::class)->findOneByEmail($email);
if ($user === null) {
$this->addFlash('error', 'Cet adresse e-mail n\'est pas connue de notre système');
return $this->redirectToRoute('app_login');
}
$token = $tokenGenerator->generateToken();
try{
$user->setResetToken($token);
$entityManager->flush();
} catch (\Exception $e) {
$this->addFlash('error', $e->getMessage());
return $this->redirectToRoute('app_login');
}
$url = $this->generateUrl('app_reset_password', array('token' => $token), UrlGeneratorInterface::ABSOLUTE_URL);
$message = (new \Swift_Message('Réinitialisation de votre mot de passe'))
->setFrom('info@oura.ch')
->setTo($user->getEmail())
->setBody(
$this->renderView(
'emails/reset_password.html.twig',
['url' => $url]
),
'text/html'
);
$mailer->send($message);
$this->addFlash('notice', 'Un e-mail vient de vous être envoyé pour réinitialiser votre mot de passe');
return $this->redirectToRoute('dashboard');
}
return $this->render('security/forgotten_password.html.twig');
}
/**
* @Route("/reset_password/{token}", name="app_reset_password")
* @Route("/create_password/{token}", name="app_create_password")
*/
public function setPassword(Request $request, string $token, UserPasswordEncoderInterface $passwordEncoder)
{
if ($request->isMethod('POST')) {
$entityManager = $this->getDoctrine()->getManager();
$user = $entityManager->getRepository(User::class)->findOneByResetToken($token);
/* @var $user User */
if ($user === null) {
$this->addFlash('danger', 'Token Inconnu');
return $this->redirectToRoute('dashboard');
}
$user->setResetToken(null);
$user->setPassword($passwordEncoder->encodePassword($user, $request->request->get('password')));
$entityManager->flush();
$this->addFlash('notice', 'Mot de passe mis à jour');
return $this->redirectToRoute('app_login');
}else {
return $this->render('security/reset_password.html.twig', ['token' => $token]);
}
}
}