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

Custom Login Bundle Laravel Package

bridgewatercollege/custom-login-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation

    composer require bridgewatercollege/custom-login-bundle
    

    Add to config/bundles.php:

    BridgewaterCollege\CustomLoginBundle\BridgewaterCollegeCustomLoginBundle::class => ['all' => true],
    
  2. Publish Configuration

    php bin/console bridgewater-college:custom-login:install
    

    This generates:

    • config/packages/bridgewater_college_custom_login.yaml (default config)
    • Login templates in templates/bridgewater_college_custom_login/
  3. Basic Usage Define a login system in config/packages/bridgewater_college_custom_login.yaml:

    bridgewater_college_custom_login:
        systems:
            default:
                type: "form"  # or "oauth", "api_key"
                form:
                    path: /login
                    template: bridgewater_college_custom_login/login.html.twig
                    handler: App\Security\CustomLoginHandler
    
  4. First Login Route Access /login (or your defined path) to test the default form-based login.


Implementation Patterns

1. Multi-Login System Workflow

  • Define Systems: Configure each login method (form, OAuth, API key) in config/packages/bridgewater_college_custom_login.yaml:

    systems:
        oauth_google:
            type: "oauth"
            provider: "google"
            client_id: "%env(GOOGLE_CLIENT_ID)%"
            client_secret: "%env(GOOGLE_CLIENT_SECRET)%"
            redirect_route: "app_verify_google"
        api_key:
            type: "api_key"
            path: "/api/login"
            handler: App\Security\ApiKeyHandler
    
  • Route Integration:

    # config/routes.yaml
    bridgewater_college_custom_login:
        resource: "@BridgewaterCollegeCustomLoginBundle/Resources/config/routing.yaml"
    

2. Custom Handlers

  • Extend BridgewaterCollege\CustomLoginBundle\Security\LoginHandlerInterface:
    namespace App\Security;
    
    use BridgewaterCollege\CustomLoginBundle\Security\LoginHandlerInterface;
    use Symfony\Component\HttpFoundation\Request;
    
    class CustomLoginHandler implements LoginHandlerInterface {
        public function handle(Request $request) {
            $email = $request->request->get('email');
            $password = $request->request->get('password');
            // Custom logic (e.g., LDAP, database, or external API)
            return $user; // Return a User object or throw an exception
        }
    }
    
  • Register in config:
    systems:
        custom:
            type: "form"
            handler: App\Security\CustomLoginHandler
    

3. OAuth Integration

  • Configure providers (e.g., Google, GitHub) in config/packages/bridgewater_college_custom_login.yaml:
    systems:
        oauth_github:
            type: "oauth"
            provider: "github"
            client_id: "%env(GITHUB_CLIENT_ID)%"
            client_secret: "%env(GITHUB_CLIENT_SECRET)%"
            scope: ["user:email"]
    
  • Implement a verifier route (e.g., app_verify_github) to handle OAuth callbacks.

4. API Key Authentication

  • Define a route for API key login:
    systems:
        api_key:
            type: "api_key"
            path: "/api/login"
            handler: App\Security\ApiKeyHandler
    
  • Handle requests in ApiKeyHandler:
    public function handle(Request $request) {
        $apiKey = $request->headers->get('X-API-KEY');
        if ($this->validateApiKey($apiKey)) {
            return $this->userProvider->loadUserByUsername($apiKey);
        }
        throw new \RuntimeException('Invalid API key');
    }
    

5. Template Customization

  • Override default templates by copying files from: vendor/bridgewatercollege/custom-login-bundle/templates/bridgewater_college_custom_login/ to: templates/bridgewater_college_custom_login/.
  • Extend Twig templates with custom logic (e.g., add CSRF tokens, branding).

6. Security Context

  • Use the bundle’s events to integrate with Symfony’s security system:
    // src/EventListener/CustomLoginListener.php
    use BridgewaterCollege\CustomLoginBundle\Event\LoginEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class CustomLoginListener implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [
                LoginEvent::LOGIN_SUCCESS => 'onLoginSuccess',
            ];
        }
    
        public function onLoginSuccess(LoginEvent $event) {
            // Log, audit, or trigger post-login actions
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Configuration Overrides

    • Ensure bridgewater_college_custom_login.yaml is merged correctly. Use !import or !include sparingly to avoid conflicts.
    • Fix: Test config changes with php bin/console debug:config bridgewater_college_custom_login.
  2. Handler Misconfiguration

    • If a handler throws an exception, the bundle may not log it clearly. Wrap handler logic in try-catch:
      public function handle(Request $request) {
          try {
              // Logic
          } catch (\Exception $e) {
              throw new \RuntimeException('Login failed: ' . $e->getMessage());
          }
      }
      
  3. OAuth Redirect URI Mismatch

    • Symfony’s OAuth bundles (e.g., hwi-oauth) may conflict with this bundle’s OAuth routes.
    • Fix: Explicitly define redirect_route in config and ensure it matches your route name.
  4. Template Caching

    • Twig templates may not update if the cache is enabled. Clear cache after changes:
      php bin/console cache:clear
      
  5. CSRF Protection

    • The default form template includes CSRF, but custom templates must manually add:
      {{ form_start(form, { 'attr': {'novalidate': 'novalidate'} }) }}
          {{ form_row(form._token) }} {# CSRF token #}
      
  6. User Provider Assumptions

    • The bundle assumes a User object is returned. If using a custom provider (e.g., LDAP), ensure it returns an object compatible with Symfony’s UserInterface.

Debugging Tips

  1. Enable Debug Mode Set APP_DEBUG=true in .env to see detailed errors and logs.

  2. Log Events Subscribe to LoginEvent::LOGIN_FAILURE to log failed attempts:

    public static function getSubscribedEvents() {
        return [
            LoginEvent::LOGIN_FAILURE => 'onLoginFailure',
        ];
    }
    
  3. Check Routes Verify routes are loaded:

    php bin/console debug:router | grep custom_login
    
  4. Validate Config Use the debug command to validate your config:

    php bin/console debug:config bridgewater_college_custom_login
    

Extension Points

  1. Custom Login Types Extend the bundle by adding new type handlers. Implement LoginHandlerInterface and register in config:

    systems:
        custom_type:
            type: "custom_type"
            handler: App\Security\CustomTypeHandler
    
  2. Event-Driven Logic Dispatch custom events in handlers:

    $dispatcher->dispatch(new CustomLoginEvent($user, $request));
    
  3. Multi-Factor Authentication (MFA) Chain handlers or use events to integrate MFA (e.g., TOTP) after successful login.

  4. Rate Limiting Use Symfony’s RateLimiter or a library like symfony/throttler to limit login attempts per IP:

    use Symfony\Component\Security\Http\Firewall\RateLimiterInterface;
    
    class CustomLoginHandler implements LoginHandlerInterface {
        private $rateLimiter;
    
        public function __construct(RateLimiterInterface $rateLimiter) {
            $this->rateLimiter = $rateLimiter;
        }
    
        public function handle(Request $request) {
            $this->rateLimiter->check($request->getClientIp());
            // Rest of logic
        }
    }
    
  5. Localization Override translation files in translations/ to customize messages (e.g., "Invalid credentials").

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