Keep an audit log of who did what, and how they came in
Written from model events, spatie's role events and panel sign-ins, only for what a person did, with secrets masked; pruned after a year. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
53
app/Http/Controllers/Api/V1/AuditController.php
Normal file
53
app/Http/Controllers/Api/V1/AuditController.php
Normal file
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Resources\AuditLogResource;
|
||||
use App\Models\AuditLog;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* GET /v1/audit — who did what, when, and how they came in.
|
||||
*/
|
||||
class AuditController extends Controller
|
||||
{
|
||||
/**
|
||||
* Newest first. Filters: user_id, action (exact, or a prefix ending in
|
||||
* `.`, e.g. `pages.`), subject_type, subject_id, via, from, to.
|
||||
*/
|
||||
public function index(Request $request): AnonymousResourceCollection
|
||||
{
|
||||
$this->authorize('audit.view_any');
|
||||
|
||||
$request->validate([
|
||||
'via' => ['sometimes', Rule::in(['panel', 'api', 'token', 'web', 'console'])],
|
||||
'from' => ['sometimes', 'date'],
|
||||
'to' => ['sometimes', 'date'],
|
||||
]);
|
||||
|
||||
$entries = AuditLog::query()
|
||||
->when($request->filled('user_id'), fn ($q) => $q->where('user_id', $request->integer('user_id')))
|
||||
->when($request->filled('action'), function ($q) use ($request): void {
|
||||
$action = (string) $request->string('action');
|
||||
|
||||
str_ends_with($action, '.')
|
||||
? $q->where('action', 'like', $action.'%')
|
||||
: $q->where('action', $action);
|
||||
})
|
||||
->when($request->filled('subject_type'), fn ($q) => $q->where('subject_type', $request->string('subject_type')))
|
||||
->when($request->filled('subject_id'), fn ($q) => $q->where('subject_id', (string) $request->string('subject_id')))
|
||||
->when($request->filled('via'), fn ($q) => $q->where('via', $request->string('via')))
|
||||
->when($request->filled('from'), fn ($q) => $q->where('created_at', '>=', $request->date('from')))
|
||||
->when($request->filled('to'), fn ($q) => $q->where('created_at', '<=', $request->date('to')))
|
||||
->latest('id')
|
||||
->paginate(perPage: min($request->integer('per_page', 50), 100))
|
||||
->withQueryString();
|
||||
|
||||
return AuditLogResource::collection($entries);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user