Skip to content

Instantly share code, notes, and snippets.

@qdelettre
Created September 10, 2013 06:44
Show Gist options
  • Save qdelettre/6505770 to your computer and use it in GitHub Desktop.
Save qdelettre/6505770 to your computer and use it in GitHub Desktop.
FacebookProvider
class FacebookProvider implements UserProviderInterface
{
/**
* @var \Facebook
*/
protected $facebook;
protected $userManager;
protected $validator;
public function __construct(BaseFacebook $facebook, $userManager, $validator)
{
$this->facebook = $facebook;
$this->userManager = $userManager;
$this->validator = $validator;
}
public function supportsClass($class)
{
return $this->userManager->supportsClass($class);
}
/**
* Find user by email
*
* @param string $email
*
* @return mixed
*/
public function findUserByEmail($email)
{
return $this->userManager->findUserBy(array('email' => $email));
}
public function findUserByFbId($fbId)
{
return $this->userManager->findUserBy(array('facebookId' => $fbId));
}
public function loadUserByUsername($username)
{
// we don't want to use this function, because
// we don't store the FbId in database
// $user = $this->findUserByFbId($username);
//
$user = null;
try {
$fbdata = $this->facebook->api('/me');
} catch (FacebookApiException $e) {
$fbdata = null;
}
if (!empty($fbdata)) {
// check user : find user with email
if (null === $user) {
$user = $this->findUserByEmail($fbdata['email']);
}
// new user : redirect to registration form
if (null === $user) {
$user = new User();
$user->setUsername($fbdata['first_name'][0].$fbdata['last_name']);
$user->setEnabled(true);
$user->setPassword('');
}
// TODO use http://developers.facebook.com/docs/api/realtime
$user->setFBData($fbdata);
if (count($this->validator->validate($user, 'Facebook'))) {
// TODO: the user was found obviously, but doesnt match our expectations, do something smart
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 refreshUser(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