alajusticia / laravel-auth-tracker
在 Laravel 中跟踪和管理会话、Passport 令牌和 Sanctum 令牌。
Requires
- php: ^7.2.5|^8.0
- alajusticia/laravel-expirable: ^1.5
Requires (Dev)
- jenssegers/agent: ^2.6
- laravel/passport: ^8.4
- laravel/sanctum: ^2.1
- mockery/mockery: ^1.3
- orchestra/testbench: ^5.1
- phpunit/phpunit: ^8.5
- whichbrowser/parser: ^2.0
README
⚠️ 此包已存档。请使用 Laravel Logins 代替。
在 Laravel 中跟踪和管理会话、Passport 令牌和 Sanctum 令牌。
此包允许您分别跟踪每次登录(会话或令牌),通过解析 User-Agent 并保存 IP 地址来附加信息。
使用受支持的提供者或创建您自己的自定义提供者,您可以使用 IP 地址查找收集更多信息,例如获取地理位置。
您可以撤销每个单独的会话/令牌或全部撤销。对于带有 remember 令牌的会话,每个会话都有自己的 remember 令牌。这样,您可以在不影响其他会话的情况下撤销会话。
兼容性
-
对于最新的 Laravel 版本,请使用 Laravel Logins。
-
对于 Laravel 的旧版本(v5.8、v6 和 v7),请使用 v2。
-
它支持 Laravel 所支持的所有会话驱动程序,当然,除了当然的 cookie 驱动程序,它仅在客户端浏览器中保存会话,以及数组驱动程序。
-
为了跟踪 API 令牌,它支持官方的 Laravel Passport (>= 7.5) 和 Laravel Sanctum (v2) 包。
安装
/!\ 本文档是为 v3(WIP)。最新版本(v2)的文档可在此处找到:https://github.com/alajusticia/laravel-auth-tracker/tree/v2
使用 composer 安装包
composer require alajusticia/laravel-auth-tracker
使用以下命令发布配置文件(config/auth_tracker.php):
php artisan vendor:publish --provider="ALajusticia\AuthTracker\AuthTrackerServiceProvider" --tag="config"
创建登录表
在运行迁移之前,您可以通过配置文件的 table_name 选项更改将用于保存登录的表名(默认名为 logins)。
启动数据库迁移以创建所需的表
php artisan migrate
准备您的可验证模型
为了跟踪您的应用程序用户的登录,请在您想要跟踪的每个可验证模型上添加 ALajusticia\AuthTracker\Traits\AuthTracking
特性
use ALajusticia\AuthTracker\Traits\AuthTracking; use Illuminate\Foundation\Auth\User as Authenticatable; // ... class User extends Authenticatable { use AuthTracking; // ... }
选择并安装一个用户代理解析器
此包依赖于一个用户代理解析器来提取信息。
目前,它支持最受欢迎的两个解析器
- WhichBrowser (https://github.com/WhichBrowser/Parser-PHP)
- Agent (https://github.com/jenssegers/agent)
在开始使用 Auth Tracker 之前,您需要选择一个受支持的解析器,安装它,并在配置文件中指定您要使用哪个。
配置用户提供者(可选)
如果您的应用程序只有无状态身份验证,则此步骤是可选的。
如果您想使用Auth Tracker进行有状态的认证,这个包包含一个修改过的Eloquent用户提供者,它会从登录表而不是用户表中检索已记住的用户。
在您的config/auth.php
配置文件中,为要跟踪的用户使用用户提供者列表中的eloquent-tracked
驱动程序
'providers' => [ 'users' => [ 'driver' => 'eloquent-tracked', 'model' => App\Models\User::class, ], // ... ],
Laravel Sanctum
在Laravel Sanctum包的实际版本(2.9)中,没有事件允许我们知道何时创建API令牌。
如果您使用Laravel Sanctum发布API令牌并希望启用认证跟踪,您将不得不分配Auth Tracker提供的事件。
分发ALajusticia\AuthTracker\Events\PersonalAccessTokenCreated
事件,传递由Laravel Sanctum特性中的createToken
方法创建的新个人访问令牌。
根据Laravel Sanctum文档中提供的示例
,它可能看起来像这样
use ALajusticia\AuthTracker\Events\PersonalAccessTokenCreated; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Validation\ValidationException; Route::post('/sanctum/token', function (Request $request) { $request->validate([ 'email' => 'required|email', 'password' => 'required', 'device_name' => 'required', ]); $user = User::where('email', $request->email)->first(); if (! $user || ! Hash::check($request->password, $user->password)) { throw ValidationException::withMessages([ 'email' => ['The provided credentials are incorrect.'], ]); } $personalAccessToken = $user->createToken($request->device_name); event(new PersonalAccessTokenCreated($personalAccessToken)); // Dispatch here the event return $personalAccessToken->plainTextToken; });
使用方法
此包提供的AuthTracking
特性为您用户的模型添加了列出登录的方法,并让您对其完全控制。
检索登录
获取所有登录
$logins = request()->user()->logins;
获取当前登录
$login = request()->user()->currentLogin();
检查当前登录
每个登录实例都有一个动态的is_current
属性。它是一个布尔值,表示登录实例是否是当前登录。
撤销登录
撤销特定登录
要吊销特定的登录,请使用带有要吊销的登录ID的logout
方法。如果没有提供参数,将吊销当前登录。
request()->user()->logout(1); // Revoke the login where id=1
request()->user()->logout(); // Revoke the current login
撤销所有登录
我们可以通过使用logoutAll
方法来销毁所有会话和吊销所有Passport/Sanctum令牌。当用户密码更改时,我们想要注销所有设备时很有用。
此功能销毁了所有会话,包括已记住的会话。
request()->user()->logoutAll();
撤销所有登录(除了当前登录)
logoutOthers
方法的行为与logoutAll
方法相同,但会保留当前会话或Passport/Sanctum令牌。
request()->user()->logoutOthers();
事件
登录
在新的登录上,您可以监听ALajusticia\AuthTracker\Events\Login
事件。它接收一个包含请求上收集的所有信息的RequestContext
对象,可以通过事件的context
属性访问。
可用的属性
$this->context->userAgent; // The full, unparsed, User-Agent header $this->context->ip; // The IP address
可用的方法
$this->context->parser(); // Returns the parser used to parse the User-Agent header $this->context->ip(); // Returns the IP address lookup provider
解析器中的方法
$this->context->parser()->getDevice(); // The name of the device (MacBook...) $this->context->parser()->getDeviceType(); // The type of the device (desktop, mobile, tablet, phone...) $this->context->parser()->getPlatform(); // The name of the platform (macOS...) $this->context->parser()->getBrowser(); // The name of the browser (Chrome...)
IP地址查找提供者中的方法
$this->context->ip()->getCountry(); // The name of the country $this->context->ip()->getRegion(); // The name of the region $this->context->ip()->getCity(); // The name of the city $this->context->ip()->getResult(); // The entire result of the API call as a Laravel collection // And all your custom methods in the case of a custom provider
IP 地址查找
默认情况下,Auth Tracker收集IP地址和User-Agent头中提供的信息。
但您可以更进一步,收集有关IP地址的其他信息,如地理位置。
要这样做,您首先必须在配置文件中启用IP查找功能。
此包包含两个官方支持的IP地址查找提供者(请参阅config/auth_tracker.php
配置文件中的IP地址查找部分)。
Ip2Location Lite DB3
此包官方支持使用Ip2Location Lite DB3进行IP地址地理定位。
以下是启用和使用它的步骤
-
下载数据库的当前版本,并根据文档说明将其导入您的数据库中:[https://lite.ip2location.com/database/ip-country-region-city](https://lite.ip2location.com/database/ip-country-region-city)
-
在
config/auth_tracker.php
配置文件中将ip_lookup.provider
选项的名称设置为ip2location-lite
-
在
config/auth_tracker.php
配置文件中指定用于IPv4和IPv6的数据库中使用的表名(默认情况下,它使用与文档中相同的名称:ip2location_db3
和ip2location_db3_ipv6
)
自定义提供者
您可以通过创建一个实现ALajusticia\AuthTracker\Interfaces\IpProvider
接口的类并使用ALajusticia\AuthTracker\Traits\MakesApiCalls
特性来添加自己的提供者。
您的自定义类必须注册在配置文件的custom_providers
数组中。
让我们看看使用内置的IpApi
提供者的IP查找提供者的一个例子
use ALajusticia\AuthTracker\Interfaces\IpProvider; use ALajusticia\AuthTracker\Traits\MakesApiCalls; use GuzzleHttp\Psr7\Request as GuzzleRequest; use Illuminate\Support\Facades\Request; class IpApi implements IpProvider { use MakesApiCalls; /** * Get the Guzzle request. * * @return GuzzleRequest */ public function getRequest() { return new GuzzleRequest('GET', 'http://ip-api.com/json/' . Request::ip() . '?fields=25'); } /** * Get the country name. * * @return string */ public function getCountry() { return $this->result->get('country'); } /** * Get the region name. * * @return string */ public function getRegion() { return $this->result->get('regionName'); } /** * Get the city name. * * @return string */ public function getCity() { return $this->result->get('city'); } }
如你所见,类有一个getRequest
方法,它必须返回一个GuzzleHttp\Psr7\Request
实例。
Guzzle使用PSR-7作为HTTP消息接口。请查阅其文档: http://docs.guzzlephp.org/en/stable/psr7.html
IpProvider
接口包含与地理位置相关的必需方法。API响应的所有键都可以通过你的提供者中的$this->result
访问,它是一个Laravel集合。
如果你想要收集其他信息,你可以在自定义提供者中添加一个getCustomData
方法。这些自定义数据将被保存在日志表的ip_data
JSON列中。让我们看看附加数据的例子
public function getCustomData() { return [ 'country_code' => $this->result->get('countryCode'), 'latitude' => $this->result->get('lat'), 'longitude' => $this->result->get('lon'), 'timezone' => $this->result->get('timezone'), 'isp_name' => $this->result->get('isp'), ]; }
处理 API 错误
如果在你的IP地址查找提供者的API调用过程中抛出异常,此包将通过FailedApiCall事件触发。
此事件包含一个异常属性,包含GuzzleHttp\Exception\TransferException(请参阅Guzzle文档)。
你可以监听此事件以添加自己的逻辑。
Blade 指令
检查当前用户是否启用了身份验证跟踪
@tracked <a href="{{ route('login.list') }}">Security</a> @endtracked
检查IP查找功能是否启用
@ipLookup {{ $login->location }} @endipLookup
许可证
开源软件,采用MIT许可证。