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 Authentication Log Laravel Package

rappasoft/laravel-authentication-log

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require rappasoft/laravel-authentication-log
    php artisan vendor:publish --provider="Rappasoft\LaravelAuthenticationLog\LaravelAuthenticationLogServiceProvider" --tag="authentication-log-migrations"
    php artisan migrate
    
  2. Add Trait to User Model:

    use Rappasoft\LaravelAuthenticationLog\Traits\AuthenticationLoggable;
    
    class User extends Authenticatable
    {
        use AuthenticationLoggable;
    }
    
  3. First Use Case: Immediately start tracking logins/logouts by attempting to authenticate a user. The package will automatically log:

    • IP address
    • User agent
    • Device fingerprint
    • Timestamps
    • Location (if GeoIP is configured)

Where to Look First

  • Configuration: config/authentication-log.php (publish with --tag="authentication-log-config")
  • Migrations: database/migrations/[timestamp]_create_authentication_logs_table.php
  • Models: app/Models/AuthenticationLog.php (if extending)
  • Artisan Commands: php artisan list (look for authentication-log:* commands)

Implementation Patterns

Core Workflows

Authentication Logging

// Automatic - No manual intervention needed
// Logs are created on successful/failed login attempts
// Access logs via:
$user->authenticationLogs()->latest()->first();

Device Management

// Trust a device (e.g., after user verification)
$user->trustDevice($deviceId);

// Get all devices
$devices = $user->getDevices();

// Check if current device is trusted
if ($user->isDeviceTrusted()) {
    // Proceed with sensitive actions
}

Session Management

// In a controller after login
$user->revokeAllOtherSessions(request()->ip()); // Keep current session

// In admin panel
$activeSessions = $user->getActiveSessions();
foreach ($activeSessions as $session) {
    if ($session->is_suspicious) {
        $user->revokeSession($session->id);
    }
}

Suspicious Activity

// Check for suspicious activity during login
$suspicious = $user->detectSuspiciousActivity();
if ($suspicious) {
    notify($user, new SuspiciousActivityDetected($suspicious));
}

Integration Patterns

Middleware Integration

// routes/web.php
Route::middleware(['auth', 'trusted.device'])->group(function () {
    // Routes requiring trusted devices
});

Notification Integration

// config/notifications.php
'channels' => [
    'slack' => [
        'driver' => 'slack',
        // Configure Slack webhook
    ],
],

Query Scopes

// In a controller or service
$recentFailedAttempts = AuthenticationLog::failed()
    ->recent(24)
    ->forUser($user)
    ->get();

Webhook Integration

// config/authentication-log.php
'webhooks' => [
    [
        'url' => env('AUTH_LOG_WEBHOOK_URL'),
        'events' => ['login', 'failed', 'new_device'],
        'secret' => env('AUTH_LOG_WEBHOOK_SECRET'),
    ],
],

Command Scheduling

// app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
    $schedule->command('authentication-log:purge')->daily();
    $schedule->command('authentication-log:export:failed-attempts')->weekly();
}

Gotchas and Tips

Common Pitfalls

  1. Duplicate Log Entries:

    • Issue: Session restoration or remember-me cookies can create duplicates.
    • Fix: Configure prevent_session_restoration_logging in config to true (default in v6+).
    • Debug: Check is_session_restoration flag in logs.
  2. GeoIP Configuration:

    • Issue: Missing GeoIP data if not properly configured.
    • Fix: Install torann/geoip and configure in config/authentication-log.php:
      'geoip' => [
          'enabled' => true,
          'database' => database_path('GeoLite2-City.mmdb'),
      ],
      
  3. Device Fingerprinting:

    • Issue: False positives with similar user agents.
    • Fix: Normalize browser versions in config:
      'device_fingerprint' => [
          'normalize_browser_versions' => true,
      ],
      
  4. Notification Spam:

    • Issue: Too many alerts for legitimate activity.
    • Fix: Adjust rate limits in config:
      'notifications' => [
          'rate_limit' => 3, // per hour
      ],
      
  5. Performance with Large Logs:

    • Issue: Slow queries on tables with millions of entries.
    • Fix:
      • Schedule regular purging: php artisan authentication-log:purge
      • Add indexes to frequently queried columns:
        Schema::table('authentication_logs', function (Blueprint $table) {
            $table->index('user_id');
            $table->index('ip_address');
            $table->index(['user_id', 'created_at']);
        });
        

Debugging Tips

  1. Log Inspection:

    // Check raw fingerprint data
    $fingerprintData = $user->getLastLogin()->fingerprint_data;
    
    // Debug GeoIP
    \Torann\GeoIP\Facades\GeoIP::getLocation(request()->ip());
    
  2. Suspicious Activity:

    // Dump suspicious reasons
    dd($user->detectSuspiciousActivity());
    
  3. Webhook Testing:

    • Use telescope or laravel-debugbar to inspect outgoing requests.
    • Test with curl:
      curl -X POST -H "Content-Type: application/json" \
           -d '{"event":"login","data":{...}}' \
           http://your-webhook-url
      

Extension Points

  1. Custom Log Fields:

    // Extend the log model
    class AuthenticationLog extends \Rappasoft\LaravelAuthenticationLog\Models\AuthenticationLog
    {
        protected $casts = [
            'custom_field' => 'boolean',
        ];
    }
    
  2. Custom Suspicious Activity Rules:

    // Extend the suspicious activity detector
    class CustomSuspiciousActivityDetector extends \Rappasoft\LaravelAuthenticationLog\Services\SuspiciousActivityDetector
    {
        public function detectCustomRule(User $user)
        {
            // Implement custom logic
            return $this->createSuspiciousActivity('custom_rule', 'Custom suspicious activity detected');
        }
    }
    
  3. Custom Notifications:

    // Create a custom notification
    class NewDeviceLoginNotification extends Notification
    {
        public function via($notifiable)
        {
            return ['mail', 'slack'];
        }
    }
    
    // Override in config
    'notifications' => [
        'new_device' => \App\Notifications\NewDeviceLoginNotification::class,
    ],
    
  4. Custom Query Scopes:

    // Add to AuthenticationLog model
    public function scopeFromCountry($query, $countryCode)
    {
        return $query->where('country_code', $countryCode);
    }
    

Configuration Quirks

  1. Session Restoration Window:

    • Default: 5 minutes (configurable via session_restoration_window_minutes).
    • Set to 0 to disable entirely.
  2. Device Trust Defaults:

    • New devices are marked as untrusted by default.
    • Trusted devices bypass suspicious activity checks for their sessions.
  3. Failed Login Notifications:

    • Disabled by default for security (to avoid alerting attackers).
    • Enable with:
      'notifications' => [
          'failed_login' => true,
      ],
      
  4. Webhook Events:

    • Available events: login, logout, failed, new_device, suspicious.
    • Add/remove as needed in config.
  5. Export Formatting:

    • CSV exports use UTF-8 encoding by default.
    • JSON exports include all model attributes by default (filter via hidden in model).
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony