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

Laravel Auth Laravel Package

cetria/laravel-auth

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require cetria/laravel-auth
    

    Publish the package configuration:

    php artisan vendor:publish --provider="Cetria\LaravelAuth\AuthServiceProvider" --tag="config"
    
  2. Configuration

    • Edit config/auth.php (published by the package) to define:
      • api_guard (default: sanctum)
      • token_lifetime (default: 1440 minutes)
      • Custom endpoints (e.g., login, refresh, logout routes).
  3. First Use Case Register a route in routes/api.php:

    Route::post('/auth/login', [\Cetria\LaravelAuth\Http\Controllers\AuthController::class, 'login']);
    

    Test with a POST request to /auth/login with credentials:

    {
        "email": "user@example.com",
        "password": "password123"
    }
    

    The response will include a token and token_type (e.g., Bearer).


Implementation Patterns

Workflows

  1. Token-Based Authentication

    • Use the AuthController to handle:
      • login(): Issues a Sanctum/Bearer token.
      • refresh(): Extends token validity (if configured).
      • logout(): Revokes the token.
    • Example middleware usage:
      Route::middleware(['auth:sanctum'])->group(function () {
          Route::get('/profile', [UserController::class, 'show']);
      });
      
  2. Customization

    • Override default responses by extending the AuthController:
      namespace App\Http\Controllers;
      
      use Cetria\LaravelAuth\Http\Controllers\AuthController as BaseAuthController;
      
      class AuthController extends BaseAuthController
      {
          public function login()
          {
              $response = parent::login();
              return $response->withAdditionalData(['custom_field' => 'value']);
          }
      }
      
    • Modify token payload via config/auth.php:
      'token_payload' => [
          'user_id',
          'username',
          'custom_metadata' => 'value',
      ],
      
  3. Integration with Sanctum

    • Leverage Sanctum’s built-in features (e.g., HasApiTokens trait) alongside the package.
    • Example user model:
      use Laravel\Sanctum\HasApiTokens;
      
      class User extends Authenticatable
      {
          use HasApiTokens;
      }
      
  4. Rate Limiting

    • Apply rate limiting to auth endpoints in app/Http/Kernel.php:
      'auth' => ['throttle:60,1'],
      

Gotchas and Tips

Pitfalls

  1. Token Revocation

    • Sanctum tokens are not automatically revoked on logout. Manually revoke via:
      $user->currentAccessToken()->delete();
      
    • For bulk revocation, use Sanctum’s revoke() helper:
      Sanctum::revoke($token);
      
  2. Configuration Overrides

    • Ensure config/auth.php is merged correctly. Use php artisan config:clear if changes aren’t reflected.
    • Default guard (sanctum) must match the guard in config/auth.php and app/Http/Kernel.php.
  3. CORS Issues

    • Sanctum requires CORS headers. Configure in config/cors.php:
      'paths' => ['api/*', 'sanctum/csrf-cookie'],
      'allowed_methods' => ['*'],
      'allowed_origins' => ['*'],
      

Debugging

  • Token Validation Errors

    • Check Sanctum’s HasApiTokens trait for token validation logic.
    • Enable Sanctum debugging:
      Sanctum::debugging();
      
    • Log token payloads:
      \Log::info('Token payload:', $user->createToken('name')->plainTextToken);
      
  • Custom Payloads

    • If token_payload in config is ignored, verify the AuthController is not overriding it. Extend the controller to debug:
      public function login()
      {
          \Log::info('Payload before:', $this->getTokenPayload());
          $response = parent::login();
          return $response;
      }
      

Extension Points

  1. Custom Auth Logic

    • Override AuthController methods (e.g., validateCredentials) for custom validation:
      protected function validateCredentials(array $credentials)
      {
          return User::where('email', $credentials['email'])
              ->where('password', $credentials['password'])
              ->where('account_status', 'active')
              ->exists();
      }
      
  2. Multi-Guard Support

    • Extend the package to support additional guards (e.g., passport):
      // In AuthServiceProvider
      $this->app['auth']->extend('passport', function ($app) {
          return new PassportGuard($app['auth']->createUserProvider(), $app['request']);
      });
      
  3. Event Listeners

    • Listen for auth events (e.g., auth.login, auth.logout) in EventServiceProvider:
      protected $listen = [
          'auth.login' => [
              \App\Listeners\LogAuthAttempt::class,
          ],
      ];
      
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