<?php
namespace Mm\Beton\Planungsatlas\AtlasBundle\Controller;
use Doctrine\Persistence\ManagerRegistry;
use Mm\Beton\Planungsatlas\AtlasBundle\Repository\UserRepository;
use Mm\Beton\Planungsatlas\AtlasBundle\Form\ChangePasswordType;
use Mm\Beton\Planungsatlas\AtlasBundle\Form\Model\ChangePassword;
use Mm\Beton\Planungsatlas\AtlasBundle\Form\Model\ResetPassword;
use Mm\Beton\Planungsatlas\AtlasBundle\Form\ResetPasswordType;
use Mm\Beton\Planungsatlas\AtlasBundle\Service\GenerationService;
use Mm\Beton\Planungsatlas\AtlasBundle\Entity\User\User;
use Mm\Beton\Planungsatlas\AtlasBundle\Form\RegisterType;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class UserController extends AbstractAuthenticatedController
{
private $managerRegistry;
public function __construct(ManagerRegistry $managerRegistry)
{
$this->managerRegistry = $managerRegistry;
}
/**
* @Route("/login", name="login")
*/
public function loginAction(TranslatorInterface $translator)
{
$this->addFlash('error', $translator->trans('Please login'));
return $this->redirectToRoute('home');
}
/**
* @Route("/user-delete", name="user_delete")
* @Security("is_granted('IS_AUTHENTICATED_FULLY')")
*/
public function deleteAction(Request $request, TranslatorInterface $translator, TokenStorageInterface $tokenStorage)
{
$user = $this->getUser();
$entityManager = $this->managerRegistry->getManager('user');
$entityManager->remove($user);
$entityManager->flush();
unset($_SESSION['userinfo']);
$tokenStorage->setToken(null);
$request->getSession()->invalidate();
$this->addFlash('success', $translator->trans('Your profile was removed'));
$response = [
'state' => 1
];
return new JsonResponse( $response );
}
/**
* @Route("/ajax-login", name="ajax_login")
*/
public function ajaxLoginAction()
{
//everything happens in service
}
/**
* @Route(
* "/logout",
* name="logout"
* )
*
* @return Response
*/
public function logoutAction()
{
unset($_SESSION['userinfo']);
session_destroy();
return $this->render('index.html.twig');
}
/**
* @Route("/register", name="user_registration")
*/
public function registerAction(
Request $request,
ParameterBagInterface $parameterBag,
GenerationService $generationService,
UserPasswordHasherInterface $encoder,
TranslatorInterface $translator,
\Swift_Mailer $mailer
)
{
$user = new User();
$form = $this->createForm(RegisterType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$generatedPassword = $generationService->generatePassword(8);
$password = $encoder->hashPassword($user, $generatedPassword);
$hash = $generationService->generateHash();
$user->setPassword($password);
$user->setHash($hash);
$date = new \DateTime();
$user->setRegisteredAt($date);
$user->setLastLoginAt($date);
// save the User
$entityManager = $this->managerRegistry->getManager('user');
$entityManager->persist($user);
$entityManager->flush();
// send DOI email
$this->sendDOIEmail(
$request,
$translator,
$mailer,
$user
);
// send new user notify email
$this->sendNewUserNotifyEmail(
$translator,
$mailer,
$user,
$parameterBag->get('notifyNewUserEmail'),
$parameterBag->get('brand_name')
);
// success flash message
$this->addFlash('success', $translator->trans('Check your email and approve it by link'));
return $this->redirectToRoute('home');
}
return $this->render(
'user/register.html.twig', [
'form' => $form->createView(),
'loggedIn' => false
]
);
}
/**
* @Route("/doi/{hash}", name="doi_check")
*/
public function doiAction(
TranslatorInterface $translator,
GenerationService $generationService,
UserPasswordHasherInterface $encoder,
\Swift_Mailer $mailer,
$hash
)
{
$entityManager = $this->managerRegistry->getManager('user');
/** @var UserRepository $userRepository */
$userRepository = $entityManager->getRepository(User::class);
/** @var User $user */
$user = $userRepository->findOneBy(
['hash' => $hash]
);
if (empty($user)) {
// error flash message
$this->addFlash('error', $translator->trans('Hash not exists'));
return $this->redirectToRoute('home');
}
// activate user
$user->setIsActive(true);
$user->setHash('');
// send email with password
$this->sendEmailWithPassword(
$generationService,
$encoder,
$translator,
$mailer,
$user
);
// save the User (include new password)
$entityManager->persist($user);
$entityManager->flush();
// success flash message
$this->addFlash('success', $translator->trans('Your email approved. Please check email to find password'));
return $this->redirectToRoute('home');
}
/**
* @Route("/reset-password", name="user_reset_password")
*/
public function resetPasswordAction(
Request $request,
TranslatorInterface $translator,
GenerationService $generationService,
UserPasswordHasherInterface $encoder,
\Swift_Mailer $mailer
)
{
$data = new ResetPassword();
$form = $this->createForm(ResetPasswordType::class, $data);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/** @var UserRepository $userRepository */
$userRepository = $this->managerRegistry->getRepository(User::class, 'user');
/** @var User $user */
$user = $userRepository->findOneBy(['username' => $data->getUsername()]);
if (!$user instanceof User) {
// error flash message
$this->addFlash('error', $translator->trans('User not exists'));
return $this->redirectToRoute('home');
}
// send email with password
$this->sendEmailWithPassword(
$generationService,
$encoder,
$translator,
$mailer,
$user
);
// save the User (include new password)
$entityManager = $this->managerRegistry->getManager('user');
$entityManager->persist($user);
$entityManager->flush();
// success flash message
$this->addFlash('success', $translator->trans('New password was created. Please check email'));
return $this->redirectToRoute('home');
}
return $this->render(
'user/resetPassword.html.twig',
[
'form' => $form->createView()
]
);
}
/**
* Change password action
*
* @Route("/change-password", name="user_change_password")
* @Security("is_granted('IS_AUTHENTICATED_FULLY')")
*/
public function changePasswordAction(
Request $request,
UserPasswordHasherInterface $encoder,
TranslatorInterface $translator
)
{
$changePasswordModel = new ChangePassword();
$form = $this->createForm(
ChangePasswordType::class,
$changePasswordModel
);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user = $this->getUser();
$password = $encoder->hashPassword($user, $changePasswordModel->getNewPassword());
$user->setPassword($password);
// save the User
$entityManager = $this->managerRegistry->getManager('user');
$entityManager->persist($user);
$entityManager->flush();
// success flash message
$this->addFlash('success', $translator->trans('Your password was changed'));
return $this->redirectToRoute('home');
}
return $this->render(
'user/changePassword.html.twig',
[
'form' => $form->createView()
]
);
}
/**
* Send email to user with hash
*
* @param Request $request
* @param TranslatorInterface $translator
* @param User $user
*/
protected function sendDOIEmail(Request $request, TranslatorInterface $translator, \Swift_Mailer $mailer, User $user)
{
$link = $request->getSchemeAndHttpHost() . $this->generateUrl(
'doi_check',
['hash' => $user->getHash()]
);
$message = (new \Swift_Message($translator->trans('DOI Email Subject')))
->setFrom(
[
'noreply@wdvs-planungsatlas.de' => 'WDVS-Planungsatlas'
]
)
->setTo($user->getUsername())
->setBody(
$this->renderView(
'Emails/doi.html.twig',
[
'link' => $link
]
),
'text/html'
);
$mailer->send($message);
}
/**
* Send email with password
*
* @param GenerationService $generationService
* @param UserPasswordHasherInterface $encoder
* @param TranslatorInterface $translator
* @param $user
*/
protected function sendEmailWithPassword(
GenerationService $generationService,
UserPasswordHasherInterface $encoder,
TranslatorInterface $translator,
\Swift_Mailer $mailer,
$user
)
{
$generatedPassword = $generationService->generatePassword(8);
$password = $encoder->hashPassword($user, $generatedPassword);
$user->setPassword($password);
$message = (new \Swift_Message($translator->trans('Password Email Subject')))
->setFrom(['noreply@wdvs-planungsatlas.de' => 'WDVS-Planungsatlas'])
->setTo($user->getUsername())
->setBody(
$this->renderView(
'Emails/password.html.twig',
['pass' => $generatedPassword]
),
'text/html'
);
$result = $mailer->send($message);
if (!$result) {
exit('An error occurred while sending an email');
}
}
/**
* Send notify email about new user
*
* @param TranslatorInterface $translator
* @param \Swift_Mailer $mailer
* @param $user
*/
protected function sendNewUserNotifyEmail(
TranslatorInterface $translator,
\Swift_Mailer $mailer,
$user,
$notifyEmail,
$brandName)
{
$message = (new \Swift_Message($translator->trans('email.notify_new')))
->setFrom(['noreply@wdvs-planungsatlas.de' => 'WDVS-Planungsatlas'])
->setTo($notifyEmail)
->setBody(
$this->renderView(
'Emails/newUserNotify.html.twig',
[
'brand' => $brandName,
'userEmail' => $user->getUsername()
]
),
'text/html'
);
$mailer->send($message);
}
}