Created
May 19, 2012 06:03
-
-
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
This file contains hidden or 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 | |
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