RequestListener.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /*
  3. * This file is part of the Sonata project.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\UserBundle\GoogleAuthenticator;
  11. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  12. use Sonata\UserBundle\Model\UserInterface;
  13. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  14. use Symfony\Component\Security\Core\SecurityContextInterface;
  15. use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
  16. class RequestListener
  17. {
  18. protected $helper;
  19. protected $securityContext;
  20. protected $templating;
  21. /**
  22. * @param Helper $helper
  23. * @param \Symfony\Component\Security\Core\SecurityContextInterface $securityContext
  24. * @param \Symfony\Bundle\FrameworkBundle\Templating\EngineInterface $templating
  25. */
  26. public function __construct(Helper $helper, SecurityContextInterface $securityContext, EngineInterface $templating)
  27. {
  28. $this->helper = $helper;
  29. $this->securityContext = $securityContext;
  30. $this->templating = $templating;
  31. }
  32. /**
  33. * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  34. * @return
  35. */
  36. public function onCoreRequest(GetResponseEvent $event)
  37. {
  38. $token = $this->securityContext->getToken();
  39. if (!$token) {
  40. return;
  41. }
  42. if (!$token instanceof UsernamePasswordToken) {
  43. return;
  44. }
  45. $key = $this->helper->getSessionKey($this->securityContext->getToken());
  46. $request = $event->getRequest();
  47. $session = $event->getRequest()->getSession();
  48. $user = $this->securityContext->getToken()->getUser();
  49. if (!$session->has($key)) {
  50. return;
  51. }
  52. if ($session->get($key) === true) {
  53. return;
  54. }
  55. $state = 'init';
  56. if ($request->getMethod() == 'POST') {
  57. if ($this->helper->checkCode($user, $request->get('_code')) == true) {
  58. $session->set($key, true);
  59. return;
  60. }
  61. $state = 'error';
  62. }
  63. $event->setResponse($this->templating->renderResponse('SonataUserBundle:Admin:Security/two_step_form.html.twig', array(
  64. 'state' => $state
  65. )));
  66. }
  67. }