-
-
Notifications
You must be signed in to change notification settings - Fork 314
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
Open
lancepioch
wants to merge
3
commits into
main
Choose a base branch
from
w6/admin-activity-viewer
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+320
−0
Open
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
182 changes: 182 additions & 0 deletions
182
app/Filament/Admin/Resources/Activities/ActivityResource.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,182 @@ | ||
| <?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\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\Support\Arr; | ||
| use Illuminate\Support\HtmlString; | ||
|
|
||
| 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) | ||
| ->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() | ||
| ->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')) | ||
| ->formatStateUsing(fn ($state) => Arr::dot($state)), | ||
| ]), | ||
| ]) | ||
| ->filters([ | ||
| SelectFilter::make('event') | ||
| ->label(trans('admin/activity.event')) | ||
| ->options(fn () => ActivityLog::whereNotIn('event', ActivityLog::DISABLED_EVENTS)->select('event')->distinct()->orderBy('event')->pluck('event', 'event')) | ||
| ->searchable() | ||
| ->preload(), | ||
| SelectFilter::make('actor_id') | ||
| ->label(trans('admin/activity.user')) | ||
| ->options(fn () => User::whereIn('id', ActivityLog::whereNotNull('actor_id')->select('actor_id'))->pluck('username', 'id')) | ||
| ->searchable() | ||
| ->preload(), | ||
| SelectFilter::make('subject_type') | ||
| ->label(trans('admin/activity.subject')) | ||
| ->options(fn () => ActivityLogSubject::select('subject_type')->distinct()->orderBy('subject_type')->pluck('subject_type', 'subject_type')->mapWithKeys(fn ($type) => [$type => class_basename($type)])) | ||
| ->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})"; | ||
| } | ||
| } | ||
21 changes: 21 additions & 0 deletions
21
app/Filament/Admin/Resources/Activities/Pages/ListActivities.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -65,6 +65,7 @@ class Role extends BaseRole | |
| 'view', | ||
| ], | ||
| 'activityLog' => [ | ||
| 'view', | ||
| 'seeIps', | ||
| ], | ||
| 'panelLog' => [ | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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', | ||
| ]; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| <?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 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('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(); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.