<?php
namespace WpBundle\Listener;
use CoreBundle\Service\UserService;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Firewall\ListenerInterface;
use CoreBundle\Entity\User;
use WpBundle\Security\WPAuthToken;
use WpBundle\Service\WPAuthService;
/**
* Class WPAuthListener
*/
class WPAuthListener implements ListenerInterface
{
/** @var TokenStorage */
protected $tokenStorage;
/** @var AuthenticationManagerInterface */
protected $authenticationManager;
/** @var WPAuthService */
protected $wpAuthService;
/** @var UserService */
protected $userService;
/**
* WPAuthListener constructor.
* @param TokenStorage $tokenStorage
* @param AuthenticationManagerInterface $authenticationManager
* @param WPAuthService $wpAuthService
* @param UserService $userManager
*/
public function __construct(
TokenStorage $tokenStorage,
AuthenticationManagerInterface $authenticationManager,
WPAuthService $wpAuthService,
UserService $userManager
) {
$this->tokenStorage = $tokenStorage;
$this->authenticationManager = $authenticationManager;
$this->wpAuthService = $wpAuthService;
$this->userService = $userManager;
}
/**
* @param GetResponseEvent $event
* @throws \Exception
*/
public function handle(GetResponseEvent $event)
{
try {
$this->wpAuthService->initUserAndAuthCookie();
/**
* @var \WpBundle\Entity\User $wpUser
*/
if ($wpUser = $this->wpAuthService->getUser()) {
/**
* @var User $user
*/
$user = $this->userService->findUserByEmail($wpUser->getEmail());
if (!$user) {
$user = $this->userService->createUser(
$wpUser->getId(),
$wpUser->getEmail(),
$wpUser->getEmail(),
uniqid('pass_', true)
);
}
$this->loginUser($user);
} else {
throw new AuthenticationException();
}
} catch (\Exception $e) {
$this->loginUser(null);
}
}
/**
* @param User $user
*/
private function loginUser(?User $user)
{
if (!$user) {
$token = new WPAuthToken([
'IS_AUTHENTICATED_ANONYMOUSLY'
]);
$token = $this->authenticationManager->authenticate($token);
} else {
$token = new WPAuthToken($user->getRoles());
$token->setUser($user);
$token = $this->authenticationManager->authenticate($token);
}
$this->tokenStorage->setToken($token);
}
}