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

Auth Logging Laravel Package

chrysanthos/auth-logging

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require chrysanthos/auth-logging
    php artisan migrate
    
    • Runs a single migration (create_auth_logs_table) to store failed login attempts.
  2. First Use Case:

    • Out-of-the-box: The package automatically logs failed login attempts (e.g., LoginController@login or LoginController@attemptLogin).
    • Manual Logging: Use the AuthLog::log() facade to manually log attempts:
      use Chrysanthos\AuthLogging\Facades\AuthLog;
      
      AuthLog::log($credentials, $ip, $userAgent);
      
  3. Where to Look First:

    • Config: config/auth-logging.php (if provided; check for customization options like log retention).
    • Migrations: database/migrations/[timestamp]_create_auth_logs_table.php (schema for auth_logs table).
    • Facade: Chrysanthos\AuthLogging\Facades\AuthLog (API reference).

Implementation Patterns

Core Workflows

  1. Automatic Logging:

    • The package hooks into Laravel’s AuthenticatesUsers trait (common in LoginController).
    • Failed attempts trigger AuthLog::log() automatically. No manual intervention needed for standard flows.
  2. Manual Logging:

    • Useful for custom auth logic (e.g., API tokens, SSO callbacks):
      try {
          $user = Auth::attempt($credentials);
      } catch (\Exception $e) {
          AuthLog::log($credentials, request()->ip(), request()->userAgent());
      }
      
  3. Querying Logs:

    • Access logs via Eloquent (assuming AuthLog model is published or auto-registered):
      use Chrysanthos\AuthLogging\Models\AuthLog;
      
      $failedAttempts = AuthLog::where('email', 'user@example.com')
          ->latest()
          ->limit(10)
          ->get();
      
  4. Integration with Events:

    • Listen for auth.failed events to enrich logs:
      use Chrysanthos\AuthLogging\Facades\AuthLog;
      use Illuminate\Auth\Events\Failed;
      
      Failed::listen(function (Failed $event) {
          AuthLog::log([
              'email' => $event->credentials->get('email'),
              'password' => '[redacted]',
          ], $event->request->ip(), $event->request->userAgent());
      });
      
  5. API/SPA Use:

    • Log failed API requests (e.g., POST /api/login):
      Route::post('/api/login', function () {
          $credentials = request()->only(['email', 'password']);
          if (!Auth::attempt($credentials)) {
              AuthLog::log($credentials, request()->ip(), request()->header('User-Agent'));
              return response()->json(['error' => 'Invalid credentials'], 401);
          }
      });
      
  6. Bulk Actions:

    • Clear old logs via Artisan:
      php artisan auth-logging:purge --days=30
      
    • (Check if the package includes this command; if not, create a custom Artisan command.)

Gotchas and Tips

Pitfalls

  1. Password Storage:

    • Gotcha: The package logs raw credentials (including passwords) by default. This is a security risk if logs are exposed.
    • Fix: Redact passwords in logs:
      AuthLog::log([
          'email' => $credentials['email'],
          'password' => '[redacted]',
      ], $ip, $userAgent);
      
    • Alternative: Use a custom model to hash/store only hashes (e.g., password_hash column).
  2. Missing Config:

    • Gotcha: No published config file in the README. Check for:
      • Log retention policies (e.g., auto-purge old entries).
      • Custom table names or model bindings.
    • Workaround: Publish the config if available:
      php artisan vendor:publish --tag=auth-logging-config
      
  3. Event Hooks:

    • Gotcha: Automatic logging may not trigger for all auth failures (e.g., custom guards or API tokens).
    • Tip: Explicitly log in handleUserAttemptingAuthenticate or validateCredentials methods.
  4. Performance:

    • Gotcha: Logging every failed attempt could slow down high-traffic endpoints.
    • Tip: Throttle logs (e.g., only log after 3 failed attempts):
      if (Auth::hasTooManyLoginAttempts($request)) {
          AuthLog::log($credentials, $ip, $userAgent);
      }
      
  5. Database Schema:

    • Gotcha: Default schema may lack critical fields (e.g., failed_at timestamp, guard name).
    • Tip: Extend the migration:
      Schema::table('auth_logs', function (Blueprint $table) {
          $table->string('guard')->default('web');
          $table->timestamp('failed_at')->useCurrent();
      });
      
  6. Testing:

    • Gotcha: Tests may not cover edge cases (e.g., null user agents, malformed IPs).
    • Tip: Write feature tests:
      public function test_failed_login_logs_credentials()
      {
          $response = $this->post('/login', ['email' => 'test@example.com', 'password' => 'wrong']);
          $this->assertDatabaseHas('auth_logs', [
              'email' => 'test@example.com',
          ]);
      }
      

Pro Tips

  1. Enrich Logs:

    • Add metadata like device_info or location (via IP geolocation):
      AuthLog::log($credentials, $ip, $userAgent, [
          'location' => $this->getLocationFromIp($ip),
      ]);
      
  2. Alerting:

    • Integrate with Laravel Notifications to alert admins of brute-force attempts:
      if ($attempts > 5) {
          AuthLog::log($credentials, $ip, $userAgent);
          $admin->notify(new BruteForceAlert($ip, $credentials['email']));
      }
      
  3. Custom Models:

    • Extend the AuthLog model to add scopes:
      namespace App\Models;
      
      use Chrysanthos\AuthLogging\Models\AuthLog as BaseAuthLog;
      
      class AuthLog extends BaseAuthLog
      {
          public function scopeForIp($query, $ip)
          {
              return $query->where('ip', $ip);
          }
      }
      
  4. API Responses:

    • Use logs to customize error messages (e.g., "Account locked after 5 attempts"):
      if (AuthLog::where('email', $email)->count() > 4) {
          return response()->json(['error' => 'Too many attempts'], 429);
      }
      
  5. Audit Trails:

    • Combine with spatie/laravel-activitylog to track admin actions on failed logins:
      event(new Failed($event->user, $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.
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
atriumphp/atrium