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

harryes/laravel-sentinellog

All-in-one Laravel security and auth logging package: tracks login/logout/failed attempts with device + geo detection, alerts, TOTP 2FA, session management, brute-force protection, geo-fencing, SSO, and new-location verify/deny flows.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require harryes/laravel-sentinellog
    php artisan vendor:publish --provider="Harryes\SentinelLog\SentinelLogServiceProvider" --tag="migrations"
    php artisan migrate
    

    Publish the config file:

    php artisan vendor:publish --provider="Harryes\SentinelLog\SentinelLogServiceProvider" --tag="config"
    
  2. Configuration: Edit config/sentinel-log.php to enable/disable features (e.g., geo_fencing, brute_force_protection). Set default values for:

    'max_failed_attempts' => 5,
    'lockout_duration' => 15, // minutes
    'allowed_countries' => ['US', 'GB'], // ISO country codes
    
  3. First Use Case: Enable logging in AuthServiceProvider:

    use Harryes\SentinelLog\Facades\SentinelLog;
    
    public function boot()
    {
        SentinelLog::enable();
    }
    

    Test by attempting a login (successful or failed). Check the sentinel_logs table for entries.


Implementation Patterns

Core Workflows

  1. Authentication Logging:

    • Login/Logout: Automatically logged via middleware. Extend SentinelLogMiddleware if custom logic is needed.
      // app/Http/Middleware/Authenticate.php
      public function handle($request, Closure $next)
      {
          SentinelLog::logLogin($request->user());
          return $next($request);
      }
      
    • Failed Attempts: Logged via SentinelLog::logFailedAttempt($request, $credentials).
  2. Device & Geolocation Tracking:

    • Use SentinelLog::trackDevice($request) in middleware to capture:
      • User agent, IP, country (via geoip-database/geoip).
    • Example middleware:
      public function handle($request, Closure $next)
      {
          SentinelLog::trackDevice($request);
          return $next($request);
      }
      
  3. 2FA Integration:

    • Enable in config: '2fa' => true.
    • Use SentinelLog::verify2FA($user) to trigger TOTP verification.
    • Generate QR codes with:
      use Harryes\SentinelLog\Facades\SentinelLog;
      $qrCode = SentinelLog::generate2FAQR($user);
      
  4. Session Management:

    • Detect hijacking by comparing stored device/location with current request:
      if (!SentinelLog::isTrustedSession($request)) {
          auth()->logout();
          return redirect()->route('login')->with('error', 'Session hijacked!');
      }
      
  5. Brute Force Protection:

    • Configure max_failed_attempts and lockout_duration.
    • Check if an IP is locked:
      if (SentinelLog::isIPLocked($request->ip())) {
          return back()->with('error', 'Too many attempts. Try again later.');
      }
      
  6. Geo-Fencing:

    • Restrict logins to specific countries:
      if (!SentinelLog::isAllowedCountry($request->ip())) {
          return back()->with('error', 'Login restricted in your region.');
      }
      
  7. SSO Support:

    • Generate/validate tokens:
      $token = SentinelLog::generateSSOToken($user);
      SentinelLog::validateSSOToken($token);
      
  8. New Location Verification:

    • Enable 'new_location_verification' => true.
    • Users receive emails with verification links for unrecognized logins.

Integration Tips

  • Notifications:

    • Customize notifications by publishing views:
      php artisan vendor:publish --provider="Harryes\SentinelLog\SentinelLogServiceProvider" --tag="views"
      
    • Extend Harryes\SentinelLog\Events\LoginEvent to trigger custom logic.
  • APIs:

    • Use SentinelLog::getUserLogs($user) to fetch activity in APIs:
      return response()->json(SentinelLog::getUserLogs(auth()->user()));
      
  • Admin Dashboard:

    • Query logs for suspicious activity:
      $failedAttempts = SentinelLog::failedAttempts()->latest()->take(10)->get();
      
  • Testing:

    • Mock SentinelLog in tests:
      $this->partialMock(SentinelLog::class, ['logLogin']);
      

Gotchas and Tips

Pitfalls

  1. GeoIP Database:

    • Requires geoip-database/geoip package. Install separately:
      composer require geoip-database/geoip
      
    • Update the database manually:
      php artisan sentinellog:update-geoip
      
  2. Rate Limiting:

    • Brute force protection uses Laravel’s rate limiter. Ensure config/rate-limiting.php is configured for high traffic:
      'default' => [
          'maxAttempts' => 100,
      ],
      
  3. Session Hijacking:

    • isTrustedSession() compares stored device/location. False positives may occur with VPNs/proxies. Whitelist known IPs in config:
      'trusted_ips' => ['192.168.1.1'],
      
  4. 2FA Setup:

    • Users must scan QR codes to enable 2FA. Provide fallback recovery codes:
      $recoveryCodes = SentinelLog::generate2FARecoveryCodes($user);
      
  5. Performance:

    • Logging every request can impact performance. Use SentinelLog::disable() in non-critical routes:
      SentinelLog::disable();
      // Non-logged route
      SentinelLog::enable();
      
  6. Database Bloat:

    • Logs accumulate over time. Add a cleanup job:
      // app/Console/Commands/CleanupSentinelLogs.php
      public function handle()
      {
          SentinelLog::cleanupLogs(Carbon::now()->subDays(30));
      }
      

Debugging

  1. Log Queries:

    • Enable query logging in config/sentinel-log.php:
      'debug' => true,
      
    • Check storage/logs/laravel.log for SQL queries.
  2. GeoIP Issues:

    • Verify the GeoIP database path in config:
      'geoip_database' => database_path('GeoLite2-Country.mmdb'),
      
    • Download the latest database from MaxMind.
  3. Failed Logins:

    • Ensure failed events are logged in app/Providers/AuthServiceProvider.php:
      public function boot()
      {
          $this->app['auth.failed'] = function ($request, $credentials) {
              SentinelLog::logFailedAttempt($request, $credentials);
          };
      }
      
  4. Notifications:

    • Test email notifications with:
      php artisan sentinellog:test-notification
      

Extension Points

  1. Custom Log Fields:

    • Extend the sentinel_logs table by publishing migrations:
      php artisan vendor:publish --provider="Harryes\SentinelLog\SentinelLogServiceProvider" --tag="migrations"
      
    • Add fields to config/sentinel-log.php:
      'custom_fields' => ['custom_field' => 'string'],
      
  2. Custom Events:

    • Listen for events like Harryes\SentinelLog\Events\LoginEvent:
      Event::listen(LoginEvent::class, function ($event) {
          // Custom logic (e.g., Slack alert)
      });
      
  3. Override Views:

    • Publish and modify views:
      php artisan vendor:publish --provider="Harryes\SentinelLog\SentinelLogServiceProvider" --tag="views"
      
    • Override 2fa-setup.blade.php or login-notification.blade.php.
  4. API Extensions:

    • Add custom endpoints for logs:
      Route::get('/api/user/logs', function () {
          return SentinelLog::getUserLogs(auth()->user());
      });
      
  5. Conditional Logging:

    • Disable logging for specific routes:
      Route::middleware(['web', 'sentinel-log:disable'])->group(function () {
          // Routes where logging is disabled
      });
      
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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