Rollen ausschließen: bei Inhalten (Zielgruppen) und für ganze Module
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 3m45s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 3m39s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 4m25s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 4m21s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 6m49s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 6m59s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 6m21s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 6m30s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m10s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-26 19:30:11 +00:00
parent 19193b850b
commit 1877a0922f
113 changed files with 699 additions and 428 deletions

View file

@ -4,6 +4,7 @@ namespace App\Dashboard;
use App\Models\DashboardTile;
use App\Models\User;
use App\Plugins\PluginAccess;
use App\Support\Settings;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
@ -161,7 +162,7 @@ class Widgets
$layout = $this->layout();
foreach ($this->candidates($user) as $key => $widget) {
if (($layout[$key]['visible'] ?? true) === false || ($only && ! $only(['key' => $key, 'area' => $widget['area']]))) {
if (($layout[$key]['visible'] ?? true) === false || ($only && ! $only(['key' => $key, 'area' => $widget['area']])) || ! app(PluginAccess::class)->allows($key, $user)) {
continue;
}

View file

@ -23,23 +23,28 @@ class AudienceSection
->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).
// Alle 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'] ?? [],
'exclude_role' => $state['audience_exclude_role'] ?? [],
]);
})
->dehydrated(false);
$roles = fn () => Role::query()->orderBy('name')->pluck('name', 'id')->mapWithKeys(fn ($name, $id) => [(string) $id => $name])->all();
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('role', 'Rollen', $roles),
$field('department', 'Abteilungen', fn () => self::distinct('department')),
$field('location', 'Standorte', fn () => self::distinct('location')),
$field('exclude_role', 'Ausgeschlossene Rollen', $roles)
->helperText('Personen mit einer dieser Rollen sehen es nie – auch wenn eine Angabe oben passt. Beispiel: Klientinnen und Klienten von einer internen Seite ausschließen.'),
]);
}

View file

@ -2,10 +2,15 @@
namespace App\Filament\Pages;
use App\Models\Role;
use App\Plugins\PluginAccess;
use App\Plugins\PluginInstaller;
use App\Plugins\PluginManager;
use App\Plugins\PluginManifest;
use App\Support\Audit;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Support\Icons\Heroicon;
@ -38,6 +43,36 @@ class Plugins extends Page
return auth()->user()?->can('plugins.manage') ?? false;
}
/** Plugins ohne eigenen Bereich im Portal – für sie gibt es keinen „Zugang“. */
private const WITHOUT_ACCESS = ['ldap', 'oidc', 'saml', 'wordpress-import'];
public function accessAction(): Action
{
return Action::make('access')
->label('Zugang')
->icon(Heroicon::OutlinedNoSymbol)
->color('gray')
->size('sm')
->modalHeading(fn (array $arguments) => 'Zugang: '.(app(PluginManager::class)->find($arguments['slug'] ?? '')?->name ?? ''))
->modalDescription('Personen mit einer dieser Rollen sehen den Bereich nicht: kein Menüpunkt, keine Seiten, keine Kacheln auf der Startseite, keine Suchtreffer. Wer Plugins verwalten darf, ist nie ausgeschlossen.')
->fillForm(fn (array $arguments) => ['roles' => array_map('strval', app(PluginAccess::class)->excludedRoles($arguments['slug'] ?? ''))])
->schema([
Select::make('roles')
->label('Ausgeschlossene Rollen')
->multiple()
->searchable()
->options(fn () => Role::query()->orderBy('name')->pluck('name', 'id')->mapWithKeys(fn ($name, $id) => [(string) $id => $name])->all()),
])
->modalSubmitActionLabel('Speichern')
->action(function (array $data, array $arguments) {
$slug = (string) ($arguments['slug'] ?? '');
abort_unless(app(PluginManager::class)->find($slug), 404);
app(PluginAccess::class)->exclude($slug, $data['roles'] ?? []);
Audit::log('plugin.access', ['plugin' => $slug, 'excluded_roles' => array_map('intval', $data['roles'] ?? [])]);
Notification::make()->success()->title('Zugang gespeichert')->send();
});
}
public function activate(string $slug, PluginManager $plugins): void
{
$this->run(fn () => $plugins->activate($slug), 'Plugin aktiviert', 'Die Änderungen sind ab dem nächsten Seitenaufruf sichtbar.');
@ -95,6 +130,8 @@ class Plugins extends Page
'enabled' => $plugins->isEnabled($m->slug),
'problem' => $plugins->problem($m->slug) ?? (($issues = $m->incompatibilities()) ? implode(', ', $issues) : null),
'dependents' => $plugins->dependents($m->slug),
'accessible' => ! in_array($m->slug, self::WITHOUT_ACCESS, true),
'excluded' => ($ids = app(PluginAccess::class)->excludedRoles($m->slug)) ? Role::query()->whereIn('id', $ids)->orderBy('name')->pluck('name')->all() : [],
])->sortBy(fn (array $p) => [$p['manifest']->core ? 0 : 1, $p['manifest']->name])->values(),
'uploadsAllowed' => PluginInstaller::uploadsAllowed(),
];

View file

@ -0,0 +1,23 @@
<?php
namespace App\Http\Middleware;
use App\Plugins\PluginAccess;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Sperrt die Routen eines Plugins für ausgeschlossene Rollen (siehe PluginAccess).
*/
class EnsurePluginAccess
{
public function __construct(private readonly PluginAccess $access) {}
public function handle(Request $request, Closure $next, string $slug): Response
{
abort_unless($this->access->allows($slug, $request->user()), 403, 'Dieser Bereich steht Ihnen nicht zur Verfügung.');
return $next($request);
}
}

View file

@ -8,11 +8,16 @@ 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.
* „exclude_role“ schließt Personen mit dieser Rolle aus – immer, auch wenn eine
* andere Regel passt.
*/
#[Fillable(['resource_type', 'resource_id', 'rule_type', 'rule_value'])]
class Audience extends Model
{
public const TYPES = ['role' => 'Rolle', 'department' => 'Abteilung', 'location' => 'Standort'];
public const TYPES = ['role' => 'Rolle', 'department' => 'Abteilung', 'location' => 'Standort', 'exclude_role' => 'Ausgeschlossene Rolle'];
/** Regeln, von denen mindestens eine passen muss (die übrigen schließen aus) */
public const INCLUDE_TYPES = ['role', 'department', 'location'];
public $timestamps = false;
}

View file

@ -3,6 +3,7 @@
namespace App\Pagebuilder;
use App\Models\User;
use App\Plugins\PluginAccess;
use App\Support\Permissions\Audiences;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
@ -231,7 +232,7 @@ class Content
}
/**
* @return array{role?: list<string>, department?: list<string>, location?: list<string>}|null
* @return array{role?: list<string>, department?: list<string>, location?: list<string>, exclude_role?: list<string>}|null
*/
private function sanitizeVisibility(mixed $visibility): ?array
{
@ -241,7 +242,7 @@ class Content
$clean = [];
foreach (['role', 'department', 'location'] as $rule) {
foreach (['role', 'department', 'location', 'exclude_role'] as $rule) {
$values = array_values(array_unique(array_filter(array_map(
fn ($value) => is_scalar($value) ? mb_substr(trim((string) $value), 0, 150) : '',
(array) ($visibility[$rule] ?? []),
@ -267,7 +268,7 @@ class Content
$type = $this->blocks->get($block['type'] ?? '');
// Blöcke deaktivierter Plugins und fremde Zielgruppen einfach auslassen.
if (! $type || ! Audiences::matches($block['visibility'] ?? null, $user)) {
if (! $type || ! Audiences::matches($block['visibility'] ?? null, $user) || ! app(PluginAccess::class)->allows($type->key, $user)) {
continue;
}

View file

@ -0,0 +1,86 @@
<?php
namespace App\Plugins;
use App\Models\User;
use App\Support\Settings;
/**
* Module für Rollen sperren (Administration → Plugins → „Zugang“).
*
* Für ausgeschlossene Rollen verschwindet ein Plugin vollständig: Menüpunkt,
* Seiten (403), Startseiten-Kacheln, Pagebuilder-Blöcke und Suchtreffer. Zugeordnet
* wird über das Kürzel – Schlüssel wie „news“ oder „news.hero“ gehören zu „news“.
* Wer Plugins verwalten darf, ist nie ausgeschlossen.
*/
class PluginAccess
{
public const SETTING = 'plugins.excluded_roles';
/** @var array<int, list<string>> Person => gesperrte Kürzel (je Anfrage) */
private array $blocked = [];
public function __construct(private readonly Settings $settings) {}
/**
* @return array<string, list<int>> Kürzel => Rollen-IDs
*/
public function all(): array
{
return array_filter(array_map(
fn ($ids) => array_values(array_unique(array_map('intval', (array) $ids))),
(array) $this->settings->get(self::SETTING, []),
));
}
/**
* @return list<int>
*/
public function excludedRoles(string $slug): array
{
return $this->all()[$slug] ?? [];
}
/**
* @param list<int|string> $roleIds
*/
public function exclude(string $slug, array $roleIds): void
{
$all = $this->all();
$all[$slug] = array_values(array_unique(array_map('intval', $roleIds)));
$this->settings->set(self::SETTING, array_filter($all));
$this->blocked = [];
}
public function allows(string $key, ?User $user): bool
{
return ! in_array(self::slugOf($key), $this->blockedFor($user), true);
}
/**
* @return list<string>
*/
public function blockedFor(?User $user): array
{
if (! $user) {
return [];
}
return $this->blocked[$user->id] ??= (function () use ($user) {
$all = $this->all();
if ($all === [] || $user->can('plugins.manage')) {
return [];
}
$roleIds = array_map('intval', $user->permissions()->roleIds);
return array_values(array_keys(array_filter($all, fn (array $ids) => array_intersect($ids, $roleIds) !== [])));
})();
}
public static function slugOf(string $key): string
{
return explode('.', $key, 2)[0];
}
}

View file

@ -2,6 +2,7 @@
namespace App\Plugins;
use App\Http\Middleware\EnsurePluginAccess;
use App\Support\Audit;
use App\Support\Update\Filesystem;
use Illuminate\Contracts\Foundation\Application;
@ -204,7 +205,7 @@ class PluginManager
}
if (is_file($manifest->path.'/routes/web.php') && ! $this->app->routesAreCached()) {
Route::middleware('web')->group($manifest->path.'/routes/web.php');
Route::middleware(['web', EnsurePluginAccess::class.':'.$manifest->slug])->group($manifest->path.'/routes/web.php');
}
$plugin->boot();

View file

@ -10,6 +10,7 @@ use App\Identity\IdentityDrivers;
use App\Models\IdentityProvider;
use App\Models\User;
use App\Pagebuilder\Blocks;
use App\Plugins\PluginAccess;
use App\Search\GlobalSearch;
use App\Support\Abilities;
use App\Support\Avatars;
@ -55,6 +56,7 @@ class AppServiceProvider extends ServiceProvider
$this->app->singleton(ThemeCompiler::class);
$this->app->singleton(Avatars::class);
$this->app->singleton(QuickLinks::class);
$this->app->singleton(PluginAccess::class);
$this->app->singleton(GlobalSearch::class);
$this->app->singleton(LicenseStore::class);
$this->app->singleton(Permissions::class);

View file

@ -3,6 +3,7 @@
namespace App\Search;
use App\Models\User;
use App\Plugins\PluginAccess;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
@ -51,6 +52,10 @@ class GlobalSearch
$groups = [];
foreach (collect($this->sources)->sortBy('sort') as $key => $source) {
if (! app(PluginAccess::class)->allows($key, $user)) {
continue;
}
try {
$items = array_slice(array_values(($source['search'])($user, $query, $limit)), 0, $limit);
} catch (Throwable $e) {

View file

@ -4,6 +4,7 @@ namespace App\Support;
use App\Models\User;
use App\Plugins\Hooks;
use App\Plugins\PluginAccess;
use Closure;
use Illuminate\Http\Request;
@ -131,6 +132,7 @@ class Navigation
$items = collect($this->items)
->filter(fn (array $item) => $item['ability'] === null || ($user?->can($item['ability']) ?? false))
->filter(fn (array $item) => $item['visible'] === null || ($user !== null && ($item['visible'])($user)))
->filter(fn (array $item, string $key) => app(PluginAccess::class)->allows($key, $user))
->map(fn (array $item, string $key) => [
'key' => $key,
'label' => $item['label'],
@ -139,7 +141,11 @@ class Navigation
'sort' => $item['sort'],
]);
foreach ($this->providers as $provider) {
foreach ($this->providers as $key => $provider) {
if (! app(PluginAccess::class)->allows($key, $user)) {
continue;
}
$items = $items->merge($provider($request, $user));
}
@ -226,6 +232,7 @@ class Navigation
$item = $this->items[$key] ?? null;
if (! $item
|| ! app(PluginAccess::class)->allows($key, $user)
|| ($item['ability'] !== null && ! ($user?->can($item['ability']) ?? false))
|| ($item['visible'] !== null && ($user === null || ! ($item['visible'])($user)))) {
return null;

View file

@ -10,8 +10,9 @@ 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.
* mindestens eine erfüllt (Rolle, Abteilung oder Standort). Ausgeschlossene Rollen
* („exclude_role“) sehen es nie. Die Prüfung ist eine indizierte SQL-Bedingung –
* auch bei tausenden Personen schnell.
*/
class Audiences
{
@ -26,6 +27,7 @@ class Audiences
$query->where(function (Builder $q) use ($type, $column, $user) {
$q->whereNotExists(fn (QueryBuilder $sub) => $sub->from('audiences')
->where('audiences.resource_type', $type)
->whereIn('audiences.rule_type', Audience::INCLUDE_TYPES)
->whereColumn('audiences.resource_id', $column));
if ($user) {
@ -35,21 +37,23 @@ class Audiences
->where(fn (QueryBuilder $rules) => self::matching($rules, $user)));
}
});
if ($user) {
$query->whereNotExists(fn (QueryBuilder $sub) => $sub->from('audiences')
->where('audiences.resource_type', $type)
->whereColumn('audiences.resource_id', $column)
->where('audiences.rule_type', 'exclude_role')
->whereIn('audiences.rule_value', array_map('strval', $user->permissions()->roleIds) ?: ['-']));
}
}
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();
return self::matches(self::get($type, $id), $user);
}
/**
* @param array{role?: list<int|string>, department?: list<string>, location?: list<string>} $rules
* @param array{role?: list<int|string>, department?: list<string>, location?: list<string>, exclude_role?: list<int|string>} $rules
*/
public static function sync(string $type, int $id, array $rules): void
{
@ -63,11 +67,11 @@ class Audiences
}
/**
* @return array{role: list<string>, department: list<string>, location: list<string>}
* @return array{role: list<string>, department: list<string>, location: list<string>, exclude_role: list<string>}
*/
public static function get(string $type, int $id): array
{
$rules = ['role' => [], 'department' => [], 'location' => []];
$rules = ['role' => [], 'department' => [], 'location' => [], 'exclude_role' => []];
foreach (Audience::query()->where('resource_type', $type)->where('resource_id', $id)->get() as $audience) {
$rules[$audience->rule_type][] = $audience->rule_value;
@ -79,14 +83,14 @@ class Audiences
/**
* Alle Regeln eines Typs auf einmal – für gecachte Strukturen wie den Seitenbaum.
*
* @return array<int, array{role: list<string>, department: list<string>, location: list<string>}> ID => Regeln
* @return array<int, array{role: list<string>, department: list<string>, location: list<string>, exclude_role: list<string>}> ID => Regeln
*/
public static function allOfType(string $type): array
{
$result = [];
foreach (Audience::query()->where('resource_type', $type)->get(['resource_id', 'rule_type', 'rule_value']) as $audience) {
$result[$audience->resource_id] ??= ['role' => [], 'department' => [], 'location' => []];
$result[$audience->resource_id] ??= ['role' => [], 'department' => [], 'location' => [], 'exclude_role' => []];
$result[$audience->resource_id][$audience->rule_type][] = $audience->rule_value;
}
@ -96,13 +100,19 @@ class Audiences
/**
* Dieselbe Prüfung wie constrain()/allows(), aber in PHP auf bereits geladenen Regeln.
*
* @param array{role?: list<int|string>, department?: list<string>, location?: list<string>}|null $rules
* @param array{role?: list<int|string>, department?: list<string>, location?: list<string>, exclude_role?: list<int|string>}|null $rules
*/
public static function matches(?array $rules, ?User $user): bool
{
$rules = array_filter((array) $rules);
$include = array_intersect_key($rules, array_flip(Audience::INCLUDE_TYPES));
$roleIds = $user ? array_map('strval', $user->permissions()->roleIds) : [];
if ($rules === []) {
if (array_intersect(array_map('strval', $rules['exclude_role'] ?? []), $roleIds) !== []) {
return false;
}
if ($include === []) {
return true;
}
@ -110,11 +120,9 @@ class Audiences
return false;
}
$roleIds = array_map('strval', $user->permissions()->roleIds);
return array_intersect(array_map('strval', $rules['role'] ?? []), $roleIds) !== []
|| (filled($user->department) && in_array($user->department, $rules['department'] ?? [], true))
|| (filled($user->location) && in_array($user->location, $rules['location'] ?? [], true));
return array_intersect(array_map('strval', $include['role'] ?? []), $roleIds) !== []
|| (filled($user->department) && in_array($user->department, $include['department'] ?? [], true))
|| (filled($user->location) && in_array($user->location, $include['location'] ?? [], true));
}
private static function matching(QueryBuilder $rules, User $user): void

View file

@ -9,5 +9,5 @@ namespace App;
*/
final class Version
{
public const VERSION = '0.13.1';
public const VERSION = '0.14.0';
}