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

Sphinx Laravel Package

hans-thomas/sphinx

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require hans-thomas/sphinx
    php artisan vendor:publish --tag=sphinx-config
    

    Publish the config and publish migrations (if using database-backed tokens):

    php artisan vendor:publish --tag=sphinx-migrations
    php artisan migrate
    
  2. Model Integration: Apply the SphinxTrait to your User model (or equivalent):

    use Hans\Sphinx\Traits\SphinxTrait;
    
    class User extends Authenticatable
    {
        use SphinxTrait;
    
        // Implement required abstract methods
        public function getJwtIdentifier(): string { return $this->id; }
        public function getJwtClaims(): array { return ['sub' => $this->id]; }
        public function getJwtCustomClaims(): array { return []; }
    }
    
  3. First Authentication Flow:

    • Generate tokens via the Sphinx facade:
      use Hans\Sphinx\Facades\Sphinx;
      
      $tokens = Sphinx::generateTokens($user);
      // Returns ['access_token' => '...', 'refresh_token' => '...']
      
    • Validate incoming requests:
      $user = Sphinx::authenticate(); // Throws exception if invalid
      

Implementation Patterns

Core Workflows

  1. Token Generation & Issuance:

    • Standard Flow:
      $tokens = Sphinx::generateTokens($user, [
          'expires_in' => 3600, // Custom TTL (default: config)
          'refresh_ttl' => 86400,
      ]);
      
    • Refresh Tokens:
      $newAccessToken = Sphinx::refreshToken($refreshToken);
      
  2. Middleware Integration: Use the provided middleware (Sphinx::middleware()) in app/Http/Kernel.php:

    protected $routeMiddleware = [
        'auth.sphinx' => \Hans\Sphinx\Http\Middleware\Authenticate::class,
    ];
    

    Apply to routes:

    Route::middleware('auth.sphinx')->group(function () {
        // Protected routes
    });
    
  3. Custom Claims & Metadata: Extend claims dynamically:

    public function getJwtCustomClaims(): array {
        return [
            'roles' => $this->roles->pluck('name'),
            'permissions' => $this->permissions,
        ];
    }
    
  4. Horus Integration (if used):

    // Sync with Horus (e.g., for multi-account management)
    Sphinx::syncWithHorus($userId, $accountId);
    

Advanced Patterns

  1. Token Revocation:

    • Blacklist Tokens (if using database):
      Sphinx::revokeToken($token);
      
    • Stateless Revocation (via custom claims):
      $user->markTokenAsRevoked($token); // Custom logic
      
  2. Multi-Tenancy: Add tenant context to claims:

    public function getJwtCustomClaims(): array {
        return ['tenant_id' => auth()->tenant()->id];
    }
    
  3. Rate Limiting: Combine with Laravel’s throttle middleware:

    Route::middleware(['throttle:60,1', 'auth.sphinx'])->group(...);
    
  4. Testing: Use the SphinxTestCase helper:

    use Hans\Sphinx\Testing\SphinxTestCase;
    
    class UserTest extends SphinxTestCase {
        public function testAuthentication() {
            $tokens = $this->generateTokens($this->user);
            $this->assertAuthenticatedAs($this->user);
        }
    }
    

Gotchas and Tips

Common Pitfalls

  1. Double Hooks:

    • Issue: Forgetting to call self::sphinxHooks() in booted() causes token generation to fail.
    • Fix: Always include:
      protected static function booted() {
          static::sphinxHooks();
      }
      
  2. Clock Skew:

    • Issue: Tokens may fail validation if server time differs from token issuance time.
    • Fix: Configure JWT_LEEWAY in .env (e.g., JWT_LEEWAY=30).
  3. Refresh Token Exhaustion:

    • Issue: Refresh tokens may be revoked before use.
    • Fix: Implement a short-lived access token (e.g., 15–30 mins) with long-lived refresh tokens.
  4. Custom Claims Serialization:

    • Issue: Non-serializable data in getJwtCustomClaims() throws errors.
    • Fix: Ensure all claims are JSON-serializable (e.g., convert DateTime to strings).

Debugging Tips

  1. Token Decoding: Use the Sphinx facade to inspect tokens:

    $decoded = Sphinx::decodeToken($token);
    dd($decoded);
    
  2. Logging: Enable debug logging in config/sphinx.php:

    'debug' => env('SPHINX_DEBUG', false),
    
  3. Token Expiry: Check expiry claims manually:

    $expiry = Sphinx::getTokenExpiry($token);
    

Extension Points

  1. Custom Encryption: Override the default encryption layers in config/sphinx.php:

    'encryption' => [
        'key' => env('SPHINX_ENCRYPTION_KEY'),
        'algorithm' => 'AES-256-CBC', // Custom algorithm
    ],
    
  2. Event Listeners: Listen to token events (e.g., TokenGenerated, TokenRevoked):

    Sphinx::listen('TokenGenerated', function ($event) {
        // Log or sync with external systems
    });
    
  3. Guard Integration: Extend Laravel’s auth guard for Sphinx:

    // In AuthServiceProvider
    $this->app['auth']->extend('sphinx', function ($app) {
        return new SphinxGuard($app['request']);
    });
    
  4. Database Backend: Customize the token storage table by publishing and modifying migrations:

    php artisan vendor:publish --tag=sphinx-migrations
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity