Skip to content

Instantly share code, notes, and snippets.

@hpatoio
Last active June 26, 2018 15:58
Show Gist options
  • Save hpatoio/4761858 to your computer and use it in GitHub Desktop.
Save hpatoio/4761858 to your computer and use it in GitHub Desktop.
Event listener to force FOS user to change password
<?php
namespace Hpatoio\UserBundle\EventListener;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\HttpFoundation\Session\Session;
/**
* @Service("request.set_messages_count_listener")
*
*/
class HpatoioForcepassupdateListener
{
private $security_context;
private $router;
private $session;
public function __construct(Router $router, SecurityContext $security_context, Session $session)
{
$this->security_context = $security_context;
$this->router = $router;
$this->session = $session;
}
public function onCheckExpired(GetResponseEvent $event)
{
if ( ($this->security_context->getToken() ) && ( $this->security_context->isGranted('IS_AUTHENTICATED_FULLY') ) ) {
$route_name = $event->getRequest()->get('_route');
if ($route_name != 'fos_user_change_password') {
$pass_validity_days = 90;
$today = new \DateTime();
$days_since_last_change = $this->security_context->getToken()->getUser()->getPasswordChangedAt()->diff($today);
if ($days_since_last_change->format('%a') > $pass_validity_days ) {
$response = new RedirectResponse($this->router->generate('fos_user_change_password'));
$this->session->setFlash('error', "Your password hash expired. Please change it");
$event->setResponse($response);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment