Skip to content

Instantly share code, notes, and snippets.

@coreymcmahon
Created May 19, 2012 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coreymcmahon/2729525 to your computer and use it in GitHub Desktop.
Save coreymcmahon/2729525 to your computer and use it in GitHub Desktop.
Using a custom UserProviderInterface for Symfony Security - http://www.symfonycentral.com/securing-your-web-application-with-symfony.html
<?php
namespace MyCompany\BlogBundle\Entity;
use Doctrine\ORM\EntityRepository;
// Make sure we include UserProviderInterface
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
class UserRepository implements UserProviderInterface // Add the 'implements' clause
{
function loadUserByUsername($username)
{
// Find and load the user from the database
$q = $this
->createQueryBuilder('u')
->where('u.username = :username')
->setParameter('username', $username)
->getQuery()
;
// If we don't find a record, throw an exception, authentication fails
try {
$user = $q->getSingleResult();
} catch (NoResultException $e) {
throw new UsernameNotFoundException(
'Unable to find an active admin MyCompanyBlogBundle:User object identified'
);
}
return $user;
}
function refreshUser(UserInterface $user)
{
$class = get_class($user);
if (!$this->supportsClass($class)) {
throw new UnsupportedUserException('User type not supported');
}
return $this->loadUserByUsername($user->getUsername());
}
function supportsClass($class)
{
return $this->getEntityName() === $class ||
is_subclass_of($class, $this->getEntityName());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment