FacebookProvider.php 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace Muzich\CoreBundle\Security\User\Provider;
  3. use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
  4. use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
  5. use Symfony\Component\Security\Core\User\UserProviderInterface;
  6. use Symfony\Component\Security\Core\User\UserInterface;
  7. use \BaseFacebook;
  8. use \FacebookApiException;
  9. class FacebookProvider implements UserProviderInterface
  10. {
  11. /**
  12. * @var \Facebook
  13. */
  14. protected $facebook;
  15. protected $userManager;
  16. protected $validator;
  17. public function __construct(BaseFacebook $facebook, $userManager, $validator)
  18. {
  19. $this->facebook = $facebook;
  20. $this->userManager = $userManager;
  21. $this->validator = $validator;
  22. }
  23. public function supportsClass($class)
  24. {
  25. return $this->userManager->supportsClass($class);
  26. }
  27. public function findUserByFbId($fbId)
  28. {
  29. return $this->userManager->findUserBy(array('facebook_id' => $fbId));
  30. }
  31. public function loadUserByUsername($username)
  32. {
  33. $user = $this->findUserByFbId($username);
  34. try {
  35. $fbdata = $this->facebook->api('/me');
  36. } catch (FacebookApiException $e) {
  37. throw new UsernameNotFoundException('The user is not authenticated on facebook');
  38. $fbdata = null;
  39. }
  40. if (!empty($fbdata)) {
  41. if (empty($user)) {
  42. $user = $this->userManager->getNewReadyUser();
  43. $user->setFBData($fbdata);
  44. }
  45. if (count($this->validator->validate($user, 'Facebook'))) {
  46. throw new UsernameNotFoundException('The facebook user could not be stored');
  47. }
  48. $this->userManager->updateUser($user);
  49. }
  50. if (empty($user)) {
  51. throw new UsernameNotFoundException('The user is not authenticated on facebook');
  52. }
  53. return $user;
  54. }
  55. public function refreshUser(UserInterface $user)
  56. {
  57. if (!$this->supportsClass(get_class($user)) || !$user->getFacebookId()) {
  58. throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
  59. }
  60. return $this->loadUserByUsername($user->getFacebookId());
  61. }
  62. }