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 Checker Laravel Package

lab404/laravel-auth-checker

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation

    composer require lab404/laravel-auth-checker
    php artisan vendor:publish --provider="Lab404\AuthChecker\AuthCheckerServiceProvider" --tag="migrations"
    php artisan migrate
    
    • Run migrations to create auth_checker_logs and auth_checker_devices tables.
  2. Configuration

    • Publish the config file:
      php artisan vendor:publish --provider="Lab404\AuthChecker\AuthCheckerServiceProvider" --tag="config"
      
    • Key settings in config/auth-checker.php:
      • lockout_threshold: Number of failed attempts before lockout (default: 5).
      • lockout_duration: Duration of lockout in minutes (default: 15).
      • log_successful_attempts: Track successful logins (default: true).
      • log_ip_address: Track IP addresses (default: true).
  3. First Use Case: Logging Logins

    • The package auto-magically logs logins/failed attempts via Laravel’s Auth events.
    • No manual intervention required—just install and use.

Implementation Patterns

1. Tracking Authentication Events

  • Automatic Logging: The package listens to Laravel’s attempting, authenticated, and failed events.
    // Example: Manually trigger logging (if needed)
    use Lab404\AuthChecker\Facades\AuthChecker;
    
    AuthChecker::logAttempt($user, $credentials, $isSuccessful);
    
  • Custom Events: Extend functionality by listening to auth.checker.logged or auth.checker.failed.

2. Device Tracking

  • Auto-Detection: Devices (IP, user agent, etc.) are auto-recorded on login.
  • Manual Override:
    AuthChecker::logDevice($user, [
        'ip' => $request->ip(),
        'user_agent' => $request->userAgent(),
        'location' => 'Custom Location',
    ]);
    

3. Lockout Management

  • Auto-Lockout: Users are locked after lockout_threshold failed attempts.
  • Manual Lock/Unlock:
    AuthChecker::lockUser($user, $durationMinutes = null); // Lock for X minutes
    AuthChecker::unlockUser($user); // Force-unlock
    
  • Check Lock Status:
    if (AuthChecker::isUserLocked($user)) {
        abort(403, 'Account locked due to too many failed attempts.');
    }
    

4. Querying Logs

  • Fetch User Logs:
    $logs = AuthChecker::getUserLogs($user);
    // Returns collection of attempts with timestamps, IPs, and success status.
    
  • Filter by Date/IP:
    $logs = AuthChecker::getLogs()
        ->where('created_at', '>', now()->subDays(7))
        ->where('ip_address', $request->ip())
        ->get();
    

5. Integration with Middleware

  • Protect Routes:
    use Lab404\AuthChecker\Middleware\CheckLockout;
    
    Route::middleware([CheckLockout::class])->group(function () {
        // Routes requiring lockout check
    });
    
  • Custom Middleware:
    public function handle($request, Closure $next) {
        if (AuthChecker::isUserLocked($request->user())) {
            return redirect()->route('account.locked');
        }
        return $next($request);
    }
    

6. Notifications

  • Failed Attempt Alerts:
    AuthChecker::failed($request, $user, $credentials)
        ->then(function ($log) {
            // Send email/notification on failed attempt
            Notification::send($user, new FailedLoginNotification($log));
        });
    

Gotchas and Tips

Pitfalls

  1. Migration Conflicts

    • If you’ve customized Laravel’s users table, ensure the auth_checker_logs table’s user_id foreign key matches your users.id column.
    • Fix: Run php artisan vendor:publish --tag="migrations" again and resolve conflicts manually.
  2. Lockout Bypassing

    • Users with is_admin = true (or similar) might bypass lockouts if not explicitly checked.
    • Solution: Add a middleware check:
      if ($request->user()->is_admin) {
          return $next($request);
      }
      
  3. IP Spoofing

    • Trusted proxies (e.g., Cloudflare) may hide real IPs. Configure trusted_proxies in AuthCheckerConfig:
      'trusted_proxies' => [
          '192.168.1.1',
          '10.0.0.1',
      ],
      
  4. Performance on Large Logs

    • Querying logs for users with thousands of attempts can be slow.
    • Optimization: Add indexes or paginate results:
      $logs = AuthChecker::getUserLogs($user)->paginate(10);
      

Debugging Tips

  1. Log Levels

    • Adjust config/auth-checker.php to log only critical events:
      'log_level' => 'critical', // Options: debug, info, warning, error, critical
      
  2. Event Debugging

    • Listen to events in EventServiceProvider:
      protected $listen = [
          'auth.attempting' => [
              'Lab404\AuthChecker\Listeners\LogAttemptListener',
          ],
      ];
      
  3. Clear Old Logs

    • Use a scheduled task to purge old logs:
      // app/Console/Commands/ClearAuthLogs.php
      AuthChecker::getLogs()->where('created_at', '<', now()->subMonths(6))->delete();
      

Extension Points

  1. Custom Fields

    • Extend the auth_checker_logs table via migrations:
      Schema::table('auth_checker_logs', function (Blueprint $table) {
          $table->string('custom_field')->nullable();
      });
      
    • Update the AuthCheckerLog model to cast the new field.
  2. Custom Lockout Logic

    • Override the lockout behavior by binding your own lockout handler:
      AuthChecker::extend(function ($app) {
          $app->bind('auth.checker.lockout', function () {
              return new CustomLockoutHandler();
          });
      });
      
  3. Webhook Notifications

    • Trigger webhooks on lockout events:
      AuthChecker::failed($request, $user)
          ->then(function () use ($user) {
              Http::post('https://your-webhook-url', [
                  'user_id' => $user->id,
                  'event' => 'lockout',
              ]);
          });
      
  4. Multi-Factor Auth (MFA) Integration

    • Skip lockout for MFA-protected logins:
      if ($request->user()->hasMfaEnabled()) {
          AuthChecker::skipLockout($request);
      }
      

Pro Tips

  • Combine with Laravel Fortify/Passport: Use auth.checker.logged to sync logins with OAuth providers.
  • Geolocation: Enrich logs with geolocation data using a package like spatie/laravel-geolocation.
  • Rate Limiting: Pair with laravel-rate-limiting to add CAPTCHA after X failed attempts.
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.
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
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope