Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Facebook Bundle Laravel Package

ailove-dev/facebook-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ailove-dev/facebook-bundle
    

    Ensure ailove-dev/abstract-social-bundle and friendsofsymfony/facebook-bundle are also installed (handled via dependency).

  2. Enable the Bundle Add to config/bundles.php:

    Ailove\FacebookBundle\AiloveFacebookBundle::class => ['all' => true],
    
  3. Configure Facebook App Update .env with your Facebook App credentials:

    FACEBOOK_APP_ID=your_app_id
    FACEBOOK_APP_SECRET=your_app_secret
    FACEBOOK_REDIRECT_URI=http://your-app.dev/connect/facebook/check
    
  4. Extend FOSUserBundle Override User entity to include Facebook-specific fields (e.g., facebookId):

    // src/Entity/User.php
    use Ailove\AbstractSocialBundle\Model\SocialUserInterface;
    
    class User extends BaseUser implements SocialUserInterface
    {
        /**
         * @ORM\Column(type="string", length=255, nullable=true)
         */
        private $facebookId;
    }
    
  5. First Use Case: Login Flow Add a route to trigger Facebook auth (e.g., login/facebook):

    # config/routes.yaml
    facebook_login:
        path: /login/facebook
        controller: AiloveFacebookBundle:Security:login
    

    Redirect users to /login/facebook to start the OAuth flow.


Implementation Patterns

Workflow: Social Login Integration

  1. Trigger OAuth Flow Use the bundle’s controller to redirect to Facebook:

    // src/Controller/AuthController.php
    use Ailove\FacebookBundle\Controller\SecurityController;
    
    class AuthController extends SecurityController
    {
        public function loginAction()
        {
            return $this->get('facebook.security.authentication.manager')->authenticate();
        }
    }
    
  2. Handle Callback The bundle auto-handles the callback at /connect/facebook/check. Customize behavior by overriding the AuthenticationSuccessHandler:

    # config/services.yaml
    services:
        App\Security\FacebookAuthSuccessHandler:
            class: App\Security\FacebookAuthSuccessHandler
            arguments: ['@router', '@fos_user.user_manager']
            tags:
                - { name: 'monolog.logger', channel: 'security' }
    
  3. Post-Auth Logic Extend UserProvider to link Facebook accounts to existing users or create new ones:

    // src/Security/FacebookUserProvider.php
    use Ailove\AbstractSocialBundle\Provider\SocialUserProvider;
    
    class FacebookUserProvider extends SocialUserProvider
    {
        protected function getSocialId($data)
        {
            return $data['id']; // Facebook user ID
        }
    
        protected function getSocialUsername($data)
        {
            return $data['email'] ?? $data['id'] . '@facebook.com';
        }
    }
    
  4. User Entity Mapping Ensure your User entity implements SocialUserInterface and maps Facebook fields:

    public function setFacebookId(?string $facebookId): self
    {
        $this->facebookId = $facebookId;
        return $this;
    }
    
    public function getFacebookId(): ?string
    {
        return $this->facebookId;
    }
    

Integration Tips

  • FOSUserBundle Compatibility: Leverage existing FOSUserBundle features (e.g., UserManager) for post-auth user handling.
  • Custom Claims: Extend getSocialExtraData() in your UserProvider to fetch additional Facebook profile fields (e.g., name, picture):
    protected function getSocialExtraData($data)
    {
        return [
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'picture' => 'https://graph.facebook.com/' . $data['id'] . '/picture?type=large',
        ];
    }
    
  • Testing: Mock the Facebook SDK response in unit tests:
    $facebookService = $this->createMock(\Facebook\FacebookSession::class);
    $facebookService->method('getToken')->willReturn('test_token');
    $this->container->set('facebook.session', $facebookService);
    

Gotchas and Tips

Pitfalls

  1. Deprecated Dependencies

    • The bundle relies on friendsofsymfony/facebook-bundle (v1.x), which is outdated. Expect compatibility issues with newer Symfony/FOSUserBundle versions.
    • Fix: Override deprecated services or use a wrapper layer for Facebook SDK calls.
  2. Missing Documentation

    • No clear docs on extending the bundle or handling edge cases (e.g., revoked tokens).
    • Tip: Study Ailove\AbstractSocialBundle for patterns, then extend FacebookBundle classes (e.g., AuthenticationManager).
  3. CSRF Token Mismatch

    • The callback route may fail if CSRF protection isn’t disabled or configured correctly.
    • Fix: Add to config/packages/security.yaml:
      firewalls:
          main:
              form_login:
                  check_path: /login_check
              facebook_login:
                  pattern: ^/login/facebook
                  csrf_token_generator: security.csrf.token_manager
      
  4. User Linking Logic

    • Default behavior may not handle duplicate Facebook logins (e.g., same email but different IDs).
    • Tip: Implement custom logic in loadUserBySocialId() to merge accounts:
      public function loadUserBySocialId($socialId)
      {
          $user = $this->findUserBy(['facebookId' => $socialId]);
          if (!$user) {
              $user = $this->createUserFromSocialData($socialData);
          }
          return $user;
      }
      

Debugging

  • Token Errors: Use facebook/facebook-php-sdk-v4 for debugging:
    $fb = \Facebook\Facebook::newInstance([...]);
    try {
        $response = $fb->get('/me?fields=id,name,email');
    } catch (\Facebook\Exceptions\FacebookResponseException $e) {
        // Handle invalid response
    } catch (\Facebook\Exceptions\FacebookSDKException $e) {
        // Handle SDK errors
    }
    
  • Log Social Data: Add a logger to getSocialExtraData() to inspect raw Facebook responses.

Extension Points

  1. Custom Authentication Manager Override AiloveFacebookBundle\Security\Authentication\AuthenticationManager to add pre/post-auth logic:

    class CustomAuthManager extends AuthenticationManager
    {
        protected function createAuthenticatedToken($user, $providerKey)
        {
            // Add custom claims or metadata
            $token = parent::createAuthenticatedToken($user, $providerKey);
            $token->setAttribute('facebook_data', $this->getSocialExtraData($this->getSessionData()));
            return $token;
        }
    }
    
  2. Dynamic Redirects Extend AuthenticationSuccessHandler to redirect based on user roles:

    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        $user = $token->getUser();
        if ($user->hasRole('ROLE_ADMIN')) {
            return new RedirectResponse('/admin');
        }
        return new RedirectResponse('/dashboard');
    }
    
  3. Rate Limiting Add a decorator to facebook.session to handle Facebook API rate limits:

    $session = $this->get('facebook.session');
    if ($session instanceof \Facebook\FacebookSession) {
        $session->setDefaultApplication($this->getFacebookApp());
        $session->setDefaultAccessToken($this->getAccessToken());
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle