src/UI/WebBundle/Controller/Security/SecurityController.php line 180

Open in your IDE?
  1. <?php
  2. namespace Whater\UI\WebBundle\Controller\Security;
  3. use Whater\UI\WebBundle\Controller\AbstractBusController;
  4. use Whater\Infrastructure\SecurityBundle\Form\Type\LoginType;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\Security\Core\Security;
  7. use Symfony\Component\HttpFoundation\RedirectResponse;
  8. use Symfony\Component\Routing\Annotation\Route;
  9. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  10. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  11. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  12. use Symfony\Component\Security\Http\SecurityEvents;
  13. use Whater\Application\UseCase\Security\CommandRequest\LoginCommand;
  14. use Whater\Application\UseCase\Security\CommandRequest\ForgotPasswordCommand;
  15. use Whater\Infrastructure\SecurityBundle\Form\Type\ForgotPaswordType;
  16. use Whater\Infrastructure\SecurityBundle\Form\Type\ResetPaswordType;
  17. use Whater\Application\UseCase\Security\CommandRequest\ResetPasswordCommand;
  18. use Whater\Application\UseCase\Security\CommandRequest\SignupCommand;
  19. use Whater\Domain\User\Exception\UserNotFoundException;
  20. use Whater\Domain\User\Exception\ResetTokenExpiredException;
  21. use Whater\Application\UseCase\User\CommandRequest\GetUserByUsernameCommand;
  22. use Whater\Domain\Security\Exception\InvalidUsernameException;
  23. use Whater\Infrastructure\SecurityBundle\Form\Type\SignupType;
  24. use Whater\Infrastructure\SecurityBundle\Security\Model\Auth;
  25. /**
  26. * @Route("")
  27. */
  28. class SecurityController extends AbstractBusController
  29. {
  30. /**
  31. * @Route("/login", name="web_login", defaults={"_format" = "html"})
  32. */
  33. public function loginAction(Request $request)
  34. {
  35. // If user is authenticated redirect to user dashboard
  36. if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  37. return new RedirectResponse($this->router()->generate('web_app_user_dashboard'));
  38. }
  39. $targetPath = $request->get('_target_path');
  40. $form = $this->getFormFactory()->create(LoginType::class, LoginCommand::convertToDTO(), array(
  41. 'action' => $this->router()->generate('web_login_check', array('_target_path' => $targetPath), true),
  42. 'method' => 'POST',
  43. 'csrf_protection' => true
  44. ));
  45. $session = $request->getSession();
  46. if ($request->attributes->has(Security::AUTHENTICATION_ERROR)) {
  47. $error = $request->attributes->get(Security::AUTHENTICATION_ERROR);
  48. } elseif (null !== $session && $session->has(Security::AUTHENTICATION_ERROR)) {
  49. $error = $session->get(Security::AUTHENTICATION_ERROR);
  50. $session->remove(Security::AUTHENTICATION_ERROR);
  51. } else {
  52. $error = null;
  53. }
  54. if (!$error instanceof AuthenticationException) {
  55. $error = null;
  56. }
  57. if (!empty($error)) {
  58. $this->setFlash('error', $this->translator()->trans($error->getMessageKey(), $error->getMessageData(), 'security'));
  59. }
  60. return $this->render('Security/login.html.twig', array('form' => $form->createView()));
  61. }
  62. /**
  63. * @Route("/login_check", name="web_login_check", defaults={"_format" = "html"})
  64. */
  65. public function loginCheckAction(Request $request)
  66. {
  67. throw new \RuntimeException('You must configure the check path to be handled by the firewall using form_login in your security firewall configuration.');
  68. }
  69. /**
  70. * @Route("/logout", name="web_logout", defaults={"_format" = "html"})
  71. */
  72. public function logoutAction()
  73. {
  74. throw new \RuntimeException('You must activate the logout in your security firewall configuration.');
  75. }
  76. /**
  77. * @Route("/forgot_password", name="web_forgot_password", defaults={"_format" = "html"})
  78. */
  79. public function forgotPasswordAction(Request $request)
  80. {
  81. // If user is authenticated redirect to user dashboard
  82. if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  83. return new RedirectResponse($this->router()->generate('web_init'));
  84. }
  85. $form = $this->getFormFactory()->create(ForgotPaswordType::class, ForgotPasswordCommand::convertToDTO(), array(
  86. 'action' => $this->router()->generate('web_forgot_password', array(), true),
  87. 'method' => 'POST',
  88. 'csrf_protection' => true
  89. ));
  90. if ('POST' === $request->getMethod()) {
  91. $form->handleRequest($request);
  92. $error = '';
  93. if ($form->isSubmitted() && $form->isValid()) {
  94. try {
  95. $this->handle(ForgotPasswordCommand::fromDTO($form->getData()));
  96. $this->setFlash('success', $this->translator()->trans('web.security.forgot_password.success'));
  97. } catch (UserNotFoundException $e) {
  98. $this->setFlash('error', $this->translator()->trans('web.security.forgot_password.user_not_found'));
  99. }
  100. } else {
  101. $this->setFlash('error', $this->translator()->trans('web.security.forgot_password.error'));
  102. }
  103. }
  104. return $this->render(
  105. 'Security/forgot_password.html.twig',
  106. array('form' => $form->createView())
  107. );
  108. }
  109. /**
  110. * @Route("/reset_password/{resetToken}", name="web_reset_password", defaults={"_format" = "html"})
  111. */
  112. public function forgotPasswordLandingAction(Request $request, string $resetToken)
  113. {
  114. // If user is authenticated redirect to user dashboard
  115. if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  116. return new RedirectResponse($this->router()->generate('web_init'));
  117. }
  118. $form = $this->getFormFactory()->create(ResetPaswordType::class, ResetPasswordCommand::convertToDTO(), array(
  119. 'action' => $this->router()->generate(
  120. 'web_reset_password',
  121. array(
  122. 'resetToken' => $resetToken
  123. ),
  124. true
  125. ),
  126. 'method' => 'POST',
  127. 'csrf_protection' => true,
  128. 'resetToken' => $resetToken
  129. ));
  130. if ('POST' === $request->getMethod()) {
  131. $form->handleRequest($request);
  132. if ($form->isSubmitted() && $form->isValid()) {
  133. try {
  134. $username = $this->handle(ResetPasswordCommand::fromDTO($form->getData()));
  135. $user = $this->handle(new GetUserByUsernameCommand($username));
  136. //Autenticate and go to dashboard
  137. $token = new UsernamePasswordToken(new Auth($user), null, "main", $user->rolesAsArray());
  138. $this->tokenStorage()->setToken($token); //now the user is logged in
  139. $this->session()->set('_security_main', serialize($token));
  140. return new RedirectResponse($this->router()->generate('web_init'));
  141. } catch (ResetTokenExpiredException $e) {
  142. $this->setFlash('error', $this->translator()->trans('web.security.reset_password.invalid_token'));
  143. } catch (UserNotFoundException $e) {
  144. $this->setFlash('error', $this->translator()->trans('web.security.reset_password.user_not_found'));
  145. }
  146. } else {
  147. $this->setFlash('error', $this->translator()->trans('web.security.reset_password.error'));
  148. }
  149. }
  150. return $this->render(
  151. 'Security/reset_password.html.twig',
  152. array('form' => $form->createView())
  153. );
  154. }
  155. /**
  156. * @Route("/signup", name="web_signup", defaults={"_format" = "html"})
  157. */
  158. public function signupUserAction(Request $request)
  159. {
  160. if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  161. return new RedirectResponse($this->router()->generate('web_init'));
  162. }
  163. $form = $this->getFormFactory()->create(SignupType::class, SignupCommand::convertToDTO(), array(
  164. 'method' => 'POST',
  165. 'csrf_protection' => true
  166. ));
  167. if ('POST' === $request->getMethod()) {
  168. $form->handleRequest($request);
  169. if ($form->isSubmitted() && $form->isValid()) {
  170. try {
  171. $user = $this->handle(SignupCommand::fromDTO($form->getData()));
  172. //Autenticate and go to dashboard
  173. $roles = ['ROLE_USER'];
  174. foreach ($user->roles() as $role) {
  175. $roles[] = $role->roleType();
  176. }
  177. $token = new UsernamePasswordToken(new Auth($user), null, "main", $roles);
  178. $this->tokenStorage()->setToken($token); //now the user is logged in
  179. $this->session()->set('_security_main', serialize($token));
  180. $loginEvent = new InteractiveLoginEvent($request, $token);
  181. $this->eventDispatcher()->dispatch($loginEvent, SecurityEvents::INTERACTIVE_LOGIN);
  182. $this->setFlash('info', $this->translator()->trans('web.security.signup.success'));
  183. return new RedirectResponse($this->router()->generate('web_app_whater_map'));
  184. } catch (InvalidUsernameException $e) {
  185. $this->setFlash('error', $this->translator()->trans('web.security.signup.invalid_username'));
  186. } catch (\Exception $e) {
  187. $this->logger()->error($e->getMessage());
  188. $this->setFlash('error', $this->translator()->trans('web.security.signup.exception'));
  189. }
  190. } else {
  191. $this->setFlash('error', $this->translator()->trans('web.security.signup.error'));
  192. }
  193. }
  194. $referralCode = $request->get('referral_code');
  195. $response = $this->render(
  196. 'Security/signup.html.twig',
  197. array(
  198. 'form' => $form->createView(),
  199. 'referralCode' => $referralCode
  200. )
  201. );
  202. return $response;
  203. }
  204. }