Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Symfony AuthenticationSuccessHandler
<?php
namespace AppBundle\Security;
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationSuccessHandler;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\Common\Persistence\ObjectManager;
use AppBundle\Entity\User;
use AppBundle\Entity\UserHasLoggedIn;
class AuthenticationSuccessHandler extends DefaultAuthenticationSuccessHandler
{
/**
* @var ObjectManager|null
*/
private $objectManager;
public function setObjectManager(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
}
/**
* {@inheritdoc}
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
$this->assertDependenciesAreSet();
$this->reportSuccess($request, $this->getUser($token));
return parent::onAuthenticationSuccess($request, $token);
}
private function assertDependenciesAreSet()
{
if (null === $this->objectManager) {
throw new \LogicException('Call setObjectManager() first');
}
}
/**
* @param TokenInterface $token
* @return User
* @throws \UnexpectedValueException
*/
private function getUser(TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof User) {
throw new \UnexpectedValueException();
}
return $user;
}
private function reportSuccess(Request $request, User $user)
{
$report = new UserHasLoggedIn($user, /* blah blah */);
$this->objectManager->persist($report);
$this->objectManager->flush();
}
}
security:
firewalls:
default:
form_login:
success_handler: security_login_success_handler
services:
security_login_success_handler:
class: AppBundle\Security\AuthenticationSuccessHandler
arguments: [@security.http_utils]
calls:
- [setObjectManager, [@doctrine.orm.entity_manager]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment