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

Session Concurrency Bundle Laravel Package

ajgl/session-concurrency-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ajgl/session-concurrency-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Ajgl\SessionConcurrencyBundle\AjglSessionConcurrencyBundle::class => ['all' => true],
    ];
    
  2. Configuration: Add to config/packages/ajgl_session_concurrency.yaml:

    ajgl_session_concurrency:
        max_sessions: 3  # Default max concurrent sessions
        session_name: 'APP_SESSION'  # Custom session name if needed
    
  3. First Use Case:

    • Lock a session: Automatically enforced when a user logs in via Symfony’s security system.
    • Test concurrency: Log in from multiple browsers/tabs to observe session invalidation behavior.

Key Files to Review

  • config/packages/ajgl_session_concurrency.yaml: Bundle configuration.
  • src/Resources/doc/index.md: Official documentation (check for Symfony 5+ compatibility notes).
  • Ajgl\SessionConcurrencyBundle\DependencyInjection\Configuration.php: Defaults and validation logic.

Implementation Patterns

Core Workflow

  1. Session Validation: Integrate the AjglSessionConcurrencyListener into Symfony’s security system. The bundle hooks into SECURITY_INTERACTIVE_LOGIN and SECURITY_AUTO_LOGIN events to validate session counts.

    // Example in a custom event subscriber (if extending behavior)
    public function onLogin(InteractiveLoginEvent $event) {
        $session = $event->getRequest()->getSession();
        $this->sessionConcurrency->validateSession($session);
    }
    
  2. Custom Session Storage: For non-standard session backends (e.g., Redis, database), extend Ajgl\SessionConcurrency\SessionStorageInterface:

    class CustomSessionStorage implements SessionStorageInterface {
        public function countSessions(string $sessionId): int { ... }
        public function invalidateSession(string $sessionId): void { ... }
    }
    

    Register it in services.yaml:

    ajgl_session_concurrency.storage: '@custom_session_storage'
    
  3. Whitelisting IPs/Paths: Exclude specific routes or IPs from concurrency checks via configuration:

    ajgl_session_concurrency:
        ignore_paths:
            - '^/admin'
        ignore_ips:
            - '127.0.0.1'
    
  4. Event-Driven Extensions: Listen to ajgl.session_concurrency.session_invalidated to handle invalidation side effects (e.g., logging, notifications):

    use Ajgl\SessionConcurrencyBundle\Event\SessionInvalidatedEvent;
    
    public function onSessionInvalidated(SessionInvalidatedEvent $event) {
        $this->logger->info('Session invalidated for user: ' . $event->getUsername());
    }
    

Integration Tips

  • Symfony Security: Works seamlessly with firewalls and providers. No manual session handling required.
  • APIs: For token-based auth (e.g., JWT), manually validate sessions in controllers:
    $this->sessionConcurrency->validateSession($request->getSession());
    
  • Testing: Use Ajgl\SessionConcurrencyBundle\Tests\* for edge cases (e.g., rapid logins, session hijacking).

Gotchas and Tips

Pitfalls

  1. Session Storage Assumptions:

    • The bundle assumes Symfony’s default session storage. For custom backends (e.g., Redis), implement SessionStorageInterface and ensure countSessions() accurately reflects active sessions.
    • Debugging: If sessions aren’t invalidated, verify session.save_handler in php.ini matches your storage backend.
  2. Configuration Overrides:

    • Bundle defaults may conflict with Symfony’s security.firewalls settings. Explicitly set max_sessions and session_name in config.
    • Symfony 5+: Some event names (e.g., SECURITY_INTERACTIVE_LOGIN) may require adjustments for newer Symfony versions.
  3. Race Conditions:

    • High-traffic apps may experience race conditions during session validation. Use transactions or locks in custom storage implementations.
  4. Caching:

    • Session counts are cached for performance. Clear cache manually if counts appear stale:
      $this->sessionConcurrency->getStorage()->clearCache();
      

Debugging Tips

  • Log Invalidations: Enable debug mode and check logs for ajgl.session_concurrency events.

    monolog:
        handlers:
            main:
                level: debug
    
  • Test with Multiple Tabs: Simulate concurrency by opening identical sessions in different browsers (e.g., Chrome + Firefox).

  • Check Session ID: Verify session_id() matches your session_name config. Mismatches cause silent failures.

Extension Points

  1. Custom Invalidators: Override the default invalidation logic by extending Ajgl\SessionConcurrency\SessionConcurrency:

    class CustomSessionConcurrency extends SessionConcurrency {
        protected function onSessionInvalidated(string $sessionId) {
            // Custom logic (e.g., send email to user)
        }
    }
    

    Register as a service:

    ajgl_session_concurrency.concurrency: '@custom_session_concurrency'
    
  2. Dynamic Max Sessions: Fetch max_sessions from a database or user profile:

    $maxSessions = $this->userRepository->getMaxSessions($user);
    $this->sessionConcurrency->setMaxSessions($maxSessions);
    
  3. Grace Periods: Add a "grace period" to delay invalidation (e.g., 5 minutes):

    $this->sessionConcurrency->setGracePeriod(300); // 5 minutes
    
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.
ilhamsyabani/laravel-volt-starter
thethunderturner/filament-latex
ghostcompiler/laravel-querybuilder
webrek/laravel-telescope-mongodb
anousss007/blatui
zatona-eg/zatona-eg-api
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat