Created
March 22, 2011 20:07
-
-
Save caefer/881945 to your computer and use it in GitHub Desktop.
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 MyProject\MyBundle\Security; | |
| use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; | |
| use Symfony\Component\Security\Core\Exception\UnsupportedUserException; | |
| use Symfony\Component\Security\Core\User\UserProviderInterface; | |
| use Symfony\Component\Security\Core\User\UserInterface; | |
| use \Facebook; | |
| use \FacebookApiException; | |
| class FacebookUserProvider implements UserProviderInterface | |
| { | |
| /** | |
| * @var \Facebook | |
| */ | |
| protected $facebook; | |
| protected $userManager; | |
| protected $validator; | |
| private $objectCache = array(); | |
| public function __construct(Facebook $facebook, $userManager, $validator) | |
| { | |
| $this->facebook = $facebook; | |
| $this->userManager = $userManager; | |
| $this->validator = $validator; | |
| } | |
| public function supportsClass($class) | |
| { | |
| return $this->userManager->supportsClass($class); | |
| } | |
| public function findUserByFbId($fbId) | |
| { | |
| if (!isset($this->objectCache[$fbId])) { | |
| $this->objectCache[$fbId] = $this->userManager->findUserBy(array('facebookID' => $fbId)); | |
| } | |
| return $this->objectCache[$fbId]; | |
| } | |
| public function loadUserByUsername($username) | |
| { | |
| $user = $this->findUserByFbId($username); | |
| try { | |
| $fbdata = $this->facebook->api('/me'); | |
| } catch (FacebookApiException $e) { | |
| $fbdata = null; | |
| } | |
| if (!empty($fbdata)) { | |
| if (empty($user)) { | |
| $user = $this->userManager->createUser(); | |
| $user->setEnabled(true); | |
| $user->setPassword(''); | |
| $user->setAlgorithm(''); | |
| } | |
| $user->setFBData($fbdata); | |
| if (count($this->validator->validate($user, 'Facebook'))) { | |
| throw new UsernameNotFoundException('The facebook user could not be stored'); | |
| } | |
| $this->userManager->updateUser($user); | |
| } | |
| if (empty($user)) { | |
| throw new UsernameNotFoundException('The user is not authenticated on facebook'); | |
| } | |
| return $user; | |
| } | |
| public function loadUser(UserInterface $user) | |
| { | |
| if (!$this->supportsClass(get_class($user)) || !$user->getFacebookId()) { | |
| throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user))); | |
| } | |
| return $this->loadUserByUsername($user->getFacebookId()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment