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
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:
parent
28ef1e4a20
commit
9ddc35a62c
112 changed files with 2408 additions and 267 deletions
53
app/Filament/Components/AudienceSection.php
Normal file
53
app/Filament/Components/AudienceSection.php
Normal 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();
|
||||
}
|
||||
}
|
||||
38
app/Filament/Components/RoleGrantSelect.php
Normal file
38
app/Filament/Components/RoleGrantSelect.php
Normal 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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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 */
|
||||
|
|
|
|||
|
|
@ -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 = '';
|
||||
|
|
|
|||
102
app/Filament/Pages/PermissionChecker.php
Normal file
102
app/Filament/Pages/PermissionChecker.php
Normal 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,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -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 */
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -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 = '';
|
||||
|
|
|
|||
17
app/Filament/Resources/Roles/Pages/CreateRole.php
Normal file
17
app/Filament/Resources/Roles/Pages/CreateRole.php
Normal 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]);
|
||||
}
|
||||
}
|
||||
30
app/Filament/Resources/Roles/Pages/EditRole.php
Normal file
30
app/Filament/Resources/Roles/Pages/EditRole.php
Normal 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),
|
||||
];
|
||||
}
|
||||
}
|
||||
22
app/Filament/Resources/Roles/Pages/ListRoles.php
Normal file
22
app/Filament/Resources/Roles/Pages/ListRoles.php
Normal 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'),
|
||||
];
|
||||
}
|
||||
}
|
||||
208
app/Filament/Resources/Roles/RoleResource.php
Normal file
208
app/Filament/Resources/Roles/RoleResource.php
Normal 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'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -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'
|
||||
|
|
|
|||
|
|
@ -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()),
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use App\Support\Audit;
|
||||
use App\Support\EnvFile;
|
||||
|
|
@ -130,10 +131,10 @@ class InstallController extends Controller
|
|||
'first_name' => $data['first_name'],
|
||||
'last_name' => $data['last_name'],
|
||||
'password' => $data['password'],
|
||||
'is_admin' => true,
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$admin->syncManualRoles([Role::administration()->id]);
|
||||
$settings->set('branding.portal_name', $data['portal_name']);
|
||||
|
||||
if (filled($data['license_email'] ?? null)) {
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ class HandleInertiaRequests extends Middleware
|
|||
'job_title' => $user->job_title,
|
||||
'avatar_url' => $user->avatarUrl(96),
|
||||
'theme' => $user->theme,
|
||||
'is_admin' => $user->is_admin,
|
||||
'can_admin' => $user->canAccessAdmin(),
|
||||
] : null,
|
||||
],
|
||||
'navigation' => fn () => $user ? $this->navigation->items($request) : [],
|
||||
|
|
|
|||
18
app/Models/Audience.php
Normal file
18
app/Models/Audience.php
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Zielgruppen-Regel: Objekt X ist sichtbar für Rolle/Abteilung/Standort Y.
|
||||
* Objekte ohne Regel sind für alle sichtbar; mehrere Regeln verknüpft ODER.
|
||||
*/
|
||||
#[Fillable(['resource_type', 'resource_id', 'rule_type', 'rule_value'])]
|
||||
class Audience extends Model
|
||||
{
|
||||
public const TYPES = ['role' => 'Rolle', 'department' => 'Abteilung', 'location' => 'Standort'];
|
||||
|
||||
public $timestamps = false;
|
||||
}
|
||||
35
app/Models/Grant.php
Normal file
35
app/Models/Grant.php
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Support\Permissions\Permissions;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Ein Recht einer Rolle: global (resource_type = null) oder für ein Objekt
|
||||
* (resource_id = null bedeutet: alle Objekte dieses Typs).
|
||||
*/
|
||||
#[Fillable(['role_id', 'ability', 'resource_type', 'resource_id', 'include_children'])]
|
||||
class Grant extends Model
|
||||
{
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::saved(fn () => Permissions::flush());
|
||||
static::deleted(fn () => Permissions::flush());
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['include_children' => 'boolean', 'resource_id' => 'integer'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Role, $this>
|
||||
*/
|
||||
public function role(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Role::class);
|
||||
}
|
||||
}
|
||||
70
app/Models/Role.php
Normal file
70
app/Models/Role.php
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Support\Permissions\Permissions;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
#[Fillable(['name', 'slug', 'description', 'is_system'])]
|
||||
class Role extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
public const ADMINISTRATION = 'administration';
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::saving(function (Role $role) {
|
||||
$role->slug = $role->slug ?: Str::slug($role->name, language: 'de');
|
||||
});
|
||||
|
||||
static::saved(fn () => Permissions::flush());
|
||||
static::deleted(fn () => Permissions::flush());
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['is_system' => 'boolean'];
|
||||
}
|
||||
|
||||
public static function administration(): self
|
||||
{
|
||||
$role = static::query()->firstOrCreate(['slug' => self::ADMINISTRATION], [
|
||||
'name' => 'Administration',
|
||||
'description' => 'Voller Zugriff auf alle Bereiche und Einstellungen.',
|
||||
'is_system' => true,
|
||||
]);
|
||||
|
||||
if (! $role->grants()->where('ability', '*')->exists()) {
|
||||
$role->grants()->create(['ability' => '*']);
|
||||
}
|
||||
|
||||
return $role;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsToMany<User, $this>
|
||||
*/
|
||||
public function users(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(User::class)->withPivot('source', 'source_ref', 'created_at');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<Grant, $this>
|
||||
*/
|
||||
public function grants(): HasMany
|
||||
{
|
||||
return $this->hasMany(Grant::class);
|
||||
}
|
||||
|
||||
public function isAdministration(): bool
|
||||
{
|
||||
return $this->slug === self::ADMINISTRATION;
|
||||
}
|
||||
}
|
||||
|
|
@ -3,6 +3,8 @@
|
|||
namespace App\Models;
|
||||
|
||||
use App\Support\Avatars;
|
||||
use App\Support\Permissions\Permissions;
|
||||
use App\Support\Permissions\PermissionSet;
|
||||
use Database\Factories\UserFactory;
|
||||
use Filament\Models\Contracts\FilamentUser;
|
||||
use Filament\Models\Contracts\HasAvatar;
|
||||
|
|
@ -12,6 +14,7 @@ use Illuminate\Database\Eloquent\Attributes\Hidden;
|
|||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Casts\Attribute;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
use Illuminate\Support\Str;
|
||||
|
|
@ -19,7 +22,7 @@ use Illuminate\Support\Str;
|
|||
#[Fillable([
|
||||
'name', 'first_name', 'last_name', 'email', 'password',
|
||||
'job_title', 'department', 'location', 'phone', 'mobile', 'about',
|
||||
'is_admin', 'is_active', 'theme',
|
||||
'is_active', 'theme',
|
||||
])]
|
||||
#[Hidden(['password', 'remember_token'])]
|
||||
class User extends Authenticatable implements FilamentUser, HasAvatar
|
||||
|
|
@ -47,18 +50,68 @@ class User extends Authenticatable implements FilamentUser, HasAvatar
|
|||
'email_verified_at' => 'datetime',
|
||||
'last_login_at' => 'datetime',
|
||||
'password' => 'hashed',
|
||||
'is_admin' => 'boolean',
|
||||
'is_active' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Vorläufig: Zugriff auf das Admin-Backend über das Flag is_admin.
|
||||
* Wird in Phase 2 durch das Rollen- und Rechtesystem ersetzt.
|
||||
* Admin-Backend: für alle mit irgendeinem Recht (z. B. Redaktion einer
|
||||
* Kategorie). Was sie dort sehen, regeln die Policies der einzelnen Seiten.
|
||||
*/
|
||||
public function canAccessPanel(Panel $panel): bool
|
||||
{
|
||||
return $this->is_admin && $this->is_active;
|
||||
return $this->canAccessAdmin();
|
||||
}
|
||||
|
||||
public function canAccessAdmin(): bool
|
||||
{
|
||||
$permissions = $this->permissions();
|
||||
|
||||
return $this->is_active && ($permissions->global !== [] || $permissions->hasAnyObjectGrant());
|
||||
}
|
||||
|
||||
public function permissions(): PermissionSet
|
||||
{
|
||||
return app(Permissions::class)->for($this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsToMany<Role, $this>
|
||||
*/
|
||||
public function roles(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Role::class)->withPivot('source', 'source_ref', 'created_at');
|
||||
}
|
||||
|
||||
public function hasRole(string $slug): bool
|
||||
{
|
||||
return $this->roles()->where('slug', $slug)->exists();
|
||||
}
|
||||
|
||||
public function isAdministrator(): bool
|
||||
{
|
||||
return $this->permissions()->isSuperuser();
|
||||
}
|
||||
|
||||
/**
|
||||
* Manuell vergebene Rollen setzen. Rollen aus Identity-Provider-Gruppen
|
||||
* (Quelle „idp“) bleiben unberührt – Rollen sind additiv.
|
||||
*
|
||||
* @param list<int> $roleIds
|
||||
*/
|
||||
public function syncManualRoles(array $roleIds): void
|
||||
{
|
||||
$current = $this->roles()->wherePivot('source', 'manual')->pluck('roles.id')->all();
|
||||
|
||||
foreach (array_diff($current, $roleIds) as $roleId) {
|
||||
$this->roles()->wherePivot('source', 'manual')->detach($roleId);
|
||||
}
|
||||
|
||||
foreach (array_diff($roleIds, $current) as $roleId) {
|
||||
$this->roles()->attach($roleId, ['source' => 'manual', 'created_at' => now()]);
|
||||
}
|
||||
|
||||
Permissions::flush();
|
||||
}
|
||||
|
||||
public function getFilamentAvatarUrl(): ?string
|
||||
|
|
|
|||
37
app/Policies/RolePolicy.php
Normal file
37
app/Policies/RolePolicy.php
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
|
||||
class RolePolicy
|
||||
{
|
||||
public function viewAny(User $user): bool
|
||||
{
|
||||
return $user->can('roles.manage');
|
||||
}
|
||||
|
||||
public function view(User $user, Role $role): bool
|
||||
{
|
||||
return $user->can('roles.manage');
|
||||
}
|
||||
|
||||
public function create(User $user): bool
|
||||
{
|
||||
return $user->can('roles.manage');
|
||||
}
|
||||
|
||||
public function update(User $user, Role $role): bool
|
||||
{
|
||||
return $user->can('roles.manage');
|
||||
}
|
||||
|
||||
/**
|
||||
* Systemrollen (Administration) lassen sich nicht löschen.
|
||||
*/
|
||||
public function delete(User $user, Role $role): bool
|
||||
{
|
||||
return $user->can('roles.manage') && ! $role->is_system;
|
||||
}
|
||||
}
|
||||
33
app/Policies/UserPolicy.php
Normal file
33
app/Policies/UserPolicy.php
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Models\User;
|
||||
|
||||
class UserPolicy
|
||||
{
|
||||
public function viewAny(User $user): bool
|
||||
{
|
||||
return $user->can('users.manage');
|
||||
}
|
||||
|
||||
public function view(User $user, User $model): bool
|
||||
{
|
||||
return $user->can('users.manage');
|
||||
}
|
||||
|
||||
public function create(User $user): bool
|
||||
{
|
||||
return $user->can('users.manage');
|
||||
}
|
||||
|
||||
public function update(User $user, User $model): bool
|
||||
{
|
||||
return $user->can('users.manage');
|
||||
}
|
||||
|
||||
public function delete(User $user, User $model): bool
|
||||
{
|
||||
return $user->can('users.manage') && ! $model->is($user);
|
||||
}
|
||||
}
|
||||
|
|
@ -5,11 +5,14 @@ namespace App\Providers;
|
|||
use App\Dashboard\CoreWidgets;
|
||||
use App\Dashboard\Widgets;
|
||||
use App\Models\User;
|
||||
use App\Support\Abilities;
|
||||
use App\Support\Avatars;
|
||||
use App\Support\BackgroundTasks;
|
||||
use App\Support\Branding;
|
||||
use App\Support\Installation;
|
||||
use App\Support\License\LicenseStore;
|
||||
use App\Support\Permissions\PermissionResource;
|
||||
use App\Support\Permissions\Permissions;
|
||||
use App\Support\QuickLinks;
|
||||
use App\Support\Settings;
|
||||
use App\Support\Update\InstalledVersion;
|
||||
|
|
@ -39,6 +42,7 @@ class AppServiceProvider extends ServiceProvider
|
|||
$this->app->singleton(Avatars::class);
|
||||
$this->app->singleton(QuickLinks::class);
|
||||
$this->app->singleton(LicenseStore::class);
|
||||
$this->app->singleton(Permissions::class);
|
||||
$this->app->singleton(BackgroundTasks::class);
|
||||
$this->app->singleton(InstalledVersion::class);
|
||||
$this->app->singleton(UpdateProgress::class);
|
||||
|
|
@ -52,9 +56,22 @@ class AppServiceProvider extends ServiceProvider
|
|||
// N+1-Abfragen in Entwicklung und Tests sofort sichtbar machen (docs/PLAN.md, Performance).
|
||||
Model::preventLazyLoading(! $this->app->isProduction());
|
||||
|
||||
// Vorläufig: Administratoren über is_admin – wird in Phase 2 durch Rollen ersetzt.
|
||||
Gate::define('admin', fn (User $user) => $user->is_admin && $user->is_active);
|
||||
Gate::before(fn (User $user) => $user->is_admin && $user->is_active ? true : null);
|
||||
// Rechte aus Rollen (App\Support\Abilities) entscheidet das Rechtesystem – Administration
|
||||
// hat sie alle. Alles andere (z. B. „delete“ auf einem Modell) entscheiden die Policies,
|
||||
// damit Regeln wie „Systemrollen nie löschen“ auch für Administratoren gelten.
|
||||
Gate::before(function (User $user, string $ability, array $arguments) {
|
||||
if (! $user->is_active) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (! $this->app->make(Abilities::class)->exists($ability)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
[$type, $id] = PermissionResource::from($arguments);
|
||||
|
||||
return $user->permissions()->can($ability, $type, $id);
|
||||
});
|
||||
|
||||
Password::defaults(fn () => Password::min(10)->letters()->numbers());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ namespace App\Providers\Filament;
|
|||
|
||||
use App\Filament\AvatarProviders\InitialsAvatarProvider;
|
||||
use App\Filament\Pages\Feedback;
|
||||
use App\Filament\Resources\Roles\RoleResource;
|
||||
use App\Filament\Resources\Users\UserResource;
|
||||
use App\Plugins\PluginManager;
|
||||
use App\Support\Branding;
|
||||
use Filament\Actions\Action;
|
||||
|
|
@ -40,7 +42,7 @@ class AdminPanelProvider extends PanelProvider
|
|||
->colors(fn () => [
|
||||
'primary' => app(Branding::class)->palette(),
|
||||
])
|
||||
->navigationGroups(['Inhalte', 'Portal', 'System', 'Hilfe'])
|
||||
->navigationGroups(['Inhalte', 'Benutzer & Rechte', 'Portal', 'System', 'Hilfe'])
|
||||
->databaseNotifications()
|
||||
->userMenuItems([
|
||||
Action::make('feedback')
|
||||
|
|
@ -54,7 +56,13 @@ class AdminPanelProvider extends PanelProvider
|
|||
->icon(Heroicon::OutlinedArrowTopRightOnSquare)
|
||||
->sort(100),
|
||||
])
|
||||
->discoverResources(in: app_path('Filament/Resources'), for: 'App\Filament\Resources')
|
||||
// Kern-Ressourcen ausdrücklich registrieren statt das Verzeichnis zu durchsuchen:
|
||||
// Der Self-Updater löscht nie Dateien, verschobene Ressourcen (z. B. nach
|
||||
// plugins-core/) blieben sonst als Doppelgänger liegen und würden mitgeladen.
|
||||
->resources([
|
||||
UserResource::class,
|
||||
RoleResource::class,
|
||||
])
|
||||
->discoverPages(in: app_path('Filament/Pages'), for: 'App\Filament\Pages')
|
||||
->pages([
|
||||
Dashboard::class,
|
||||
|
|
|
|||
|
|
@ -19,7 +19,6 @@ class Abilities
|
|||
|
||||
public function __construct()
|
||||
{
|
||||
$this->define('admin.access', 'Administrationsbereich öffnen', 'System');
|
||||
$this->define('users.manage', 'Benutzer verwalten', 'System');
|
||||
$this->define('roles.manage', 'Rollen und Rechte verwalten', 'System');
|
||||
$this->define('plugins.manage', 'Plugins verwalten und installieren', 'System');
|
||||
|
|
|
|||
93
app/Support/Permissions/Audiences.php
Normal file
93
app/Support/Permissions/Audiences.php
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Permissions;
|
||||
|
||||
use App\Models\Audience;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Query\Builder as QueryBuilder;
|
||||
|
||||
/**
|
||||
* Zielgruppen: Ein Objekt ohne Regeln sehen alle. Mit Regeln sieht es, wer
|
||||
* mindestens eine erfüllt (Rolle, Abteilung oder Standort). Die Prüfung ist eine
|
||||
* indizierte SQL-Bedingung – auch bei tausenden Personen schnell.
|
||||
*/
|
||||
class Audiences
|
||||
{
|
||||
/**
|
||||
* Schränkt eine Abfrage auf Objekte ein, die die Person sehen darf.
|
||||
*
|
||||
* @param Builder<Model> $query
|
||||
* @param string $column Spalte mit der ID des Objekts, dessen Zielgruppe gilt
|
||||
*/
|
||||
public static function constrain(Builder $query, string $type, string $column, ?User $user): void
|
||||
{
|
||||
$query->where(function (Builder $q) use ($type, $column, $user) {
|
||||
$q->whereNotExists(fn (QueryBuilder $sub) => $sub->from('audiences')
|
||||
->where('audiences.resource_type', $type)
|
||||
->whereColumn('audiences.resource_id', $column));
|
||||
|
||||
if ($user) {
|
||||
$q->orWhereExists(fn (QueryBuilder $sub) => $sub->from('audiences')
|
||||
->where('audiences.resource_type', $type)
|
||||
->whereColumn('audiences.resource_id', $column)
|
||||
->where(fn (QueryBuilder $rules) => self::matching($rules, $user)));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static function allows(string $type, int $id, ?User $user): bool
|
||||
{
|
||||
$rules = Audience::query()->where('resource_type', $type)->where('resource_id', $id);
|
||||
|
||||
if (! (clone $rules)->exists()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $user !== null && $rules->where(fn ($q) => self::matching($q->getQuery(), $user))->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{role?: list<int|string>, department?: list<string>, location?: list<string>} $rules
|
||||
*/
|
||||
public static function sync(string $type, int $id, array $rules): void
|
||||
{
|
||||
Audience::query()->where('resource_type', $type)->where('resource_id', $id)->delete();
|
||||
|
||||
foreach (array_keys(Audience::TYPES) as $ruleType) {
|
||||
foreach (array_unique(array_filter((array) ($rules[$ruleType] ?? []), fn ($v) => $v !== null && $v !== '')) as $value) {
|
||||
Audience::query()->create(['resource_type' => $type, 'resource_id' => $id, 'rule_type' => $ruleType, 'rule_value' => (string) $value]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{role: list<string>, department: list<string>, location: list<string>}
|
||||
*/
|
||||
public static function get(string $type, int $id): array
|
||||
{
|
||||
$rules = ['role' => [], 'department' => [], 'location' => []];
|
||||
|
||||
foreach (Audience::query()->where('resource_type', $type)->where('resource_id', $id)->get() as $audience) {
|
||||
$rules[$audience->rule_type][] = $audience->rule_value;
|
||||
}
|
||||
|
||||
return $rules;
|
||||
}
|
||||
|
||||
private static function matching(QueryBuilder $rules, User $user): void
|
||||
{
|
||||
$roleIds = array_map('strval', $user->permissions()->roleIds);
|
||||
|
||||
$rules->where(fn (QueryBuilder $q) => $q->where('audiences.rule_type', 'role')->whereIn('audiences.rule_value', $roleIds ?: ['-']));
|
||||
|
||||
if (filled($user->department)) {
|
||||
$rules->orWhere(fn (QueryBuilder $q) => $q->where('audiences.rule_type', 'department')->where('audiences.rule_value', $user->department));
|
||||
}
|
||||
|
||||
if (filled($user->location)) {
|
||||
$rules->orWhere(fn (QueryBuilder $q) => $q->where('audiences.rule_type', 'location')->where('audiences.rule_value', $user->location));
|
||||
}
|
||||
}
|
||||
}
|
||||
36
app/Support/Permissions/PermissionResource.php
Normal file
36
app/Support/Permissions/PermissionResource.php
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Permissions;
|
||||
|
||||
/**
|
||||
* Übersetzt die Argumente eines Rechte-Checks in Objekttyp und ID:
|
||||
* $user->can('news.post.create', $category) – Modell mit permissionResource()
|
||||
* $user->can('news.post.create', ['news_category', 5]) – Laravel reicht das als zwei Argumente durch
|
||||
*/
|
||||
final class PermissionResource
|
||||
{
|
||||
/**
|
||||
* @param array<int, mixed> $arguments
|
||||
* @return array{0: string|null, 1: int|null}
|
||||
*/
|
||||
public static function from(array $arguments): array
|
||||
{
|
||||
$first = $arguments[0] ?? null;
|
||||
|
||||
if (is_object($first) && method_exists($first, 'permissionResource')) {
|
||||
return $first->permissionResource();
|
||||
}
|
||||
|
||||
if (is_array($first)) {
|
||||
return self::from($first);
|
||||
}
|
||||
|
||||
if (is_string($first)) {
|
||||
$id = $arguments[1] ?? null;
|
||||
|
||||
return [$first, is_numeric($id) ? (int) $id : null];
|
||||
}
|
||||
|
||||
return [null, null];
|
||||
}
|
||||
}
|
||||
75
app/Support/Permissions/PermissionSet.php
Normal file
75
app/Support/Permissions/PermissionSet.php
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Permissions;
|
||||
|
||||
/**
|
||||
* Vorberechnete Rechte einer Person (gecacht, siehe Permissions).
|
||||
*/
|
||||
final class PermissionSet
|
||||
{
|
||||
/**
|
||||
* @param list<int> $roleIds
|
||||
* @param array<string, true> $global Ability => true („*“ = alles)
|
||||
* @param array<string, array<string, list<int>|true>> $objects Ability => Typ => IDs oder true (alle)
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly array $roleIds,
|
||||
public readonly array $global,
|
||||
public readonly array $objects,
|
||||
) {}
|
||||
|
||||
public function isSuperuser(): bool
|
||||
{
|
||||
return isset($this->global['*']);
|
||||
}
|
||||
|
||||
public function can(string $ability, ?string $resourceType = null, ?int $resourceId = null): bool
|
||||
{
|
||||
if ($this->isSuperuser() || isset($this->global[$ability])) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($resourceType === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$ids = $this->objects[$ability][$resourceType] ?? null;
|
||||
|
||||
return $ids === true || ($ids !== null && ($resourceId === null ? $ids !== [] : in_array($resourceId, $ids, true)));
|
||||
}
|
||||
|
||||
/**
|
||||
* IDs der Objekte, für die das Recht gilt – für Abfragen („nur meine Kategorien“).
|
||||
*
|
||||
* @return list<int>|true true = alle
|
||||
*/
|
||||
public function ids(string $ability, string $resourceType): array|true
|
||||
{
|
||||
if ($this->isSuperuser() || isset($this->global[$ability])) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->objects[$ability][$resourceType] ?? [];
|
||||
}
|
||||
|
||||
public function hasAnyObjectGrant(): bool
|
||||
{
|
||||
return $this->objects !== [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return ['roleIds' => $this->roleIds, 'global' => $this->global, 'objects' => $this->objects];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
return new self($data['roleIds'], $data['global'], $data['objects']);
|
||||
}
|
||||
}
|
||||
72
app/Support/Permissions/Permissions.php
Normal file
72
app/Support/Permissions/Permissions.php
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Permissions;
|
||||
|
||||
use App\Models\Grant;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Löst die effektiven Rechte einer Person auf: Vereinigung aller Rollen (manuell
|
||||
* und über IdP-Gruppen) – es gibt keine Verbote. Das Ergebnis wird je Person
|
||||
* gecacht; jede Änderung an Rollen, Rechten oder Zuweisungen erhöht die
|
||||
* Version und macht damit alle Caches auf einen Schlag ungültig.
|
||||
*/
|
||||
class Permissions
|
||||
{
|
||||
private const VERSION_KEY = 'permissions.version';
|
||||
|
||||
/** @var array<int, PermissionSet> */
|
||||
private array $resolved = [];
|
||||
|
||||
public function for(User $user): PermissionSet
|
||||
{
|
||||
if (! $user->is_active) {
|
||||
return new PermissionSet([], [], []);
|
||||
}
|
||||
|
||||
return $this->resolved[$user->id] ??= PermissionSet::fromArray(Cache::rememberForever(
|
||||
'permissions.user.'.$user->id.'.'.self::version(),
|
||||
fn () => $this->resolve($user)->toArray(),
|
||||
));
|
||||
}
|
||||
|
||||
public static function flush(): void
|
||||
{
|
||||
Cache::forever(self::VERSION_KEY, self::version() + 1);
|
||||
app(self::class)->resolved = [];
|
||||
}
|
||||
|
||||
public static function version(): int
|
||||
{
|
||||
return (int) Cache::get(self::VERSION_KEY, 1);
|
||||
}
|
||||
|
||||
private function resolve(User $user): PermissionSet
|
||||
{
|
||||
$roleIds = DB::table('role_user')->where('user_id', $user->id)->distinct()->pluck('role_id')->map(fn ($id) => (int) $id)->all();
|
||||
$global = [];
|
||||
$objects = [];
|
||||
|
||||
foreach (Grant::query()->whereIn('role_id', $roleIds)->get(['ability', 'resource_type', 'resource_id']) as $grant) {
|
||||
if ($grant->resource_type === null) {
|
||||
$global[$grant->ability] = true;
|
||||
} elseif ($grant->resource_id === null) {
|
||||
$objects[$grant->ability][$grant->resource_type] = true;
|
||||
} elseif (($objects[$grant->ability][$grant->resource_type] ?? null) !== true) {
|
||||
$objects[$grant->ability][$grant->resource_type][] = $grant->resource_id;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($objects as $ability => $types) {
|
||||
foreach ($types as $type => $ids) {
|
||||
if (is_array($ids)) {
|
||||
$objects[$ability][$type] = array_values(array_unique($ids));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new PermissionSet($roleIds, $global, $objects);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue