<?php
namespace WebBundle\Controller;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use FlexApp\Form\ResettingFormType;
use FlexApp\Security\LoginFormAuthenticator;
use FlexApp\Service\Canonicalizer;
use FlexApp\Service\ManagerContactsProvider;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
use WebBundle\Entity\User;
use WebBundle\Helper\App;
use WebBundle\Repository\ListCountryRepository;
use WebBundle\Repository\UserRepository;
use WebBundle\Service\ListEmailService;
class ResettingController extends ExtendedController
{
/** @required */
public UserRepository $userRepository;
/** @required */
public ListCountryRepository $listCountryRepository;
/** @required */
public Canonicalizer $canonicalizer;
/** @required */
public FormFactoryInterface $formFactory;
/** @required */
public UserPasswordHasherInterface $userPasswordHasher;
/** @required */
public EntityManagerInterface $entityManager;
/** @required */
public UserAuthenticatorInterface $userAuthenticator;
/** @required */
public LoginFormAuthenticator $loginFormAuthenticator;
/** @required */
public RequestStack $requestStack;
/** @required */
public ManagerContactsProvider $managerContactsProvider;
/**
* Request reset user password: show form
*/
public function requestAction()
{
return $this->render('@Web/Resetting/request.html.twig');
}
/**
* @param Request $request
* @return RedirectResponse|Response
* @throws Exception
*/
public function sendEmailAction(Request $request)
{
$username = trim($request->request->get('username'));
$user = $this->userRepository->findOneByEmail($this->canonicalizer->canonicalize($username));
if (null === $user) {
return $this->render('@Web/Resetting/request.html.twig', [
'invalid_username' => $username,
]);
}
if (null === $user->getConfirmationToken()) {
$generatedConfirmationToken = base64_encode(md5(uniqid(true)));
$user->setConfirmationToken($generatedConfirmationToken);
$this->userRepository->save($user);
}
$contactsObject = $this->managerContactsProvider->getContacts();
//отправка письма
/** @var ListEmailService $listEmailService */
$listEmailService = $this->get('app.service.list_email');
$link = $this->container->get('router')->generate('user_resetting_reset', ['token' => $user->getConfirmationToken()], UrlGeneratorInterface::ABSOLUTE_URL);
$listEmailService->sendEmailByCriteria(
[
'keyEmail' => 'password_reset',
],
App::getCurLocale(),
[
$user->getEmail()
],
[
'%fio%' => $this->getFio($user),
'%designResetPasswordLinkLeft%' => '<center><table border="0" cellpadding="0" cellspacing="0" bgcolor="#6890C5"><tr><td width="10" height="40"> </td><td valign="middle" align="center"><a href="' . $link . '" style="color: white; text-decoration: none;">',
'%designResetPasswordLinkRight%' => '</a></td><td width="10" height="40"> </td></tr></table></center>',
'%resetPasswordLink%' => '<a href="' . $link . '">' . $link . '</a>',
'%managerName%' => $contactsObject->managerName,
'%managerEmail%' => $contactsObject->managerEmail,
'%managerPhone%' => $contactsObject->managerPhone,
'%designFooterStart%' => '<hr/><table bgcolor="#ededed"><tr><td colspan = 3 height="25px"> </td></tr><tr><td width = "25px"> </td><td style="font:normal 14px \'Arial\';line-height:18px;color:#333333;">',
'%designFooterEnd%' => '</td><td width = "25px"> </td></tr><tr><td colspan = 3 height="25px"> </td></tr></table>',
],
$this->container->getParameter('mailer_email_from')
);
return new RedirectResponse($this->generateUrl('user_resetting_check_email',
array('email' => $this->getObfuscatedEmail($user))
));
}
/**
* @param User $user
* @return string
* @throws Exception
*/
private function getFio($user): string
{
$locale = App::getCurLocale();
$mainDeliveryAddress = $user->getMainRecipientAddress();
if (!$mainDeliveryAddress->getId()) {
$this->entityManager->persist($mainDeliveryAddress);
$this->entityManager->flush();
}
$name = $mainDeliveryAddress->getName();
$sex = $user->getSex();
$t = App::trans((($sex == 1 || $sex == null) ? 'title.man' : 'title.woman'), $locale);
if ($locale != 'fr') {
$name = $t . ' ' . $name;
} else {
$name = $t;
}
$name = '<strong style="font-size: 18px;">' . $name . '</strong>';
$name .= ',';
return $name;
}
/**
* Tell the user to check his email provider
*/
public function checkEmailAction(Request $request)
{
$email = $request->query->get('email');
if (empty($email)) {
// the user does not come from the sendEmail action
return new RedirectResponse($this->generateUrl('user_resetting_request'));
}
return $this->render('@Web/Resetting/checkEmail.html.twig', array(
'email' => $email,
));
}
/**
* Reset user password
*/
public function resetAction(Request $request, $token): Response
{
$user = $this->userRepository->findOneBy(['confirmationToken' => $token]);
if (null === $user) {
throw new NotFoundHttpException(sprintf('The user with "confirmation token" does not exist for value "%s"', $token));
}
$form = $this->formFactory->create(ResettingFormType::class);
$form->setData($user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$plainPassword = $form->getData()->getPlainPassword();
$user->setPassword($this->userPasswordHasher->hashPassword($user, $plainPassword));
$user->setConfirmationToken(null);
$this->userRepository->save($user);
$url = $this->generateUrl('user_resetting_complete');
$this->userAuthenticator->authenticateUser($user, $this->loginFormAuthenticator, $this->requestStack->getCurrentRequest());
return new RedirectResponse($url);
}
return $this->render('@Web/Resetting/reset.html.twig', array(
'token' => $token,
'form' => $form->createView(),
));
}
/**
* @return Response
*/
public function completeAction(): Response
{
return $this->render('@Web/Resetting/complete_resetting.html.twig');
}
/**
* Get the truncated email displayed when requesting the resetting.
*
* The default implementation only keeps the part following @ in the address.
*
* @param User $user
*
* @return string
*/
protected function getObfuscatedEmail(User $user)
{
$email = $user->getEmail();
if (false !== $pos = strpos($email, '@')) {
$email = '...' . substr($email, $pos);
}
return $email;
}
}