<?php
namespace App\Controller;
use App\Entity\User;
use App\Manager\UserManager;
use App\Form\ResetPasswordType;
use App\Repository\UserRepository;
use App\Form\ForgottenPasswordType;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class SecurityController extends AbstractController
{
/**
* @Route("/login", name="security_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("/reset_password", name="security_reset_password")
*
* @param Request $request
* @param UserRepository $userRepo
* @param UserPasswordEncoderInterface $encoder
* @param UserManager $userManager
*
* @return Response
* @throws \Exception
*/
public function resetPassword(Request $request, UserRepository $userRepo, UserPasswordEncoderInterface $encoder, UserManager $userManager)
{
$isTokenValid = false;
$tokenToCheck = $request->query->get('token');
if(!$tokenToCheck)
{
return $this->redirectToRoute('security_login');
}
$userTarget = $userRepo->findOneByToken($tokenToCheck);
$form = $this->createForm(ResetPasswordType::class, $userTarget);
$form->handleRequest($request);
// If token match a User
if ($userTarget != null) {
// Check if token is expired
$dateNow = new \Datetime('now');
$dateNow->setTimezone(new \DateTimezone('Europe/Paris'));
$tokenDate = $userTarget->getTokenCreatedAt();
$tokenDate->add(new \DateInterval('P7D'));
if ($dateNow < $tokenDate) {
// Define token Status
$isTokenValid = true;
if ($form->isSubmitted() && $form->isValid()) {
$newPassword = $form->get('password')->getData();
$userTarget->setPassword($encoder->encodePassword($userTarget, $newPassword));
$userTarget->setTokenResetPassword(null);
$userTarget->setTokenCreatedAt(null);
$userManager->update($userTarget);
$this->addFlash(
'success',
'Mot de passe mis à jour avec succès.'
);
return $this->redirectToRoute('security_login');
}
} else {
return $this->redirectToRoute('security_forgotten_password', [
'tokenExpired' => true
]);
}
}
return $this->render('security/reset_password.html.twig', [
'form' => $form->createView(),
'token_is_valid' => $isTokenValid,
]);
}
/**
* @Route("/forgotten_password", name="security_forgotten_password")
*
* @param Request $request
* @param UserManager $userManager
* @param UserRepository $userRepo
* @param TokenGeneratorInterface $tokenGenerator
* @param \Swift_Mailer $mailer
*
* @return Response
* @throws \Exception
*/
public function forgottenPassword(Request $request, UserManager $userManager, UserRepository $userRepo, TokenGeneratorInterface $tokenGenerator, \Swift_Mailer $mailer)
{
$tokenExpired = false;
if ($request->query->get('tokenExpired')){
$tokenExpired = $request->query->get('tokenExpired');
}
$submitted = false;
$userExist = false;
$form = $this->createForm(ForgottenPasswordType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$submitted = true;
$email = $form->get('email')->getData();
$user = $userRepo->findOneBy(['email' => $email]);
if ($user) {
$userExist = true;
$date = (new \DateTime('now'))
->setTimezone(new \DateTimeZone('Europe/Paris'));
// Generate a random token
$token = $tokenGenerator->generateToken();
// Associate token to User
$user->setTokenResetPassword($token);
$user->setTokenCreatedAt($date);
// Save token
$userManager->update($user);
// Send email to User
$sendEmail = (new \Swift_Message())
->setFrom(['no-reply@specific-polymers.fr' => 'Specific Polymers'])
->setTo($user->getEmail())
->setSubject('Specific Polymers - Récupération de votre mot de passe')
->setBody(
$this->renderView(
'mail/reset_password_mail.html.twig',
[
'user_target' => $user,
]
),
'text/html'
);
$mailer->send($sendEmail);
}
}
return $this->render(
'security/forgotten_password.html.twig',
[
'form' => $form->createView(),
'submitted' => $submitted,
'tokenExpired' => $tokenExpired,
'userExist' => $userExist
]
);
}
/**
* @Route("/logout", name="security_logout")
*/
public function logout()
{
}
}