Last active
August 29, 2015 14:04
-
-
Save wizhippo/86820dd54012be0df970 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use eZ\Publish\Core\MVC\ConfigResolverInterface; | |
use Symfony\Component\HttpFoundation\RedirectResponse; | |
use Symfony\Component\HttpKernel\Event\GetResponseEvent; | |
use Symfony\Component\Routing\RouterInterface; | |
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken; | |
use Symfony\Component\Security\Core\SecurityContextInterface; | |
class RequireUserLoginListener | |
{ | |
/** | |
* @var \Symfony\Component\Security\Core\SecurityContextInterface | |
*/ | |
protected $securityContext; | |
/** | |
* @var \eZ\Publish\Core\MVC\ConfigResolverInterface | |
*/ | |
protected $configResolver; | |
/** | |
* @var \Symfony\Component\Routing\RouterInterface | |
*/ | |
protected $router; | |
public function __construct( | |
SecurityContextInterface $securityContext, | |
ConfigResolverInterface $configResolver, | |
RouterInterface $router | |
) | |
{ | |
$this->securityContext = $securityContext; | |
$this->configResolver = $configResolver; | |
$this->router = $router; | |
} | |
public function onKernelRequireLoginRedirect( GetResponseEvent $event ) | |
{ | |
$requireUserLogin = $this->configResolver->getParameter( | |
'SiteAccessSettings.RequireUserLogin' | |
); | |
$requireUserLogin = strtolower($requireUserLogin) == 'true' ? true : false; | |
$token = $this->securityContext->getToken(); | |
if ( $requireUserLogin && $token instanceof AnonymousToken ) | |
{ | |
$routeName = $event->getRequest()->get( '_route' ); | |
if ( !in_array( $routeName, [ 'login', 'login_check', 'logout', 'ez_legacy', null ] ) ) | |
{ | |
$event->setResponse( | |
new RedirectResponse( | |
$this->router->generate( 'login' ), | |
301 | |
) | |
); | |
$event->stopPropagation(); | |
return; | |
} | |
} | |
} | |
static public function getSubscribedEvents() | |
{ | |
return array( | |
// must be registered before the default Locale listener | |
KernelEvents::REQUEST => array( array( 'onKernelRequest', 17 ) ), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment