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

Bzbb Authentication Bundle Laravel Package

allejo/bzbb-authentication-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle Add the package via Composer:

    composer require allejo/bzbb-authentication-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Allejo\BZBBAuthenticationBundle\AllejoBZBBAuthenticationBundle::class => ['all' => true],
    ];
    
  2. Configure the Bundle Update config/packages/allejo_bzbb_authentication.yaml (or create it if missing):

    allejo_bzbb_authentication:
        bzflag_url: 'https://www.bzflag.org'  # BZFlag forum URL
        login_path: '/login'                  # BZFlag login endpoint
        callback_path: '/bzbb-callback'       # Symfony callback route
    
  3. Create a Callback Route Define a route in config/routes.yaml:

    bzbb_callback:
        path: /bzbb-callback
        controller: Allejo\BZBBAuthenticationBundle\Controller\BZBBCallbackController::callbackAction
    
  4. First Use Case: Login Button Add a login link in a Twig template (e.g., templates/base.html.twig):

    <a href="{{ path('bzbb_callback') }}">Login with BZFlag</a>
    

    The bundle will handle the OAuth flow automatically.


Implementation Patterns

Workflow: OAuth Flow Integration

  1. Trigger Authentication Redirect users to the BZFlag login page via the callback route. The bundle handles:

    • Generating a state token for CSRF protection.
    • Redirecting to BZFlag’s login endpoint with preconfigured parameters.
  2. Callback Handling After BZFlag authentication, users are redirected to /bzbb-callback. The bundle:

    • Validates the state token.
    • Exchanges the BZFlag session for a Symfony User entity.
    • Logs the user in via Symfony’s security system.
  3. User Entity Integration Extend the default User entity to include BZFlag-specific fields (e.g., bzflagId, bzflagUsername):

    // src/Entity/User.php
    class User implements UserInterface
    {
        // ...
        private ?int $bzflagId;
        private ?string $bzflagUsername;
    }
    

    Configure the bundle to map BZFlag data to your User entity in config/packages/allejo_bzbb_authentication.yaml:

    allejo_bzbb_authentication:
        user_entity:
            class: App\Entity\User
            property_mappings:
                bzflag_id: 'bzflagId'
                username: 'bzflagUsername'
    
  4. Event-Driven Customization Listen to bundle events to customize behavior:

    • bzbb.authenticate: Modify the authentication logic (e.g., validate additional fields).
      // src/EventListener/BZBBAuthListener.php
      use Allejo\BZBBAuthenticationBundle\Event\AuthenticateEvent;
      
      public function onAuthenticate(AuthenticateEvent $event)
      {
          $userData = $event->getUserData();
          if (!$this->isValidUser($userData)) {
              throw new \RuntimeException('Invalid BZFlag user data');
          }
      }
      
      Register the listener in config/services.yaml:
      services:
          App\EventListener\BZBBAuthListener:
              tags:
                  - { name: kernel.event_listener, event: bzbb.authenticate, method: onAuthenticate }
      
  5. Security Integration Ensure the firewalls section in config/packages/security.yaml includes the callback route:

    security:
        firewalls:
            main:
                # ...
                form_login:
                    enable_csrf: true
                # Allow the callback route to bypass authentication temporarily
                pattern: ^/bzbb-callback
                anonymous: true
    

Gotchas and Tips

Pitfalls

  1. Deprecated Symfony 3.4 Guard Auth The bundle was updated for Symfony 3.4’s Guard auth changes, but Symfony 4+ users may need additional adjustments (e.g., Authenticator interfaces). Test thoroughly with your Symfony version.

  2. State Token Validation

    • Issue: Missing or invalid state tokens can cause authentication failures.
    • Fix: Ensure the state parameter is preserved in redirects and validated in the callback. The bundle uses Symfony’s GuardAuthenticatorHandler for this, but custom routes may bypass it.
    • Debug: Check var/log/dev.log for Invalid CSRF token errors.
  3. BZFlag API Changes

    • BZFlag’s login endpoint may change without notice. The bundle assumes a specific OAuth flow. If BZFlag updates their API, the bundle’s BZBBCallbackController may need patches.
    • Workaround: Override the controller or extend the bundle to adapt to new endpoints.
  4. User Entity Mismatch

    • If the User entity doesn’t match the bundle’s expected structure, authentication will fail silently.
    • Debug: Enable debug mode and check for UserNotFoundException or PropertyAccessException.
  5. Session Handling

    • The bundle relies on BZFlag’s session cookie. If the user clears cookies or uses private browsing, the callback may fail.
    • Tip: Inform users to avoid private browsing modes for BZFlag authentication.

Tips

  1. Testing the Flow

    • Use Symfony’s HACCESS or curl to simulate the OAuth flow:
      curl -v "https://www.bzflag.org/login?state=YOUR_STATE_TOKEN"
      
    • Mock the callback response in tests by overriding the BZBBCallbackController.
  2. Customizing the Login Page

    • Extend the bundle’s login template by overriding AllejoBZBBAuthenticationBundle:Default:login.html.twig in your theme.
  3. Logging and Monitoring

    • Enable debug logging for the bundle in config/packages/monolog.yaml:
      handlers:
          bzbb:
              type: stream
              path: "%kernel.logs_dir%/bzbb_auth.log"
              level: debug
              channels: ["bzbb"]
      
    • Add the bzbb channel to the bundle’s services.
  4. Performance Considerations

    • The bundle makes HTTP requests to BZFlag’s API during authentication. For high-traffic sites, cache the user data or implement a queue system to avoid rate-limiting.
  5. Extending the Bundle

    • To add support for additional BZFlag endpoints (e.g., profile data), create a custom service that extends Allejo\BZBBAuthenticationBundle\Service\BZBBUserProvider:
      // src/Service/CustomBZBBUserProvider.php
      use Allejo\BZBBAuthenticationBundle\Service\BZBBUserProvider;
      
      class CustomBZBBUserProvider extends BZBBUserProvider
      {
          public function fetchUserData($sessionData)
          {
              // Add custom logic here
              return parent::fetchUserData($sessionData);
          }
      }
      
    • Register the service in config/services.yaml and update the bundle’s configuration to use your provider.
  6. Fallback Authentication

    • Combine BZFlag auth with other providers (e.g., email/password) using Symfony’s ProviderChainAuthenticator. Example:
      security:
          firewalls:
              main:
                  provider: chain_provider
                  form_login: ~
      providers:
          chain_provider:
              chain:
                  providers: [bzbb_provider, custom_provider]
                  voter_checker: security.user_voter_checker
          bzbb_provider:
              id: allejo_bzbb_authentication.user_provider
      
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.
croct/coding-standard
croct/plug-php
nqxcode/phpmorphy
boundwize/pyrameter
testo/facade
headercat/phpstan-extension-ide-helper
yosymfony/parser-utils
innmind/black-box
babenkoivan/elastic-migrations
babenkoivan/elastic-adapter
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle