Rollen, Rechte und Zielgruppen
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m30s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m28s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m31s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m36s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 1m45s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 1m44s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 1m35s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 1m38s
CI / Build-Artefakte aktuell (pull_request) Successful in 54s

- Rollen mit globalen Rechten und Rechten für einzelne Objekte (z. B. „Beiträge
  schreiben in Kategorie MAV-Info“); Rollen sind additiv, Zuweisungen merken
  sich ihre Herkunft (manuell oder später Identity-Provider-Gruppe)
- Systemrolle „Administration“ ersetzt users.is_admin (Migration übernimmt
  bestehende Administratoren); nicht löschbar, man kann sie sich nicht selbst entziehen
- Rechte je Person vorberechnet und gecacht, Versionszähler invalidiert bei Änderungen
- Gate-Anbindung: registrierte Rechte entscheidet das Rechtesystem, Objektregeln
  die Policies; Admin-Seiten und Plugin-Ressourcen hinter passenden Rechten
- Redaktion nach Kategorie: Schreiben und Veröffentlichen getrennt, Liste im
  Admin auf eigene Kategorien beschränkt, ohne Veröffentlichungsrecht bleibt
  ein Beitrag Entwurf
- Zielgruppen (Rolle/Abteilung/Standort) für Kategorien und Termine als
  indizierte SQL-Bedingung in Listen, Detailseiten, Kacheln und .ics-Export
- Admin: Rollen-Verwaltung, „Rechte prüfen“, Redaktion und Sichtbarkeit direkt
  an Kategorie bzw. Termin
- Kern-Ressourcen explizit registriert, damit nach Updates liegengebliebene
  alte Dateien nicht doppelt geladen werden
- docs/PLUGINS.md für Plugin-Entwicklung; Demo-Rolle „MAV“

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-26 07:18:37 +00:00
parent 28ef1e4a20
commit 9ddc35a62c
112 changed files with 2408 additions and 267 deletions

View file

@ -0,0 +1,53 @@
<?php
namespace App\Filament\Components;
use App\Models\Role;
use App\Models\User;
use App\Support\Permissions\Audiences;
use Filament\Forms\Components\Select;
use Filament\Schemas\Components\Section;
use Illuminate\Database\Eloquent\Model;
/**
* Formularbereich „Sichtbarkeit“ für Objekte mit Zielgruppen.
*/
class AudienceSection
{
public static function make(string $type, string $description = 'Leer lassen = für alle sichtbar. Sonst sehen es nur Personen, die mindestens eine Angabe erfüllen.'): Section
{
$field = fn (string $rule, string $label, callable $options) => Select::make("audience_{$rule}")
->label($label)
->multiple()
->searchable()
->options($options)
->afterStateHydrated(fn (Select $component, ?Model $record) => $component->state($record ? Audiences::get($type, $record->getKey())[$rule] : []))
->saveRelationshipsUsing(function (Model $record, Select $component) use ($type) {
// Alle drei Felder zusammen speichern (einmal pro Formular reicht, aber schadet nicht).
$state = $component->getContainer()->getRawState();
Audiences::sync($type, $record->getKey(), [
'role' => $state['audience_role'] ?? [],
'department' => $state['audience_department'] ?? [],
'location' => $state['audience_location'] ?? [],
]);
})
->dehydrated(false);
return Section::make('Sichtbarkeit')
->description($description)
->collapsible()
->schema([
$field('role', 'Rollen', fn () => Role::query()->orderBy('name')->pluck('name', 'id')->mapWithKeys(fn ($name, $id) => [(string) $id => $name])->all()),
$field('department', 'Abteilungen', fn () => self::distinct('department')),
$field('location', 'Standorte', fn () => self::distinct('location')),
]);
}
/**
* @return array<string, string>
*/
private static function distinct(string $column): array
{
return User::query()->whereNotNull($column)->distinct()->orderBy($column)->pluck($column, $column)->all();
}
}

View file

@ -0,0 +1,38 @@
<?php
namespace App\Filament\Components;
use App\Models\Grant;
use App\Models\Role;
use Filament\Forms\Components\Select;
use Illuminate\Database\Eloquent\Model;
/**
* „Welche Rollen haben dieses Recht auf diesem Objekt?“ – direkt am Objekt
* gepflegt, z. B. am Formular einer Kategorie. Speichert Grants.
*/
class RoleGrantSelect
{
public static function make(string $name, string $label, string $ability, string $resourceType): Select
{
return Select::make($name)
->label($label)
->multiple()
->preload()
->options(fn () => Role::query()->where('slug', '!=', Role::ADMINISTRATION)->orderBy('name')->pluck('name', 'id')->all())
->afterStateHydrated(fn (Select $component, ?Model $record) => $component->state($record
? Grant::query()->where('ability', $ability)->where('resource_type', $resourceType)->where('resource_id', $record->getKey())->pluck('role_id')->all()
: []))
->saveRelationshipsUsing(function (Model $record, ?array $state) use ($ability, $resourceType) {
$roleIds = array_map('intval', $state ?? []);
$existing = Grant::query()->where('ability', $ability)->where('resource_type', $resourceType)->where('resource_id', $record->getKey());
(clone $existing)->whereNotIn('role_id', $roleIds)->get()->each->delete();
foreach (array_diff($roleIds, (clone $existing)->pluck('role_id')->all()) as $roleId) {
Grant::query()->create(['role_id' => $roleId, 'ability' => $ability, 'resource_type' => $resourceType, 'resource_id' => $record->getKey()]);
}
})
->dehydrated(false);
}
}

View file

@ -32,6 +32,11 @@ class Appearance extends Page
protected static ?string $title = 'Erscheinungsbild';
public static function canAccess(): bool
{
return auth()->user()?->can('appearance.manage') ?? false;
}
protected static ?string $slug = 'erscheinungsbild';
/** @var array<string, mixed>|null */

View file

@ -31,6 +31,11 @@ class Feedback extends Page
protected static ?string $title = 'Rückmeldung geben';
public static function canAccess(): bool
{
return auth()->user()?->can('feedback.send') ?? false;
}
protected static ?string $slug = 'rueckmeldung';
public string $type = '';

View file

@ -0,0 +1,102 @@
<?php
namespace App\Filament\Pages;
use App\Models\Grant;
use App\Models\User;
use App\Support\Abilities;
use BackedEnum;
use Filament\Pages\Page;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Facades\DB;
use UnitEnum;
/**
* „Was darf Person X – und warum?“ Zeigt Rollen samt Herkunft und alle Rechte
* mit der Rolle, aus der sie stammen.
*/
class PermissionChecker extends Page
{
protected string $view = 'filament.pages.permission-checker';
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedMagnifyingGlassCircle;
protected static string|UnitEnum|null $navigationGroup = 'Benutzer & Rechte';
protected static ?int $navigationSort = 3;
protected static ?string $title = 'Rechte prüfen';
protected static ?string $slug = 'rechte-pruefen';
public ?int $userId = null;
public string $search = '';
public static function canAccess(): bool
{
return auth()->user()?->can('roles.manage') ?? false;
}
public function mount(): void
{
$this->userId = request()->integer('person') ?: null;
}
public function selectUser(int $id): void
{
$this->userId = $id;
$this->search = '';
}
/**
* @return array<string, mixed>
*/
protected function getViewData(): array
{
$abilities = app(Abilities::class);
$user = $this->userId ? User::query()->find($this->userId) : null;
$results = strlen($this->search) >= 2
? User::query()->where(fn ($q) => $q->where('name', 'like', "%{$this->search}%")->orWhere('email', 'like', "%{$this->search}%"))->orderBy('name')->limit(8)->get()
: collect();
$roles = collect();
$global = collect();
$objects = collect();
if ($user) {
$roles = DB::table('role_user')->join('roles', 'roles.id', '=', 'role_user.role_id')
->where('role_user.user_id', $user->id)
->orderBy('roles.name')
->get(['roles.id', 'roles.name', 'role_user.source', 'role_user.source_ref']);
$grants = Grant::query()->with('role')->whereIn('role_id', $roles->pluck('id')->unique())->get();
$types = $abilities->resourceTypes();
$global = $grants->whereNull('resource_type')->map(fn (Grant $g) => [
'label' => $g->ability === '*' ? 'Alle Rechte (voller Zugriff)' : $abilities->label($g->ability),
'role' => $g->role->name,
])->sortBy('label')->values();
$objects = $grants->whereNotNull('resource_type')->map(function (Grant $g) use ($abilities, $types) {
$options = isset($types[$g->resource_type]) ? ($types[$g->resource_type]['options'])() : [];
return [
'label' => $abilities->label($g->ability),
'object' => ($types[$g->resource_type]['label'] ?? $g->resource_type).': '.($g->resource_id === null ? 'alle' : ($options[$g->resource_id] ?? '#'.$g->resource_id)),
'role' => $g->role->name,
];
})->sortBy('label')->values();
}
return [
'user' => $user,
'results' => $results,
'roles' => $roles,
'global' => $global,
'objects' => $objects,
'canAdmin' => $user?->canAccessAdmin() ?? false,
];
}
}

View file

@ -28,6 +28,11 @@ class QuickLinksSettings extends Page
protected static ?string $title = 'Schnellzugriffe';
public static function canAccess(): bool
{
return auth()->user()?->can('appearance.manage') ?? false;
}
protected static ?string $slug = 'schnellzugriffe';
/** @var array<string, mixed>|null */

View file

@ -23,6 +23,11 @@ class SystemHealth extends Page
protected static ?string $title = 'Systemzustand';
public static function canAccess(): bool
{
return auth()->user()?->can('updates.manage') ?? false;
}
protected static ?string $slug = 'systemzustand';
/**

View file

@ -37,6 +37,11 @@ class Updates extends Page
protected static ?string $title = 'Aktualisierung';
public static function canAccess(): bool
{
return auth()->user()?->can('updates.manage') ?? false;
}
protected static ?string $slug = 'aktualisierung';
public string $licenseEmail = '';

View file

@ -0,0 +1,17 @@
<?php
namespace App\Filament\Resources\Roles\Pages;
use App\Filament\Resources\Roles\RoleResource;
use App\Support\Audit;
use Filament\Resources\Pages\CreateRecord;
class CreateRole extends CreateRecord
{
protected static string $resource = RoleResource::class;
protected function afterCreate(): void
{
Audit::log('role.created', ['role' => $this->record->name]);
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace App\Filament\Resources\Roles\Pages;
use App\Filament\Resources\Roles\RoleResource;
use App\Support\Audit;
use App\Support\Permissions\Permissions;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditRole extends EditRecord
{
protected static string $resource = RoleResource::class;
protected function afterSave(): void
{
Permissions::flush();
Audit::log('role.updated', [
'role' => $this->record->name,
'grants' => $this->record->grants()->get(['ability', 'resource_type', 'resource_id'])->toArray(),
]);
}
protected function getHeaderActions(): array
{
return [
DeleteAction::make()->visible(fn () => ! $this->record->is_system),
];
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace App\Filament\Resources\Roles\Pages;
use App\Filament\Pages\PermissionChecker;
use App\Filament\Resources\Roles\RoleResource;
use Filament\Actions\Action;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListRoles extends ListRecords
{
protected static string $resource = RoleResource::class;
protected function getHeaderActions(): array
{
return [
Action::make('checker')->label('Rechte prüfen')->color('gray')->url(PermissionChecker::getUrl()),
CreateAction::make()->label('Neue Rolle'),
];
}
}

View file

@ -0,0 +1,208 @@
<?php
namespace App\Filament\Resources\Roles;
use App\Filament\Resources\Roles\Pages\CreateRole;
use App\Filament\Resources\Roles\Pages\EditRole;
use App\Filament\Resources\Roles\Pages\ListRoles;
use App\Models\Grant;
use App\Models\Role;
use App\Models\User;
use App\Support\Abilities;
use App\Support\Permissions\Permissions;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use UnitEnum;
class RoleResource extends Resource
{
protected static ?string $model = Role::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedShieldCheck;
protected static string|UnitEnum|null $navigationGroup = 'Benutzer & Rechte';
protected static ?string $modelLabel = 'Rolle';
protected static ?string $pluralModelLabel = 'Rollen';
protected static ?string $slug = 'rollen';
protected static ?int $navigationSort = 2;
protected static ?string $recordTitleAttribute = 'name';
public static function form(Schema $schema): Schema
{
$abilities = app(Abilities::class);
return $schema
->columns(1)
->components([
Section::make('Rolle')
->columns(2)
->schema([
TextInput::make('name')->label('Name')->required()->maxLength(100)->disabled(fn (?Role $record) => $record?->is_system),
Textarea::make('description')->label('Beschreibung')->rows(2)->maxLength(500),
]),
Section::make('Globale Rechte')
->description('Gelten im ganzen Portal.')
->visible(fn (?Role $record) => ! $record?->isAdministration())
->schema([
CheckboxList::make('global_abilities')
->hiddenLabel()
->columns(2)
->options(fn () => collect($abilities->global())->map(fn (array $a) => $a['label'])->all())
->descriptions(fn () => collect($abilities->global())->map(fn (array $a) => $a['group'])->all())
->bulkToggleable()
->afterStateHydrated(fn (CheckboxList $component, ?Role $record) => $component->state(
$record?->grants()->whereNull('resource_type')->pluck('ability')->all() ?? []
))
->saveRelationshipsUsing(function (Role $record, ?array $state) {
$record->grants()->whereNull('resource_type')->where('ability', '!=', '*')->delete();
foreach (array_unique($state ?? []) as $ability) {
$record->grants()->create(['ability' => $ability]);
}
})
->dehydrated(false),
]),
Section::make('Rechte für einzelne Objekte')
->description('Zum Beispiel: Beiträge schreiben nur in der Kategorie „MAV-Info“.')
->visible(fn (?Role $record) => ! $record?->isAdministration() && $abilities->resourceTypes() !== [])
->schema([
Repeater::make('object_grants')
->hiddenLabel()
->columns(2)
->addActionLabel('Recht hinzufügen')
->defaultItems(0)
->schema([
Select::make('ability')
->label('Recht')
->required()
->live()
->options(fn () => collect($abilities->all())
->filter(fn (array $a) => $a['resource'] !== null)
->map(fn (array $a) => $a['group'].': '.$a['label'])
->all()),
Select::make('resource_ids')
->label('Für')
->multiple()
->required()
->options(function (Get $get) use ($abilities) {
$type = $abilities->all()[$get('ability')]['resource'] ?? null;
$options = $type ? ($abilities->resourceTypes()[$type]['options'])() : [];
return ['*' => 'Alle'] + $options;
}),
])
->afterStateHydrated(fn (Repeater $component, ?Role $record) => $component->state(
$record?->grants()->whereNotNull('resource_type')->get()
->groupBy('ability')
->map(fn ($grants, $ability) => [
'ability' => $ability,
'resource_ids' => $grants->map(fn (Grant $g) => $g->resource_id === null ? '*' : (string) $g->resource_id)->values()->all(),
])->values()->all() ?? []
))
->saveRelationshipsUsing(function (Role $record, ?array $state) use ($abilities) {
$record->grants()->whereNotNull('resource_type')->delete();
foreach ($state ?? [] as $item) {
$type = $abilities->all()[$item['ability'] ?? '']['resource'] ?? null;
if (! $type) {
continue;
}
$ids = in_array('*', (array) $item['resource_ids'], true) ? [null] : array_map('intval', (array) $item['resource_ids']);
foreach (array_unique($ids) as $id) {
$record->grants()->create(['ability' => $item['ability'], 'resource_type' => $type, 'resource_id' => $id]);
}
}
})
->dehydrated(false),
]),
Section::make('Mitglieder')
->description('Manuell zugewiesene Personen. Personen aus Identity-Provider-Gruppen kommen automatisch dazu.')
->schema([
Select::make('members')
->hiddenLabel()
->multiple()
->searchable()
->getSearchResultsUsing(fn (string $search) => User::query()
->where(fn ($q) => $q->where('name', 'like', "%{$search}%")->orWhere('email', 'like', "%{$search}%"))
->orderBy('name')->limit(50)->pluck('name', 'id')->all())
->getOptionLabelsUsing(fn (array $values) => User::query()->whereIn('id', $values)->pluck('name', 'id')->all())
->afterStateHydrated(fn (Select $component, ?Role $record) => $component->state(
$record?->users()->wherePivot('source', 'manual')->pluck('users.id')->all() ?? []
))
->rule(fn (?Role $record) => function (string $attribute, mixed $value, \Closure $fail) use ($record) {
if ($record?->isAdministration() && ! in_array(auth()->id(), array_map('intval', (array) $value), true)) {
$fail('Sie können sich nicht selbst aus der Rolle „Administration“ entfernen.');
}
})
->saveRelationshipsUsing(function (Role $record, ?array $state) {
$ids = array_map('intval', $state ?? []);
$current = $record->users()->wherePivot('source', 'manual')->pluck('users.id')->all();
foreach (array_diff($current, $ids) as $userId) {
$record->users()->wherePivot('source', 'manual')->detach($userId);
}
foreach (array_diff($ids, $current) as $userId) {
$record->users()->attach($userId, ['source' => 'manual', 'created_at' => now()]);
}
Permissions::flush();
})
->dehydrated(false),
]),
]);
}
public static function table(Table $table): Table
{
return $table
->defaultSort('name')
->modifyQueryUsing(fn ($query) => $query->withCount(['users', 'grants']))
->columns([
TextColumn::make('name')->label('Name')->searchable()->weight('medium')
->description(fn (Role $record) => $record->description),
IconColumn::make('is_system')->label('System')->boolean()->trueIcon(Heroicon::LockClosed)->falseIcon(false),
TextColumn::make('users_count')->label('Mitglieder'),
TextColumn::make('grants_count')->label('Rechte')
->formatStateUsing(fn (Role $record, $state) => $record->isAdministration() ? 'alle' : $state),
])
->recordActions([
EditAction::make(),
DeleteAction::make()->visible(fn (Role $record) => ! $record->is_system),
]);
}
public static function getPages(): array
{
return [
'index' => ListRoles::route('/'),
'create' => CreateRole::route('/neu'),
'edit' => EditRole::route('/{record}/bearbeiten'),
];
}
}

View file

@ -2,7 +2,9 @@
namespace App\Filament\Resources\Users\Schemas;
use App\Models\Role;
use App\Models\User;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
@ -47,10 +49,26 @@ class UserForm
->label('Aktiv')
->helperText('Deaktivierte Konten können sich nicht anmelden und erscheinen nicht im Portal.')
->default(true),
Toggle::make('is_admin')
->label('Administrator')
->helperText('Zugriff auf diesen Admin-Bereich. Wird später durch Rollen ersetzt.')
->disabled(fn (?User $record) => $record?->is(auth()->user()) ?? false),
Select::make('manual_roles')
->label('Rollen')
->helperText('Rollen sind additiv. Rollen aus Identity-Provider-Gruppen werden automatisch vergeben.')
->multiple()
->preload()
->options(fn () => Role::query()->orderByDesc('is_system')->orderBy('name')->pluck('name', 'id')->all())
->afterStateHydrated(function (Select $component, ?User $record) {
$component->state($record?->roles()->wherePivot('source', 'manual')->pluck('roles.id')->all() ?? []);
})
->rule(function (?User $record) {
// Die eigene Administrationsrolle kann man sich nicht selbst entziehen.
return function (string $attribute, mixed $value, \Closure $fail) use ($record) {
if ($record?->is(auth()->user()) && $record->hasRole(Role::ADMINISTRATION)
&& ! in_array(Role::administration()->id, array_map('intval', (array) $value), true)) {
$fail('Die eigene Rolle „Administration“ kann nicht entfernt werden.');
}
};
})
->saveRelationshipsUsing(fn (User $record, ?array $state) => $record->syncManualRoles(array_map('intval', $state ?? [])))
->dehydrated(false),
TextInput::make('password')
->label(fn (string $operation) => $operation === 'create' ? 'Passwort' : 'Neues Passwort')
->helperText(fn (string $operation) => $operation === 'create'

View file

@ -28,7 +28,7 @@ class UsersTable
TextColumn::make('job_title')->label('Funktion')->toggleable(),
TextColumn::make('department')->label('Abteilung')->sortable()->toggleable(),
TextColumn::make('location')->label('Standort')->sortable()->toggleable(isToggledHiddenByDefault: true),
IconColumn::make('is_admin')->label('Admin')->boolean(),
TextColumn::make('roles.name')->label('Rollen')->badge()->color('gray'),
IconColumn::make('is_active')->label('Aktiv')->boolean(),
TextColumn::make('last_login_at')
->label('Letzte Anmeldung')
@ -38,7 +38,7 @@ class UsersTable
])
->filters([
TernaryFilter::make('is_active')->label('Aktiv'),
TernaryFilter::make('is_admin')->label('Administrator'),
SelectFilter::make('roles')->label('Rolle')->relationship('roles', 'name'),
SelectFilter::make('department')
->label('Abteilung')
->options(fn () => User::query()->whereNotNull('department')->distinct()->orderBy('department')->pluck('department', 'department')->all()),

View file

@ -13,6 +13,7 @@ use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
class UserResource extends Resource
{
@ -20,6 +21,10 @@ class UserResource extends Resource
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedUsers;
protected static string|\UnitEnum|null $navigationGroup = 'Benutzer & Rechte';
protected static ?int $navigationSort = 1;
protected static ?string $modelLabel = 'Benutzer';
protected static ?string $pluralModelLabel = 'Benutzer';
@ -28,6 +33,11 @@ class UserResource extends Resource
protected static ?string $recordTitleAttribute = 'name';
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()->with('roles');
}
public static function form(Schema $schema): Schema
{
return UserForm::configure($schema);