-
-
Notifications
You must be signed in to change notification settings - Fork 316
Add admin-wide activity viewer behind a new view activityLog permission #2569
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
932fbbe
7d5b0a3
4d7ca37
f16cec8
3bdb479
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,196 @@ | ||
| <?php | ||
|
|
||
| namespace App\Filament\Admin\Resources\Activities; | ||
|
|
||
| use App\Enums\TablerIcon; | ||
| use App\Filament\Admin\Resources\Activities\Pages\ListActivities; | ||
| use App\Filament\Admin\Resources\Users\Pages\EditUser; | ||
| use App\Filament\Components\Tables\Columns\DateTimeColumn; | ||
| use App\Models\ActivityLog; | ||
| use App\Models\ActivityLogSubject; | ||
| use App\Models\User; | ||
| use App\Traits\Filament\CanCustomizePages; | ||
| use App\Traits\Filament\CanCustomizeRelations; | ||
| use App\Traits\Filament\CanModifyTable; | ||
| use BackedEnum; | ||
| use Exception; | ||
| use Filament\Actions\ViewAction; | ||
| use Filament\Forms\Components\DateTimePicker; | ||
| use Filament\Forms\Components\KeyValue; | ||
| use Filament\Forms\Components\TextInput; | ||
| use Filament\Infolists\Components\TextEntry; | ||
| use Filament\Resources\Pages\PageRegistration; | ||
| use Filament\Resources\Resource; | ||
| use Filament\Tables\Columns\TextColumn; | ||
| use Filament\Tables\Enums\PaginationMode; | ||
| use Filament\Tables\Filters\Filter; | ||
| use Filament\Tables\Filters\SelectFilter; | ||
| use Filament\Tables\Table; | ||
| use Illuminate\Auth\Access\Response; | ||
| use Illuminate\Database\Eloquent\Builder; | ||
| use Illuminate\Database\Eloquent\Model; | ||
| use Illuminate\Database\Eloquent\Relations\Relation; | ||
| use Illuminate\Support\Arr; | ||
| use Illuminate\Support\HtmlString; | ||
| use Illuminate\Support\Str; | ||
|
|
||
| class ActivityResource extends Resource | ||
| { | ||
| use CanCustomizePages; | ||
| use CanCustomizeRelations; | ||
| use CanModifyTable; | ||
|
|
||
| protected static ?string $model = ActivityLog::class; | ||
|
|
||
| protected static string|BackedEnum|null $navigationIcon = TablerIcon::Stack; | ||
|
|
||
| /** | ||
| * @throws Exception | ||
| */ | ||
| public static function defaultTable(Table $table): Table | ||
| { | ||
| return $table | ||
| ->paginated([25, 50]) | ||
| ->defaultPaginationPageOption(25) | ||
| // Simple pagination skips the COUNT(*) over the whole activity log. | ||
| ->paginationMode(PaginationMode::Simple) | ||
| ->columns([ | ||
| TextColumn::make('event') | ||
| ->label(trans('admin/activity.event')) | ||
| ->html() | ||
| ->description(fn ($state) => $state) | ||
| ->icon(fn (ActivityLog $activityLog) => $activityLog->getIcon()) | ||
| ->formatStateUsing(fn (ActivityLog $activityLog) => $activityLog->getLabel()), | ||
| TextColumn::make('user') | ||
| ->label(trans('admin/activity.user')) | ||
| ->state(fn (ActivityLog $activityLog) => self::actorName($activityLog)) | ||
| ->tooltip(fn (ActivityLog $activityLog) => $activityLog->getIp() ?? '') | ||
| ->url(fn (ActivityLog $activityLog) => $activityLog->actor instanceof User && user()?->can('update', $activityLog->actor) ? EditUser::getUrl(['record' => $activityLog->actor]) : '') | ||
| ->grow(false), | ||
| TextColumn::make('subjects') | ||
| ->label(trans('admin/activity.subject')) | ||
| ->state(fn (ActivityLog $activityLog) => $activityLog->subjects | ||
| ->map(fn (ActivityLogSubject $subject) => class_basename($subject->subject_type) . ' #' . $subject->subject_id) | ||
| ->unique() | ||
| ->join(', ')) | ||
| ->grow(false), | ||
| DateTimeColumn::make('timestamp') | ||
| ->label(trans('admin/activity.timestamp')) | ||
| ->since() | ||
| ->sortable() | ||
| ->grow(false), | ||
| ]) | ||
| ->defaultSort('timestamp', 'desc') | ||
| ->recordActions([ | ||
| ViewAction::make() | ||
| // Flatten before the form fills: KeyValue's state cast mistakes a nested | ||
| // assoc (first value an array) for its own row format and blanks it. | ||
| ->mutateRecordDataUsing(function (array $data) { | ||
| $data['properties'] = collect(Arr::dot($data['properties'] ?? [])) | ||
| ->map(fn ($value) => is_bool($value) || is_null($value) ? var_export($value, true) : $value) | ||
| ->all(); | ||
|
Comment on lines
+89
to
+91
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟠 High The View modal exposes - $data['properties'] = collect(Arr::dot($data['properties'] ?? []))
- ->map(fn ($value) => is_bool($value) || is_null($value) ? var_export($value, true) : $value)
+ $data['properties'] = collect(Arr::dot($data['properties'] ?? []))
+ ->reject(fn ($value, $key) => $key === 'ip' && ! (user()?->can('seeIps activityLog') ?? false))
+ ->map(fn ($value) => is_bool($value) || is_null($value) ? var_export($value, true) : $value)🚀 Reply "fix it for me" or copy this AI Prompt for your agent: |
||
|
|
||
| return $data; | ||
| }) | ||
| ->schema([ | ||
| TextEntry::make('event') | ||
| ->label(trans('admin/activity.event')) | ||
| ->state(fn (ActivityLog $activityLog) => new HtmlString($activityLog->getLabel())), | ||
| TextInput::make('user') | ||
| ->label(trans('admin/activity.user')) | ||
| ->formatStateUsing(function (ActivityLog $activityLog) { | ||
| $user = self::actorName($activityLog); | ||
| $ip = $activityLog->getIp(); | ||
|
|
||
| return $ip ? "$user - $ip" : $user; | ||
| }), | ||
| DateTimePicker::make('timestamp') | ||
| ->label(trans('admin/activity.timestamp')), | ||
| KeyValue::make('properties') | ||
| ->label(trans('admin/activity.metadata')), | ||
| ]), | ||
| ]) | ||
| ->filters([ | ||
| // Options come from the translated event names and the morph map rather | ||
| // than SELECT DISTINCT, which scans the whole log on every page load. | ||
| SelectFilter::make('event') | ||
| ->label(trans('admin/activity.event')) | ||
| ->options(fn () => collect(Arr::dot(trans('activity')))->keys()->map(fn (string $key) => Str::replaceFirst('.', ':', $key))->sort()->mapWithKeys(fn (string $event) => [$event => $event])) | ||
| ->searchable(), | ||
| SelectFilter::make('actor_id') | ||
| ->label(trans('admin/activity.user')) | ||
| ->searchable() | ||
| ->getSearchResultsUsing(fn (string $search) => User::where('username', 'like', "%$search%")->orWhere('email', 'like', "%$search%")->limit(50)->pluck('username', 'id')) | ||
| ->getOptionLabelUsing(fn ($value) => User::find($value)?->username), | ||
| SelectFilter::make('subject_type') | ||
| ->label(trans('admin/activity.subject')) | ||
| ->options(fn () => collect(Relation::morphMap())->mapWithKeys(fn (string $class, string $alias) => [$alias => class_basename($class)])->sort()) | ||
| ->query(fn (Builder $query, array $data) => $query->when($data['value'], fn (Builder $query, $value) => $query->whereHas('subjects', fn (Builder $query) => $query->where('subject_type', $value)))), | ||
| Filter::make('timestamp') | ||
| ->schema([ | ||
| DateTimePicker::make('from') | ||
| ->label(trans('admin/activity.from')), | ||
| DateTimePicker::make('until') | ||
| ->label(trans('admin/activity.until')), | ||
| ]) | ||
| ->query(fn (Builder $query, array $data) => $query | ||
| ->when($data['from'], fn (Builder $query, $value) => $query->where('timestamp', '>=', $value)) | ||
| ->when($data['until'], fn (Builder $query, $value) => $query->where('timestamp', '<=', $value))), | ||
| ]); | ||
| } | ||
|
|
||
| /** @return Builder<ActivityLog> */ | ||
| public static function getEloquentQuery(): Builder | ||
| { | ||
| // Deliberately unscoped (and ignoring activity.hide_admin_activity): | ||
| // this is the panel-wide audit view for admins holding "view activityLog". | ||
| return ActivityLog::with(['actor', 'apiKey']) | ||
| ->whereNotIn('event', ActivityLog::DISABLED_EVENTS); | ||
| } | ||
|
|
||
| public static function canViewAny(): bool | ||
| { | ||
| return user()?->can('view activityLog') ?? false; | ||
| } | ||
|
|
||
| public static function canAccess(): bool | ||
| { | ||
| return static::canViewAny(); | ||
| } | ||
|
|
||
| /** | ||
| * ActivityLogPolicy::view() checks the server-panel subuser permission, | ||
| * which never applies here; the admin viewer is gated by "view activityLog". | ||
| */ | ||
| public static function getViewAuthorizationResponse(Model $record): Response | ||
| { | ||
| return static::canViewAny() ? Response::allow() : Response::deny(); | ||
| } | ||
|
|
||
| /** @return array<string, PageRegistration> */ | ||
| public static function getDefaultPages(): array | ||
| { | ||
| return [ | ||
| 'index' => ListActivities::route('/'), | ||
| ]; | ||
| } | ||
|
|
||
| public static function getNavigationLabel(): string | ||
| { | ||
| return trans('admin/activity.title'); | ||
| } | ||
|
|
||
| public static function getNavigationGroup(): ?string | ||
| { | ||
| return trans('admin/dashboard.advanced'); | ||
| } | ||
|
|
||
| private static function actorName(ActivityLog $activityLog): string | ||
| { | ||
| if (!$activityLog->actor instanceof User) { | ||
| return $activityLog->actor_id === null ? trans('admin/activity.system') : trans('admin/activity.deleted_user'); | ||
| } | ||
|
|
||
| return "{$activityLog->actor->username} ({$activityLog->actor->email})"; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| <?php | ||
|
|
||
| namespace App\Filament\Admin\Resources\Activities\Pages; | ||
|
|
||
| use App\Filament\Admin\Resources\Activities\ActivityResource; | ||
| use App\Traits\Filament\CanCustomizeHeaderActions; | ||
| use App\Traits\Filament\CanCustomizeHeaderWidgets; | ||
| use Filament\Resources\Pages\ListRecords; | ||
|
|
||
| class ListActivities extends ListRecords | ||
| { | ||
| use CanCustomizeHeaderActions; | ||
| use CanCustomizeHeaderWidgets; | ||
|
|
||
| protected static string $resource = ActivityResource::class; | ||
|
|
||
| public function getTitle(): string | ||
| { | ||
| return trans('admin/activity.title'); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -65,6 +65,7 @@ class Role extends BaseRole | |
| 'view', | ||
| ], | ||
| 'activityLog' => [ | ||
| 'view', | ||
| 'seeIps', | ||
| ], | ||
| 'panelLog' => [ | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| <?php | ||
|
|
||
| return [ | ||
| 'title' => 'Activity', | ||
| 'event' => 'Event', | ||
| 'user' => 'User', | ||
| 'deleted_user' => 'Deleted User', | ||
| 'system' => 'System', | ||
| 'subject' => 'Subject', | ||
| 'timestamp' => 'Timestamp', | ||
| 'metadata' => 'Metadata', | ||
| 'from' => 'From', | ||
| 'until' => 'Until', | ||
| ]; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| <?php | ||
|
|
||
| use App\Facades\Activity; | ||
| use App\Filament\Admin\Resources\Activities\Pages\ListActivities; | ||
| use App\Models\ActivityLog; | ||
| use App\Models\Role; | ||
| use Filament\Actions\Testing\TestAction; | ||
| use Filament\Facades\Filament; | ||
| use Illuminate\Support\Facades\DB; | ||
| use Spatie\Permission\Models\Permission; | ||
|
|
||
| use function Pest\Livewire\livewire; | ||
|
|
||
| beforeEach(fn () => Filament::setCurrentPanel(Filament::getPanel('admin'))); | ||
| afterEach(fn () => Filament::setCurrentPanel(null)); | ||
|
|
||
| it('root admin can see activity from every panel', function () { | ||
| [$admin, $server] = generateTestAccount([]); | ||
| $admin = $admin->syncRoles(Role::getRootAdmin()); | ||
|
|
||
| Activity::event('auth:success')->actor($admin)->log(); | ||
| Activity::event('server:power.start')->subject($server)->log(); | ||
|
|
||
| $this->actingAs($admin); | ||
| livewire(ListActivities::class) | ||
| ->assertSuccessful() | ||
| ->assertCountTableRecords(ActivityLog::count()) | ||
| ->assertCanSeeTableRecords(ActivityLog::all()); | ||
| }); | ||
|
|
||
| it('event filter narrows the table', function () { | ||
| [$admin] = generateTestAccount([]); | ||
| $admin = $admin->syncRoles(Role::getRootAdmin()); | ||
|
|
||
| Activity::event('auth:success')->actor($admin)->log(); | ||
| Activity::event('auth:fail')->log(); | ||
|
|
||
| $this->actingAs($admin); | ||
| livewire(ListActivities::class) | ||
| ->filterTable('event', 'auth:fail') | ||
| ->assertCountTableRecords(1); | ||
| }); | ||
|
|
||
| it('user without view activityLog is forbidden', function () { | ||
| $role = Role::factory()->create(['name' => 'IP Viewer', 'guard_name' => 'web']); | ||
| // seeIps alone must not grant access to the viewer. | ||
| $role->givePermissionTo(Permission::findOrCreate('seeIps activityLog', 'web')); | ||
| [$user] = generateTestAccount([]); | ||
| $user = $user->syncRoles($role); | ||
|
|
||
| $this->actingAs($user); | ||
| livewire(ListActivities::class) | ||
| ->assertForbidden(); | ||
| }); | ||
|
|
||
| it('user with view activityLog can see the viewer', function () { | ||
| $role = Role::factory()->create(['name' => 'Auditor', 'guard_name' => 'web']); | ||
| $role->givePermissionTo(Permission::findOrCreate('view activityLog', 'web')); | ||
| [$user] = generateTestAccount([]); | ||
| $user = $user->syncRoles($role); | ||
|
|
||
| Activity::event('auth:success')->log(); | ||
|
|
||
| $this->actingAs($user); | ||
| livewire(ListActivities::class) | ||
| ->assertSuccessful() | ||
| ->assertCountTableRecords(ActivityLog::count()); | ||
| }); | ||
|
|
||
| it('flattens nested properties for the metadata modal', function () { | ||
| [$admin] = generateTestAccount([]); | ||
| $admin = $admin->syncRoles(Role::getRootAdmin()); | ||
|
|
||
| // Nested-only properties trip KeyValue's state cast without the flatten. | ||
| $log = Activity::event('settings:update')->property('changes', ['APP_NAME' => ['old' => 'A', 'new' => null]])->log(); | ||
|
|
||
| $this->actingAs($admin); | ||
| livewire(ListActivities::class) | ||
| ->mountAction(TestAction::make('view')->table($log)) | ||
| ->assertActionDataSet(['properties' => ['changes.APP_NAME.old' => 'A', 'changes.APP_NAME.new' => 'NULL']]); | ||
| }); | ||
|
|
||
| it('user with view activityLog can open the properties modal', function () { | ||
| $role = Role::factory()->create(['name' => 'Modal Auditor', 'guard_name' => 'web']); | ||
| $role->givePermissionTo(Permission::findOrCreate('view activityLog', 'web')); | ||
| [$user] = generateTestAccount([]); | ||
| $user = $user->syncRoles($role); | ||
|
|
||
| $log = Activity::event('auth:success')->log(); | ||
|
|
||
| $this->actingAs($user); | ||
| livewire(ListActivities::class) | ||
| ->callAction(TestAction::make('view')->table($log)) | ||
| ->assertHasNoActionErrors(); | ||
| }); | ||
|
|
||
| it('subject filter narrows the table by morph alias', function () { | ||
| [$admin, $server] = generateTestAccount([]); | ||
| $admin = $admin->syncRoles(Role::getRootAdmin()); | ||
|
|
||
| ActivityLog::query()->delete(); | ||
| Activity::event('server:power.start')->subject($server)->log(); | ||
| Activity::event('auth:success')->actor($admin)->log(); | ||
|
|
||
| $this->actingAs($admin); | ||
| livewire(ListActivities::class) | ||
| ->filterTable('subject_type', $server->getMorphClass()) | ||
| ->assertCountTableRecords(1); | ||
| }); | ||
|
|
||
| it('does not query per row', function () { | ||
| [$admin, $server] = generateTestAccount([]); | ||
| $admin = $admin->syncRoles(Role::getRootAdmin()); | ||
| $this->actingAs($admin); | ||
|
|
||
| $count = function () { | ||
| DB::flushQueryLog(); | ||
| DB::enableQueryLog(); | ||
| livewire(ListActivities::class)->assertSuccessful(); | ||
|
|
||
| return count(DB::getQueryLog()); | ||
| }; | ||
|
|
||
| Activity::event('server:power.start')->subject($server)->log(); | ||
| $count(); // Warm the permission and settings caches. | ||
| $baseline = $count(); | ||
|
|
||
| foreach (range(1, 10) as $ignored) { | ||
| Activity::event('server:power.start')->subject($server)->log(); | ||
| } | ||
|
|
||
| expect($count())->toBe($baseline); | ||
| }); |
Uh oh!
There was an error while loading. Please reload this page.