<?php
namespace App\Controller;
use App\Entity\User;
use App\Form\Type\ForgotPasswordType;
use App\Service\EmailService;
use App\Service\MessageService;
use Exception;
use Swift_Mailer;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class ForgotPasswordController extends AbstractController
{
/**
* @Route("/forgot-password", name="forgot_password")
* @param Request $request
* @param UserPasswordEncoderInterface $passwordEncoder
* @param MessageService $messageService
* @param EmailService $emailService
* @return RedirectResponse|Response
* @throws Exception
*/
public function forgotPassword(Request $request, UserPasswordEncoderInterface $passwordEncoder, MessageService $messageService, EmailService $emailService)
{
$entityManager = $this->getDoctrine()->getManager();
$form = $this->createForm(ForgotPasswordType::class, new User());
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user_tmp = $form->getData();
// load user by email
$user = $entityManager->getRepository(User::class)->findOneBy(array(
'email' => $user_tmp->getEmail()
));
if (!$user) {
// if no user with the given email address was found exit here
$messageService->setMessage('Something went wrong. Please try again.', 'danger');
return $this->redirectToRoute('forgot_password');
} else {
// generate random password
$random_password = $this->generateNewPassword();
// save new password to user
$user->setPassword($passwordEncoder->encodePassword($user, $random_password));
$user->setModified(new \DateTime());
$entityManager->persist($user);
$entityManager->flush();
// send message with new password
$emailService->setSubject('METRO Menu Engineering: Your new password');
$emailService->setTo($user->getEmail());
$emailService->setBody($this->renderView(EmailService::EMAIL_TEMPLATE_NEW_PASSWORD, [
"password" => $random_password,
"login_link" => $_SERVER["HTTP_ORIGIN"]. "/login"
]));
$emailService->send();
$messageService->setMessage('Your password was renewed. Please check your emails.');
return $this->redirectToRoute('login');
}
}
return $this->render('forgot.password.html.twig', [
'form' => $form->createView(),
]);
}
/**
* Generates and returns a random password
* @return false|string
*/
private function generateNewPassword()
{
$letters = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$random_password = "";
for ($i = 0; $i <= 12; $i++) {
$random_position = random_int(0, strlen($letters) - 1);
$random_password .= substr($letters, $random_position, 1);
}
return $random_password;
}
}