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

gestazion/laravel-auth-checker

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation

    composer require gestazion/laravel-auth-checker
    php artisan vendor:publish --provider="Gestazion\AuthChecker\AuthCheckerServiceProvider" --tag="migrations"
    php artisan migrate
    
    • Run php artisan auth-checker:install (if provided) to set up default configurations.
  2. Configuration

    • Publish the config file:
      php artisan vendor:publish --provider="Gestazion\AuthChecker\AuthCheckerServiceProvider" --tag="config"
      
    • Review config/auth-checker.php for:
      • log_auth_attempts: Enable/disable logging failed/successful attempts.
      • lock_after_attempts: Set max failed attempts before locking an account.
      • lock_duration: Duration (in minutes) for account lockout.
      • allowed_ips: Whitelist IPs for bypassing checks (e.g., admin panels).
  3. First Use Case: Logging Auth Attempts

    • Enable logging in config/auth-checker.php:
      'log_auth_attempts' => true,
      
    • Test by attempting to log in via POST /login. Check the auth_attempts table for records.

Implementation Patterns

Core Workflows

  1. Logging Authentication Events

    • The package automatically logs attempts (successful/failed) to the auth_attempts table.
    • Manual Logging (if needed):
      use Gestazion\AuthChecker\Facades\AuthChecker;
      
      AuthChecker::logAttempt($user, $isSuccessful, $ipAddress, $userAgent);
      
  2. Locking Accounts After Failed Attempts

    • Configure lock_after_attempts and lock_duration in the config.
    • Example: Lock after 5 failed attempts for 30 minutes.
      'lock_after_attempts' => 5,
      'lock_duration' => 30,
      
    • Check if Locked:
      if (AuthChecker::isLocked($user)) {
          abort(429, 'Account locked. Try again later.');
      }
      
  3. IP-Based Restrictions

    • Restrict logins to specific IPs (e.g., corporate networks):
      'allowed_ips' => ['192.168.1.0/24', '10.0.0.5'],
      
    • Bypass for Admins:
      if (auth()->user()->isAdmin()) {
          AuthChecker::allowIp($ipAddress);
      }
      
  4. Customizing Lockout Responses

    • Override the default lockout response in your LoginController:
      public function login(Request $request)
      {
          if (AuthChecker::isLocked($request->user())) {
              return back()->withError('Account locked. Contact support.');
          }
          // ... rest of login logic
      }
      
  5. Device Tracking

    • Log devices (IP, user agent) for each attempt:
      AuthChecker::logDevice($user, $ip, $userAgent);
      
    • Query devices:
      $devices = AuthChecker::getUserDevices($user);
      
  6. Integration with Laravel Events

    • Listen for auth.attempting, auth.failed, and auth.successful events:
      Auth::attempting(function ($request) {
          AuthChecker::logAttempt($request->user(), false, $request->ip());
      });
      

Advanced Patterns

  1. Customizing the Auth Attempts Table

    • Extend the AuthAttempt model (e.g., add location or device_type):
      php artisan make:model AuthAttemptExtension --extend=Gestazion\AuthChecker\Models\AuthAttempt
      
    • Publish and modify the migration:
      php artisan vendor:publish --tag="auth-checker-migrations"
      
  2. Rate Limiting with Throttle

    • Combine with Laravel’s throttle middleware for additional protection:
      Route::post('/login', [LoginController::class, 'login'])
           ->middleware(['throttle:5,1']);
      
  3. Two-Factor Authentication (2FA) Integration

    • Log 2FA attempts separately:
      AuthChecker::logTwoFactorAttempt($user, $isSuccessful, $ipAddress);
      
  4. Exporting Logs

    • Create a scheduled job to export logs to a secure storage:
      use Gestazion\AuthChecker\Facades\AuthChecker;
      
      AuthChecker::exportLogsToStorage($user, 'csv');
      

Gotchas and Tips

Pitfalls

  1. Database Overhead

    • Logging every attempt can bloat the database. Tip: Use Laravel’s queue to defer logging:
      AuthChecker::queueLogAttempt($user, $isSuccessful, $ipAddress);
      
  2. IP Spoofing

    • Attackers can spoof IPs. Tip: Combine with user_agent and geolocation (e.g., using geoip-database):
      AuthChecker::logAttempt($user, false, $ip, $userAgent, $country);
      
  3. Lockout Loops

    • Users might get locked out permanently if lock_duration is too long. Tip:
      • Add an "unlock" endpoint:
        public function unlock(Request $request) {
            AuthChecker::unlock($request->user());
            return back()->with('status', 'Account unlocked!');
        }
        
      • Or use a temporary lock flag.
  4. Config Caching

    • Changes to config/auth-checker.php require cache clearing:
      php artisan config:clear
      
  5. Middleware Conflicts

    • If using auth middleware, ensure AuthChecker runs before session validation:
      // app/Http/Middleware/Authenticate.php
      public function handle($request, Closure $next, ...$guards) {
          if (AuthChecker::isLocked($request->user())) {
              abort(429);
          }
          return $next($request);
      }
      

Debugging Tips

  1. Check Logs

    • Enable Laravel’s debug mode and check storage/logs/laravel.log for AuthChecker events.
  2. Test Lockout Manually

    • Simulate failed attempts:
      php artisan tinker
      >>> $user = User::first();
      >>> AuthChecker::lock($user, 5, 30); // Lock for 5 attempts, 30 mins
      
  3. Verify Database Records

    • Inspect auth_attempts:
      SELECT * FROM auth_attempts WHERE user_id = 1 ORDER BY created_at DESC;
      
  4. Disable Logging Temporarily

    • Set 'log_auth_attempts' => false in config to debug without cluttering logs.

Extension Points

  1. Custom Lockout Notifications

    • Extend the AuthChecker facade to send emails/SMS on lockout:
      AuthChecker::extend(function ($checker) {
          $checker->onLock(function ($user) {
              Mail::to($user)->send(new AccountLocked($user));
          });
      });
      
  2. Custom Validation Rules

    • Add rules to AuthChecker for device fingerprinting (e.g., using laravel-fingerprint):
      AuthChecker::validateDevice($user, $fingerprint);
      
  3. API-Specific Logic

    • Override behavior for API routes:
      if ($request->is('api/*')) {
          AuthChecker::setApiMode(true); // Stricter checks
      }
      
  4. Third-Party Integrations

    • Sync with SIEM tools (e.g., Splunk) or monitoring services:
      AuthChecker::onFailedAttempt(function ($attempt) {
          // Send to SIEM
          $siem->log($attempt);
      });
      

Pro Tips

  • Use Queues for Heavy Logs: Offload logging to a queue to avoid slowing down auth requests.
  • Monitor with Laravel Horizon: Track failed attempts in real-time.
  • Combine with laravel-activitylog: Correlate auth events with other user actions.
  • A/B Test Lockout Policies: Use different lock_after_attempts for user segments (e.g., admins vs. regular users).
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