src/ClientBundle/Controller/AuthController.php line 255

Open in your IDE?
  1. <?php
  2. namespace ClientBundle\Controller;
  3. use AdminBundle\Controller\BaseController;
  4. use AdminBundle\Entity\Account;
  5. use AdminBundle\Entity\Settings;
  6. use AdminBundle\Entity\User;
  7. use AdminBundle\Helpers\MandrillManager;
  8. use ClientBundle\Form\AuthType;
  9. use ClientBundle\Form\RegisterType;
  10. use FOS\UserBundle\Form\Factory\FactoryInterface;
  11. use FOS\UserBundle\Model\UserManagerInterface;
  12. use FOS\UserBundle\Util\TokenGeneratorInterface;
  13. use Symfony\Component\HttpFoundation\RedirectResponse;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  16. use Symfony\Component\Security\Core\Exception\AccountStatusException;
  17. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  18. class AuthController extends BaseController {
  19. public function loginAction(AuthenticationUtils $authenticationUtils) {
  20. $flash = $this->get('session')->getFlashBag();
  21. $error = $authenticationUtils->getLastAuthenticationError();
  22. if ($error) {
  23. $flash->add(
  24. 'danger',
  25. 'Something went wrong. '. $error->getMessage()
  26. );
  27. } else {
  28. $flash->add(
  29. 'info',
  30. '<strong>First time logging in?</strong> '.
  31. '<br/> * Use the "<b>Reset your password</b>" feature to receive a password reset link, or'.
  32. '<br/> * Use the "<b>Authentication Link</b>" feature to receive a quick-login link'.
  33. '<br/><b>Note:</b> The links expire once used.'
  34. );
  35. }
  36. $lastUsername = $authenticationUtils->getLastUsername();
  37. return $this->render('@Client/Auth/Login/login.html.twig', [
  38. 'last_username' => $lastUsername,
  39. 'error' => $error,
  40. ]);
  41. }
  42. public function resetRequestAction(Request $request) {
  43. $default = true;
  44. $flash = $this->get('session')->getFlashBag();
  45. $form = $this->createForm(
  46. AuthType::class
  47. );
  48. $form->handleRequest($request);
  49. if ($form->isSubmitted() && $form->isValid()) {
  50. $email = $form->get('email')->getData();
  51. $userManager = $this->get('sonata.user.user_manager');
  52. $user = $userManager->findUserByUsernameOrEmail($email);
  53. if (null === $user) {
  54. $default = false;
  55. $flash->add(
  56. 'danger',
  57. 'The provided email address "<b>'. $email. '</b>" does not belong to any existing users.'
  58. );
  59. } else {
  60. $ttl = $this->getParameter('fos_user.resetting.retry_ttl');
  61. if (!$user->isPasswordRequestNonExpired($ttl)) {
  62. /** @var $tokenGenerator TokenGeneratorInterface */
  63. $tokenGenerator = $this->get('fos_user.util.token_generator');
  64. $user->setConfirmationToken(
  65. $tokenGenerator->generateToken()
  66. );
  67. $user->setPasswordRequestedAt(new \DateTime());
  68. $userManager->save($user);
  69. $this->sendResettingEmail($user);
  70. $default = false;
  71. $flash->add(
  72. 'success',
  73. 'A password reset link has been sent to the provided email.<br/>
  74. Please access the link to reset your password.<br/>
  75. <b>Note:</b> You can only request a password reset link once every'.
  76. ' <b>'. ceil($ttl / 3600). '</b> hours.<br/>'.
  77. "If you didn't receive an email try checking your spam folder ".
  78. 'or try again later.'
  79. );
  80. } else {
  81. $default = false;
  82. $flash->add(
  83. 'warning',
  84. 'You can only request a password reset link once every'.
  85. ' <b>'. ceil($ttl / 3600). '</b> hours.<br/> Please try again later.'
  86. );
  87. }
  88. }
  89. }
  90. if ($default) {
  91. $flash->add(
  92. 'success',
  93. 'Please insert your email address below to receive a password reset link.'
  94. );
  95. }
  96. return $this->render('@Client/Auth/Reset/request.html.twig',[
  97. 'form' => $form->createView(),
  98. ]);
  99. }
  100. public function resetProcessAction(Request $request, $token) {
  101. $flash = $this->get('session')->getFlashBag();
  102. $userManager = $this->get('sonata.user.user_manager');
  103. $user = $userManager->findUserByConfirmationToken($token);
  104. if (
  105. !$user ||
  106. !$user->isPasswordRequestNonExpired(
  107. $this->getParameter('fos_user.resetting.token_ttl')
  108. )
  109. ) {
  110. $flash->add(
  111. 'danger',
  112. 'The password reset link is invalid.'
  113. );
  114. $flash->add(
  115. 'info',
  116. 'Use the "<b>Reset your password</b>" feature below to receive a new reset link.'
  117. );
  118. return new RedirectResponse(
  119. $this->generateUrl('client_login')
  120. );
  121. }
  122. /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
  123. $formFactory = $this->get('fos_user.resetting.form.factory');
  124. $form = $formFactory->createForm();
  125. $form->setData($user);
  126. $form->handleRequest($request);
  127. if ($form->isSubmitted() && $form->isValid()) {
  128. $user->setConfirmationToken(null);
  129. $user->setPasswordRequestedAt(null);
  130. $user->setEnabled(true);
  131. $message = $this->get('translator')->trans(
  132. 'resetting.flash.success',
  133. [],
  134. 'FOSUserBundle'
  135. );
  136. $flash->add('success', $message);
  137. $response = new RedirectResponse(
  138. $this->generateUrl('client_homepage')
  139. );
  140. return $this->authUser($user, $request, $response);
  141. } else {
  142. $flash->add(
  143. 'success',
  144. 'Please set and confirm your new password below.'
  145. );
  146. }
  147. return $this->render(
  148. '@Client/Auth/Reset/form.html.twig', [
  149. 'token' => $token,
  150. 'form' => $form->createView(),
  151. ]
  152. );
  153. }
  154. public function sendResettingEmail($user) {
  155. $em = $this->get('doctrine');
  156. $phone = $user->getPhone();
  157. $name = $user->getFullname();
  158. if (
  159. $client = $em->getRepository(Account::class)->findOneBy([
  160. 'user' => $user->getId(),
  161. ])
  162. ) {
  163. $phone = $client->getPhone();
  164. $name = $client->getName();
  165. }
  166. $url = $this->get('router')->generate(
  167. 'client_reset_process',[
  168. 'token' => $user->getConfirmationToken(),
  169. ], UrlGeneratorInterface::ABSOLUTE_URL
  170. );
  171. $from = $this->get('settings_repo')->getOfficeEmail();
  172. $mandrillManager = $this->get('mandrill.manager');
  173. $mandrillManager->sendTemplate(
  174. MandrillManager::$TEMPLATE_EMAIL_NOTIFICATION_GENERAL,
  175. [],
  176. [
  177. 'subject' => 'Twelve Transfers - Password Reset',
  178. 'from_email' => $from,
  179. 'to' => [
  180. 'email' => $user->getEmail(),
  181. 'name' => $user->getUsername(),
  182. 'type' => 'to',
  183. ],
  184. 'global_merge_vars' => [
  185. 'request_email' => $user->getEmail(),
  186. 'subject' => 'Password Reset',
  187. "content" => $this->renderView(
  188. '@Client/Auth/Reset/email.html.twig', [
  189. 'url' => $url
  190. ]
  191. ),
  192. ],
  193. ],
  194. true
  195. );
  196. }
  197. protected function authUser($user, $request, $response) {
  198. $userManager = $this->get('sonata.user.user_manager');
  199. $loginManager = $this->get('login.manager');
  200. try {
  201. $firewallName = 'client';
  202. $loginManager->logInUser($firewallName, $user, $response);
  203. $this->get(
  204. 'authentication.handler.login_success_handler'
  205. )->onAuthenticationSuccess(
  206. $request,
  207. $this->get('security.token_storage')->getToken()
  208. );
  209. $user->setLastLogin(new \DateTime());
  210. } catch (AccountStatusException $ex) {
  211. if ($this->has('logger')) {
  212. $this->get('logger')->warning(
  213. sprintf(
  214. 'Unable to login user %d',
  215. $user->getId()
  216. )
  217. );
  218. }
  219. }
  220. $userManager->save($user);
  221. return $response;
  222. }
  223. public function authProcessAction(Request $request, $token, $url) {
  224. $userManager = $this->get('sonata.user.user_manager');
  225. $user = $userManager->findUserByConfirmationToken($token);
  226. if (!$user) {
  227. $flash = $this->get('session')->getFlashBag();
  228. $flash->add(
  229. 'danger',
  230. 'The authentication link is invalid.'
  231. );
  232. return new RedirectResponse(
  233. $this->generateUrl('client_login')
  234. );
  235. }
  236. $user->setConfirmationToken(null);
  237. if ($url) {
  238. $url = urldecode($url);
  239. } else {
  240. $url = $this->generateUrl('client_homepage');
  241. }
  242. $response = new RedirectResponse($url);
  243. return $this->authUser($user, $request, $response);
  244. }
  245. public function authLinkAction(Request $request) {
  246. $default = true;
  247. $to = $request->query->get('to');
  248. $flash = $this->get('session')->getFlashBag();
  249. $form = $this->createForm(
  250. AuthType::class
  251. );
  252. $form->handleRequest($request);
  253. if ($form->isSubmitted() && $form->isValid()) {
  254. $email = $form->get('email')->getData();
  255. $userManager = $this->get('sonata.user.user_manager');
  256. $user = $userManager->findUserByUsernameOrEmail($email);
  257. if (null === $user) {
  258. $default = false;
  259. $flash->add(
  260. 'danger',
  261. 'The provided email address "<b>'. $email.'</b>" does not belong to any existing users.'
  262. );
  263. } else {
  264. /** @var $tokenGenerator TokenGeneratorInterface */
  265. $tokenGenerator = $this->get('fos_user.util.token_generator');
  266. $user->setConfirmationToken(
  267. $tokenGenerator->generateToken()
  268. );
  269. $userManager->save($user);
  270. $this->sendAuthEmail($user, $to);
  271. $default = false;
  272. $flash->add(
  273. 'success',
  274. 'The authentication link has been sent. Please check your email.'
  275. );
  276. }
  277. }
  278. if ($default) {
  279. $flash->add(
  280. 'success',
  281. 'Please insert your email address below to receive an authentication link.'
  282. );
  283. }
  284. return $this->render(
  285. '@Client/Auth/Login/link.html.twig', [
  286. 'form' => $form->createView()
  287. ]
  288. );
  289. }
  290. public function sendAuthEmail($user, $to = null) {
  291. $url = $this->get('router') ->generate(
  292. 'client_auth_process', [
  293. 'token' => $user->getConfirmationToken(),
  294. 'url' => urlencode($to)
  295. ], UrlGeneratorInterface::ABSOLUTE_URL
  296. );
  297. $from = $this->get('settings_repo')->getOfficeEmail();
  298. $mandrillManager = $this->get('mandrill.manager');
  299. $mandrillManager->sendTemplate(
  300. MandrillManager::$TEMPLATE_EMAIL_NOTIFICATION_GENERAL,
  301. [],
  302. [
  303. 'subject' => 'Twelve Transfers - Authentication Link',
  304. 'from_email' => $from,
  305. 'to' => [
  306. 'email' => $user->getEmail(),
  307. 'name' => $user->getUsername(),
  308. 'type' => 'to',
  309. ],
  310. 'global_merge_vars' => [
  311. "content" => $this->renderView(
  312. '@Client/Auth/Login/email.html.twig', [
  313. 'url' => $url
  314. ]
  315. ),
  316. 'request_email' => $user->getEmail(),
  317. 'subject' => 'Authentication Link',
  318. ],
  319. ],
  320. true
  321. );
  322. }
  323. public function signUpAction(Request $request) {
  324. $error = false;
  325. $flash = $this->get('session')->getFlashBag();
  326. $form = $this->createForm(
  327. AuthType::class
  328. );
  329. $form->handleRequest($request);
  330. if ($form->isSubmitted() && $form->isValid()) {
  331. $email = $form->get('email')->getData();
  332. $userManager = $this->get('sonata.user.user_manager');
  333. $user = $userManager->findUserByUsernameOrEmail($email);
  334. if (null === $user) {
  335. $now = new \DateTime();
  336. $user = $userManager->create();
  337. $user->setUsername($email);
  338. $user->setUsernameCanonical($email);
  339. $user->setEmail($email);
  340. $user->setEmailCanonical($email);
  341. $user->setPassword(md5(uniqid()));
  342. $user->addRole('ROLE_CLIENT');
  343. $user->setCreatedAt($now);
  344. $user->setUpdatedAt($now);
  345. $user->setEnabled(true);
  346. $userManager->save($user);
  347. $account = $user->getAccount();
  348. if (empty($account)) {
  349. $account = new Account();
  350. $account->setUser($user);
  351. $account->setTitle('Mr');
  352. $account->setName($email);
  353. $account->setPhone('12345');
  354. $account->setEmail($email);
  355. $em = $this->getDoctrine()->getManager();
  356. $em->persist($account);
  357. $user->setAccount($account);
  358. $em->flush();
  359. }
  360. $flash->add(
  361. 'success',
  362. 'Your account has been created!'
  363. );
  364. return new RedirectResponse(
  365. $this->generateUrl('client_login')
  366. );
  367. } else {
  368. $error = true;
  369. $flash->add(
  370. 'danger',
  371. 'This email is already being used. Use a different email address.'
  372. );
  373. }
  374. }
  375. if (!$error) {
  376. $flash->add(
  377. 'success',
  378. 'Please insert your email address below to create an account.'
  379. );
  380. }
  381. return $this->render('@Client/Auth/Register/signup.html.twig',[
  382. 'form' => $form->createView(),
  383. ]);
  384. }
  385. public function registerAction(
  386. Request $request
  387. ) {
  388. $error = false;
  389. $flash = $this->get('session')->getFlashBag();
  390. $userManager = $this->get('sonata.user.user_manager');
  391. $user = $userManager->create();
  392. $form = $this->createForm(
  393. RegisterType::class,
  394. $user
  395. );
  396. $form->handleRequest($request);
  397. if ($form->isSubmitted() && $form->isValid()) {
  398. $now = new \DateTime();
  399. $user = $form->getData();
  400. $email = $user->getEmail();
  401. $found = $userManager->findUserByUsernameOrEmail($email);
  402. if (null === $found) {
  403. $user->setUsername($email);
  404. $user->setUsernameCanonical($email);
  405. $user->setEmail($email);
  406. $user->setEmailCanonical($email);
  407. $user->addRole('ROLE_CLIENT');
  408. $user->setCreatedAt($now);
  409. $user->setUpdatedAt($now);
  410. $user->setEnabled(true);
  411. $userManager->save($user);
  412. $account = $user->getAccount();
  413. if (empty($account)) {
  414. $account = new Account();
  415. $account->setUser($user);
  416. $account->setTitle('Mr');
  417. $account->setName($email);
  418. $account->setPhone('12345');
  419. $account->setEmail($email);
  420. $em = $this->getDoctrine()->getManager();
  421. $em->persist($account);
  422. $user->setAccount($account);
  423. $em->flush();
  424. }
  425. $flash->add(
  426. 'success',
  427. 'Your account has been created!'
  428. );
  429. $response = new RedirectResponse(
  430. $this->generateUrl('client_homepage')
  431. );
  432. return $this->authUser($user, $request, $response);
  433. } else {
  434. $error = true;
  435. $flash->add(
  436. 'danger',
  437. 'This email is already being used. Use a different email address.'
  438. );
  439. }
  440. }
  441. if (!$error) {
  442. $flash->add(
  443. 'success',
  444. 'Please fill in your details below to create an account.'
  445. );
  446. }
  447. return $this->render(
  448. '@Client/Auth/Register/register.html.twig', [
  449. 'form' => $form->createView()
  450. ]
  451. );
  452. }
  453. }