定制 rappasoft/laravel-authentication-log 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

rappasoft/laravel-authentication-log

Composer 安装命令:

composer require rappasoft/laravel-authentication-log

包简介

Log user authentication details and send new device notifications.

README 文档

README

Package Logo

Latest Version on Packagist Total Downloads

Laravel Authentication Log is a comprehensive package which tracks your user's authentication information such as login/logout time, IP, Browser, Location, Device Fingerprint, etc. It sends out notifications via mail, slack, or SMS for new devices and failed logins, detects suspicious activity, provides session management, prevents duplicate log entries from session restorations, and much more.

Version 6.0.0 introduces major enhancements including session restoration prevention, improved device fingerprinting, enhanced statistics, and more. Version 6.1.0 adds Laravel 13.x support and compatibility with immutable date casting. See the Release Notes for complete details.

Features

Core Features

  • Authentication Logging - Tracks all login/logout attempts with IP, user agent, location, and timestamps
  • Device Fingerprinting - Reliable device identification using SHA-256 hashing with browser version normalization (prevents false positives)
  • New Device Detection - Automatically detects and notifies users of new device logins
  • Failed Login Tracking - Logs and optionally notifies users of failed login attempts
  • Location Tracking - Optional GeoIP integration for location data
  • Session Restoration Prevention - Automatically prevents duplicate log entries from page refreshes and remember me cookies

Advanced Features

  • 🔒 Suspicious Activity Detection - Automatically detects multiple failed logins, rapid location changes, and unusual login times
  • 📊 Statistics & Insights - Get comprehensive login statistics including total logins, failed attempts, unique devices, and more
  • 🔐 Session Management - View active sessions, revoke specific sessions, or logout all other devices
  • 🛡️ Device Trust Management - Mark devices as trusted, manage device names, and require trusted devices for sensitive actions
  • Rate Limiting - Prevents notification spam with configurable rate limits
  • 🔔 Webhook Support - Send webhooks to external services for authentication events
  • 📤 Export Functionality - Export authentication logs to CSV or JSON format
  • 🎯 Query Scopes - Powerful query scopes for filtering logs (successful, failed, suspicious, recent, by IP, by device, etc.)
  • 🚦 Middleware - Protect routes with trusted device middleware

Documentation, Installation, and Usage Instructions

See the documentation for detailed installation and usage instructions.

Version Compatibility

Laravel Authentication Log Features
8.x 1.x Basic logging only
9.x 2.x Basic logging only
10.x 3.x Basic logging only
11.x 5.x, 6.x All features (device fingerprinting, suspicious activity, webhooks, session management, etc.)
12.x 5.x, 6.x All features (device fingerprinting, suspicious activity, webhooks, session management, etc.)
13.x 6.1+ All features (device fingerprinting, suspicious activity, webhooks, session management, etc.)

Note: Version 6.1+ requires Laravel 11.x, 12.x, or 13.x and PHP 8.2+. Version 5.x also supports Laravel 11.x and 12.x. For Laravel 10.x support, please use version 3.x.

Installation

composer require rappasoft/laravel-authentication-log

Quick Start

1. Add the Trait to Your User Model

use Rappasoft\LaravelAuthenticationLog\Traits\AuthenticationLoggable;

class User extends Authenticatable
{
    use AuthenticationLoggable;
}

2. Publish and Run Migrations

For new installations:

php artisan vendor:publish --provider="Rappasoft\LaravelAuthenticationLog\LaravelAuthenticationLogServiceProvider" --tag="authentication-log-migrations"
php artisan migrate

For existing installations (upgrading from v5.x or earlier):

# Update the package
composer update rappasoft/laravel-authentication-log

# Publish the upgrade migration (if upgrading from v3.x or earlier)
php artisan vendor:publish --provider="Rappasoft\LaravelAuthenticationLog\LaravelAuthenticationLogServiceProvider" --tag="authentication-log-migrations"

# Run the migrations (the upgrade migration will only add columns if they don't exist)
php artisan migrate

Important: If upgrading from v3.x or earlier, the upgrade migration will safely add the new columns (device_id, device_name, is_trusted, last_activity_at, is_suspicious, suspicious_reason) to your existing authentication_log table without affecting existing data.

Breaking Changes in v6.0.0:

  • Laravel 10.x support was dropped (v6.1+ supports Laravel 11.x, 12.x, and 13.x)
  • PHP 8.1+ was required (PHP 8.2+ as of v6.1.0)
  • See the Upgrade Guide for detailed migration instructions

3. Configure (Optional)

php artisan vendor:publish --provider="Rappasoft\LaravelAuthenticationLog\LaravelAuthenticationLogServiceProvider" --tag="authentication-log-config"

Usage Examples

Get User Statistics

$user = User::find(1);

// Get comprehensive statistics
$stats = $user->getLoginStats();
// Returns: total_logins, failed_attempts, unique_devices, unique_ips, last_30_days, etc.

// Or get individual stats
$totalLogins = $user->getTotalLogins();
$failedAttempts = $user->getFailedAttempts();
$uniqueDevices = $user->getUniqueDevicesCount();

Session Management

// Get all active sessions
$activeSessions = $user->getActiveSessions();
$sessionCount = $user->getActiveSessionsCount();

// Revoke a specific session
$user->revokeSession($sessionId);

// Revoke all other sessions (keep current device)
$user->revokeAllOtherSessions($currentDeviceId);

// Revoke all sessions
$user->revokeAllSessions();

Device Management

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

// Trust a device
$user->trustDevice($deviceId);

// Untrust a device
$user->untrustDevice($deviceId);

// Update device name
$user->updateDeviceName($deviceId, 'My iPhone');

// Check if device is trusted
if ($user->isDeviceTrusted($deviceId)) {
    // Device is trusted
}

Query Scopes

use Rappasoft\LaravelAuthenticationLog\Models\AuthenticationLog;

// Filter successful logins
$successfulLogins = AuthenticationLog::successful()->get();

// Filter failed logins
$failedLogins = AuthenticationLog::failed()->get();

// Filter by IP address
$ipLogs = AuthenticationLog::fromIp('192.168.1.1')->get();

// Filter recent logs (last 7 days)
$recentLogs = AuthenticationLog::recent(7)->get();

// Filter suspicious activities
$suspicious = AuthenticationLog::suspicious()->get();

// Filter active sessions
$activeSessions = AuthenticationLog::active()->get();

// Filter trusted devices
$trustedDevices = AuthenticationLog::trusted()->get();

// Filter by device ID
$deviceLogs = AuthenticationLog::fromDevice($deviceId)->get();

// Filter for specific user
$userLogs = AuthenticationLog::forUser($user)->get();

Suspicious Activity Detection

// Detect suspicious activity
$suspiciousActivities = $user->detectSuspiciousActivity();

// Returns array of suspicious activities:
// [
//     [
//         'type' => 'multiple_failed_logins',
//         'count' => 5,
//         'message' => '5 failed login attempts in the last hour'
//     ],
//     [
//         'type' => 'rapid_location_change',
//         'countries' => ['US', 'UK'],
//         'message' => 'Login from multiple countries within an hour'
//     ]
// ]

Middleware for Trusted Devices

use Rappasoft\LaravelAuthenticationLog\Middleware\RequireTrustedDevice;

// In your routes file
Route::middleware(['auth', RequireTrustedDevice::class])->group(function () {
    // These routes require a trusted device
    Route::get('/sensitive-action', [Controller::class, 'sensitiveAction']);
});

Export Logs

# Export all logs to CSV
php artisan authentication-log:export --format=csv

# Export to JSON
php artisan authentication-log:export --format=json

# Specify custom output path
php artisan authentication-log:export --format=csv --path=storage/app/logs.csv

Webhook Configuration

Add webhooks to your config/authentication-log.php:

'webhooks' => [
    [
        'url' => 'https://example.com/webhook',
        'events' => ['login', 'failed', 'new_device', 'suspicious'],
        'headers' => [
            'Authorization' => 'Bearer your-token',
        ],
    ],
],

Configuration

The package includes comprehensive configuration options:

  • Notifications - Configure new device and failed login notifications with rate limiting
  • Suspicious Activity - Configure thresholds and detection rules
  • Webhooks - Set up webhook endpoints for external integrations
  • Database - Customize table name and database connection
  • Session Restoration - Configure session restoration prevention (prevents duplicate log entries)
  • New User Threshold - Configure time window for new user detection

See the configuration documentation for all available options.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

rappasoft/laravel-authentication-log 适用场景与选型建议

rappasoft/laravel-authentication-log 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.91M 次下载、GitHub Stars 达 984, 最近一次更新时间为 2021 年 10 月 01 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「laravel」 「rappasoft」 「laravel-authentication-log」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 rappasoft/laravel-authentication-log 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 rappasoft/laravel-authentication-log 我们能提供哪些服务?
定制开发 / 二次开发

基于 rappasoft/laravel-authentication-log 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1.91M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 987
  • 点击次数: 25
  • 依赖项目数: 11
  • 推荐数: 0

GitHub 信息

  • Stars: 984
  • Watchers: 22
  • Forks: 119
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-10-01