Compare commits
2 commits
cc0020458f
...
9ddc35a62c
| Author | SHA1 | Date | |
|---|---|---|---|
| 9ddc35a62c | |||
| 28ef1e4a20 |
204 changed files with 4978 additions and 648 deletions
10
CHANGELOG.md
10
CHANGELOG.md
|
|
@ -4,6 +4,16 @@ Neueste Version oben. Jeder Abschnitt beginnt mit `## MAJOR.MINOR.PATCH` und
|
|||
enthält kurze Stichpunkte für Anwenderinnen und Anwender – keine Commit-Texte.
|
||||
Der Self-Updater zeigt diese Abschnitte bei neuen Versionen an.
|
||||
|
||||
## 0.3.0
|
||||
|
||||
- Rollen und Rechte: eigene Rollen anlegen, Rechte global oder für einzelne Kategorien vergeben – z. B. darf die MAV nur in „MAV-Info“ schreiben
|
||||
- Veröffentlichen ist ein eigenes Recht; ohne dieses Recht bleiben Beiträge Entwürfe
|
||||
- Sichtbarkeit: Kategorien und Termine lassen sich auf Rollen, Abteilungen oder Standorte beschränken
|
||||
- „Rechte prüfen“ zeigt, was eine Person darf und warum
|
||||
- Redaktion und Sichtbarkeit direkt an der Kategorie einstellen
|
||||
- Plugins: Funktionen lassen sich einzeln aktivieren und deaktivieren, eigene Plugins per ZIP installieren
|
||||
- Neuigkeiten und Termine sind jetzt mitgelieferte Plugins
|
||||
|
||||
## 0.2.0
|
||||
|
||||
- Aktualisierung per Klick im Admin-Bereich – ohne Serverzugang, mit Wartungsseite und Fortschrittsanzeige
|
||||
|
|
|
|||
|
|
@ -9,3 +9,6 @@
|
|||
- UI-Texte Deutsch mit Umlauten, Schlüssel/Routen ASCII. Kein Node/Shell auf dem Kundenserver voraussetzen.
|
||||
- Design: Tailwind + shadcn-vue (`resources/js/components/ui`), Lucide-Icons, Inter. Farben nur über Tokens
|
||||
(`brand`, `brand-text`, `card`, `muted-foreground` …); Markenfarbe kommt serverseitig als CSS-Variable.
|
||||
- Funktionen als Plugins: mitgeliefert in `plugins-core/<slug>` (Namespace `Inhaus\Plugins\…`), Kunden in `plugins/`. Kern stellt
|
||||
Registries bereit (Navigation, Dashboard\\Widgets, Abilities) – siehe `docs/PLUGINS.md`.
|
||||
- Rechte immer über `$user->can('ability', ['typ', id])` bzw. Policies; Sichtbarkeit über `Audiences::constrain`.
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ shadcn-vue im Portal, MySQL/MariaDB, Apache.
|
|||
|
||||
- Projektplan: [`docs/PLAN.md`](docs/PLAN.md)
|
||||
- Installation beim Kunden (auch Shared Hosting): [`docs/INSTALLATION.md`](docs/INSTALLATION.md)
|
||||
- Plugins entwickeln: [`docs/PLUGINS.md`](docs/PLUGINS.md)
|
||||
- Mitarbeit, Entwicklungsumgebung und Release-Ablauf: [`CONTRIBUTING.md`](CONTRIBUTING.md)
|
||||
- Änderungen: [`CHANGELOG.md`](CHANGELOG.md)
|
||||
|
||||
|
|
|
|||
47
app/Dashboard/CoreWidgets.php
Normal file
47
app/Dashboard/CoreWidgets.php
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
<?php
|
||||
|
||||
namespace App\Dashboard;
|
||||
|
||||
use App\Http\Resources\PersonResource;
|
||||
use App\Models\User;
|
||||
use App\Support\QuickLinks;
|
||||
|
||||
/**
|
||||
* Kacheln des Kerns. Plugins ergänzen weitere über App\Dashboard\Widgets.
|
||||
*/
|
||||
class CoreWidgets
|
||||
{
|
||||
public static function register(Widgets $widgets): void
|
||||
{
|
||||
$widgets->add('core.greeting', 'core::Greeting', 'aside', sort: 0, props: fn (User $user) => [
|
||||
'profile' => [
|
||||
'job_title' => $user->job_title,
|
||||
'department' => $user->department,
|
||||
'location' => $user->location,
|
||||
'avatar_url' => $user->avatarUrl(256),
|
||||
],
|
||||
], mobileSort: 0);
|
||||
|
||||
$widgets->add('core.quick-links', 'core::QuickLinks', 'main', sort: 10, props: fn () => [
|
||||
'links' => app(QuickLinks::class)->all(),
|
||||
], mobileSort: 40);
|
||||
|
||||
$widgets->add('core.new-colleagues', 'core::NewColleagues', 'main', sort: 90, props: function (User $user) {
|
||||
$people = User::query()
|
||||
->active()
|
||||
->whereKeyNot($user->getKey())
|
||||
->where('created_at', '>=', now()->subDays(90))
|
||||
->latest()
|
||||
->limit(6)
|
||||
->get();
|
||||
|
||||
return $people->isEmpty() ? null : ['people' => PersonResource::collection($people)->resolve()];
|
||||
}, mobileSort: 60);
|
||||
|
||||
$widgets->add('core.profile-incomplete', 'core::ProfileIncomplete', 'aside', sort: 50, props: fn (User $user) => $user->avatar_path && $user->job_title ? null : [], mobileSort: 70);
|
||||
|
||||
$widgets->add('core.people-search', 'core::PeopleSearch', 'aside', sort: 60, props: fn () => [
|
||||
'count' => User::query()->active()->count(),
|
||||
], mobileSort: 80);
|
||||
}
|
||||
}
|
||||
72
app/Dashboard/Widgets.php
Normal file
72
app/Dashboard/Widgets.php
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
<?php
|
||||
|
||||
namespace App\Dashboard;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Kacheln der Startseite als Registry.
|
||||
*
|
||||
* Bereiche (siehe resources/js/pages/Dashboard.vue):
|
||||
* hero – groß links oben (z. B. Slider) feed – neben hero
|
||||
* main – volle Breite der linken Spalte aside – rechte Spalte
|
||||
*
|
||||
* Die Props-Funktion liefert die Daten der Kachel oder null, wenn sie für
|
||||
* diese Person nichts anzuzeigen hat.
|
||||
*/
|
||||
class Widgets
|
||||
{
|
||||
public const AREAS = ['hero', 'feed', 'main', 'aside'];
|
||||
|
||||
/** @var array<string, array{component: string, area: string, sort: int, mobileSort: int, props: callable}> */
|
||||
private array $widgets = [];
|
||||
|
||||
/**
|
||||
* @param string $component Vue-Komponente, z. B. „core::QuickLinks“ oder „news::Hero“
|
||||
* @param callable(User, Request): (array<string, mixed>|null) $props
|
||||
* @param int|null $mobileSort Reihenfolge in der einspaltigen Mobilansicht (Standard: nach Bereich)
|
||||
*/
|
||||
public function add(string $key, string $component, string $area, int $sort, callable $props, ?int $mobileSort = null): void
|
||||
{
|
||||
if (! in_array($area, self::AREAS, true)) {
|
||||
throw new \InvalidArgumentException("Unbekannter Bereich „{$area}“ für Kachel {$key}.");
|
||||
}
|
||||
|
||||
$mobileSort ??= ['hero' => 10, 'feed' => 20, 'aside' => 30, 'main' => 50][$area] + $sort;
|
||||
|
||||
$this->widgets[$key] = compact('component', 'area', 'sort', 'mobileSort', 'props');
|
||||
}
|
||||
|
||||
public function remove(string $key): void
|
||||
{
|
||||
unset($this->widgets[$key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{key: string, component: string, area: string, mobileSort: int, props: array<string, mixed>}>
|
||||
*/
|
||||
public function resolve(User $user, Request $request): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach (collect($this->widgets)->sortBy('sort') as $key => $widget) {
|
||||
try {
|
||||
$props = ($widget['props'])($user, $request);
|
||||
} catch (Throwable $e) {
|
||||
// Eine fehlerhafte Kachel darf die Startseite nicht lahmlegen.
|
||||
Log::error("Startseiten-Kachel {$key} fehlgeschlagen: ".$e->getMessage(), ['exception' => $e]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($props !== null) {
|
||||
$result[] = ['key' => $key, 'component' => $widget['component'], 'area' => $widget['area'], 'mobileSort' => $widget['mobileSort'], 'props' => $props];
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
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,
|
||||
];
|
||||
}
|
||||
}
|
||||
102
app/Filament/Pages/Plugins.php
Normal file
102
app/Filament/Pages/Plugins.php
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Plugins\PluginInstaller;
|
||||
use App\Plugins\PluginManager;
|
||||
use App\Plugins\PluginManifest;
|
||||
use BackedEnum;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
|
||||
use Livewire\WithFileUploads;
|
||||
use Throwable;
|
||||
use UnitEnum;
|
||||
|
||||
class Plugins extends Page
|
||||
{
|
||||
use WithFileUploads;
|
||||
|
||||
protected string $view = 'filament.pages.plugins';
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedPuzzlePiece;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'System';
|
||||
|
||||
protected static ?int $navigationSort = 5;
|
||||
|
||||
protected static ?string $title = 'Plugins';
|
||||
|
||||
protected static ?string $slug = 'plugins';
|
||||
|
||||
/** @var TemporaryUploadedFile|null */
|
||||
public $archive = null;
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return auth()->user()?->can('plugins.manage') ?? false;
|
||||
}
|
||||
|
||||
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.');
|
||||
}
|
||||
|
||||
public function deactivate(string $slug, PluginManager $plugins): void
|
||||
{
|
||||
$this->run(fn () => $plugins->deactivate($slug), 'Plugin deaktiviert', 'Die Daten bleiben erhalten und stehen nach erneuter Aktivierung wieder zur Verfügung.');
|
||||
}
|
||||
|
||||
public function delete(string $slug, bool $removeData, PluginManager $plugins): void
|
||||
{
|
||||
$this->run(fn () => $plugins->delete($slug, $removeData), 'Plugin gelöscht', $removeData ? 'Das Plugin und seine Daten wurden entfernt.' : 'Die Daten des Plugins sind noch in der Datenbank.');
|
||||
}
|
||||
|
||||
public function upload(PluginInstaller $installer): void
|
||||
{
|
||||
$this->validate(['archive' => ['required', 'file', 'mimes:zip', 'max:51200']], attributes: ['archive' => 'ZIP-Archiv']);
|
||||
|
||||
try {
|
||||
$manifest = $installer->install($this->archive->getRealPath());
|
||||
$this->archive = null;
|
||||
|
||||
Notification::make()
|
||||
->success()
|
||||
->title("„{$manifest->name}“ {$manifest->version} installiert")
|
||||
->body('Das Plugin kann jetzt aktiviert werden.')
|
||||
->send();
|
||||
} catch (Throwable $e) {
|
||||
$this->addError('archive', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private function run(callable $action, string $title, string $body): void
|
||||
{
|
||||
try {
|
||||
$action();
|
||||
Notification::make()->success()->title($title)->body($body)->send();
|
||||
$this->redirect(static::getUrl());
|
||||
} catch (Throwable $e) {
|
||||
Notification::make()->danger()->title('Nicht möglich')->body($e->getMessage())->send();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function getViewData(): array
|
||||
{
|
||||
$plugins = app(PluginManager::class);
|
||||
|
||||
return [
|
||||
'plugins' => collect($plugins->all())->map(fn (PluginManifest $m) => [
|
||||
'manifest' => $m,
|
||||
'enabled' => $plugins->isEnabled($m->slug),
|
||||
'problem' => $plugins->problem($m->slug) ?? (($issues = $m->incompatibilities()) ? implode(', ', $issues) : null),
|
||||
'dependents' => $plugins->dependents($m->slug),
|
||||
])->sortBy(fn (array $p) => [$p['manifest']->core ? 0 : 1, $p['manifest']->name])->values(),
|
||||
'uploadsAllowed' => PluginInstaller::uploadsAllowed(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -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 = '';
|
||||
|
|
|
|||
|
|
@ -1,19 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\NewsPosts\Pages;
|
||||
|
||||
use App\Filament\Resources\NewsPosts\NewsPostResource;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditNewsPost extends EditRecord
|
||||
{
|
||||
protected static string $resource = NewsPostResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
DeleteAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
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,59 +2,17 @@
|
|||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Http\Resources\EventResource;
|
||||
use App\Http\Resources\NewsPostResource;
|
||||
use App\Http\Resources\PersonResource;
|
||||
use App\Models\Event;
|
||||
use App\Models\NewsPost;
|
||||
use App\Models\User;
|
||||
use App\Support\QuickLinks;
|
||||
use App\Dashboard\Widgets;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class DashboardController extends Controller
|
||||
{
|
||||
public function __invoke(Request $request, QuickLinks $quickLinks): Response
|
||||
public function __invoke(Request $request, Widgets $widgets): Response
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
// Hervorgehobene Beiträge für den Slider; ohne Hervorhebung die neuesten mit Bild.
|
||||
$featured = NewsPost::query()->published()->with('category')
|
||||
->where('is_featured', true)->whereNotNull('cover_path')
|
||||
->latest('published_at')->limit(5)->get();
|
||||
|
||||
if ($featured->isEmpty()) {
|
||||
$featured = NewsPost::query()->published()->with('category')
|
||||
->whereNotNull('cover_path')->latest('published_at')->limit(3)->get();
|
||||
}
|
||||
|
||||
$recent = NewsPost::query()->published()->with('category')
|
||||
->whereKeyNot($featured->modelKeys())
|
||||
->latest('published_at')->limit(8)->get();
|
||||
|
||||
return Inertia::render('Dashboard', [
|
||||
'profile' => [
|
||||
'job_title' => $user->job_title,
|
||||
'department' => $user->department,
|
||||
'location' => $user->location,
|
||||
'avatar_url' => $user->avatarUrl(256),
|
||||
],
|
||||
'quickLinks' => $quickLinks->all(),
|
||||
'featuredNews' => NewsPostResource::collection($featured),
|
||||
'latestNews' => NewsPostResource::collection($recent->take(4)->values()),
|
||||
'moreNews' => NewsPostResource::collection($recent->slice(4)->values()),
|
||||
'upcomingEvents' => EventResource::collection(Event::query()->upcoming()->limit(4)->get()),
|
||||
'newColleagues' => PersonResource::collection(
|
||||
User::query()
|
||||
->active()
|
||||
->whereKeyNot($user->getKey())
|
||||
->where('created_at', '>=', now()->subDays(90))
|
||||
->latest()
|
||||
->limit(6)
|
||||
->get()
|
||||
),
|
||||
'peopleCount' => User::query()->active()->count(),
|
||||
'widgets' => $widgets->resolve($request->user(), $request),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable(['name', 'slug', 'description', 'sort'])]
|
||||
class NewsCategory extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
/**
|
||||
* @return HasMany<NewsPost, $this>
|
||||
*/
|
||||
public function posts(): HasMany
|
||||
{
|
||||
return $this->hasMany(NewsPost::class, 'category_id');
|
||||
}
|
||||
}
|
||||
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
|
||||
|
|
|
|||
67
app/Plugins/Hooks.php
Normal file
67
app/Plugins/Hooks.php
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
<?php
|
||||
|
||||
namespace App\Plugins;
|
||||
|
||||
/**
|
||||
* Actions und Filter nach WordPress-Vorbild.
|
||||
*
|
||||
* Hooks::on('post.published', fn (NewsPost $post) => …); // Action
|
||||
* Hooks::do('post.published', $post);
|
||||
*
|
||||
* Hooks::filter('navigation.items', fn (array $items) => [...]); // Filter
|
||||
* $items = Hooks::apply('navigation.items', $items);
|
||||
*
|
||||
* Niedrigere Priorität läuft zuerst (Standard 10).
|
||||
*/
|
||||
class Hooks
|
||||
{
|
||||
/** @var array<string, array<int, list<callable>>> */
|
||||
private array $actions = [];
|
||||
|
||||
/** @var array<string, array<int, list<callable>>> */
|
||||
private array $filters = [];
|
||||
|
||||
public static function on(string $name, callable $callback, int $priority = 10): void
|
||||
{
|
||||
app(self::class)->actions[$name][$priority][] = $callback;
|
||||
}
|
||||
|
||||
public static function do(string $name, mixed ...$arguments): void
|
||||
{
|
||||
foreach (app(self::class)->sorted(app(self::class)->actions[$name] ?? []) as $callback) {
|
||||
$callback(...$arguments);
|
||||
}
|
||||
}
|
||||
|
||||
public static function filter(string $name, callable $callback, int $priority = 10): void
|
||||
{
|
||||
app(self::class)->filters[$name][$priority][] = $callback;
|
||||
}
|
||||
|
||||
public static function apply(string $name, mixed $value, mixed ...$arguments): mixed
|
||||
{
|
||||
foreach (app(self::class)->sorted(app(self::class)->filters[$name] ?? []) as $callback) {
|
||||
$value = $callback($value, ...$arguments);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
public static function has(string $name): bool
|
||||
{
|
||||
$hooks = app(self::class);
|
||||
|
||||
return ! empty($hooks->actions[$name]) || ! empty($hooks->filters[$name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, list<callable>> $byPriority
|
||||
* @return list<callable>
|
||||
*/
|
||||
private function sorted(array $byPriority): array
|
||||
{
|
||||
ksort($byPriority);
|
||||
|
||||
return array_merge(...array_values($byPriority) ?: [[]]);
|
||||
}
|
||||
}
|
||||
39
app/Plugins/Plugin.php
Normal file
39
app/Plugins/Plugin.php
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
<?php
|
||||
|
||||
namespace App\Plugins;
|
||||
|
||||
use Illuminate\Contracts\Foundation\Application;
|
||||
|
||||
/**
|
||||
* Basisklasse für Plugins – mitgelieferte wie vom Kunden installierte.
|
||||
*
|
||||
* register(): Dienste binden, Navigation/Kacheln/Rechte registrieren (früh, vor boot).
|
||||
* boot(): Hooks, Routen, Views – alles, was andere Dienste braucht.
|
||||
* activate()/deactivate()/uninstall(): Lebenszyklus, vom Admin ausgelöst.
|
||||
*/
|
||||
abstract class Plugin
|
||||
{
|
||||
public function __construct(
|
||||
protected readonly Application $app,
|
||||
public readonly PluginManifest $manifest,
|
||||
) {}
|
||||
|
||||
public function register(): void {}
|
||||
|
||||
public function boot(): void {}
|
||||
|
||||
public function activate(): void {}
|
||||
|
||||
public function deactivate(): void {}
|
||||
|
||||
/**
|
||||
* Beim Löschen mit „Daten entfernen“. Die Tabellen aus den Migrationen des
|
||||
* Plugins entfernt der Kern selbst.
|
||||
*/
|
||||
public function uninstall(): void {}
|
||||
|
||||
protected function path(string $path = ''): string
|
||||
{
|
||||
return $this->manifest->path.($path !== '' ? '/'.ltrim($path, '/') : '');
|
||||
}
|
||||
}
|
||||
75
app/Plugins/PluginInstaller.php
Normal file
75
app/Plugins/PluginInstaller.php
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
<?php
|
||||
|
||||
namespace App\Plugins;
|
||||
|
||||
use App\Support\Audit;
|
||||
use App\Support\Update\Filesystem;
|
||||
use App\Support\Update\ZipExtractor;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Installiert Kunden-Plugins aus einem ZIP-Archiv nach plugins/<slug>.
|
||||
* Nutzt denselben ZIP-Slip-Schutz wie der Self-Updater. Ein vorhandenes Plugin
|
||||
* mit gleichem Kürzel wird ersetzt (Update), seine Daten bleiben erhalten.
|
||||
*/
|
||||
class PluginInstaller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly PluginManager $plugins,
|
||||
private readonly ZipExtractor $extractor,
|
||||
) {}
|
||||
|
||||
public static function uploadsAllowed(): bool
|
||||
{
|
||||
return ! filter_var(config('inhaus.disallow_file_mods'), FILTER_VALIDATE_BOOL);
|
||||
}
|
||||
|
||||
public function install(string $zipFile): PluginManifest
|
||||
{
|
||||
if (! self::uploadsAllowed()) {
|
||||
throw new RuntimeException('Das Installieren von Plugins ist in dieser Installation abgeschaltet.');
|
||||
}
|
||||
|
||||
$staging = storage_path('framework/plugin-upload-'.bin2hex(random_bytes(4)));
|
||||
|
||||
try {
|
||||
$this->extractor->extract($zipFile, $staging);
|
||||
|
||||
try {
|
||||
$manifest = PluginManifest::fromDirectory($staging, core: false);
|
||||
} catch (Throwable $e) {
|
||||
throw new RuntimeException('Das Archiv enthält kein gültiges Plugin: '.$e->getMessage());
|
||||
}
|
||||
|
||||
$existing = $this->plugins->find($manifest->slug);
|
||||
|
||||
if ($existing?->core) {
|
||||
throw new RuntimeException("Das Kürzel „{$manifest->slug}“ gehört zu einem mitgelieferten Plugin.");
|
||||
}
|
||||
|
||||
if (! is_file($staging.'/src/'.str_replace('\\', '/', substr($manifest->class, strlen($manifest->namespace))).'.php')) {
|
||||
throw new RuntimeException("Die Plugin-Klasse {$manifest->class} fehlt im Archiv (erwartet unter src/).");
|
||||
}
|
||||
|
||||
$target = $this->plugins->customerPath().'/'.$manifest->slug;
|
||||
|
||||
if (! is_dir(dirname($target)) && ! @mkdir(dirname($target), 0775, true)) {
|
||||
throw new RuntimeException('Das Verzeichnis plugins/ ist nicht beschreibbar.');
|
||||
}
|
||||
|
||||
Filesystem::deleteDirectory($target);
|
||||
|
||||
if (! Filesystem::moveDirectory($staging, $target)) {
|
||||
throw new RuntimeException('Das Plugin konnte nicht nach plugins/ verschoben werden. Bitte Schreibrechte prüfen.');
|
||||
}
|
||||
|
||||
$this->plugins->forgetDiscovered();
|
||||
Audit::log($existing ? 'plugin.updated' : 'plugin.installed', ['plugin' => $manifest->slug, 'version' => $manifest->version]);
|
||||
|
||||
return PluginManifest::fromDirectory($target, core: false);
|
||||
} finally {
|
||||
Filesystem::deleteDirectory($staging);
|
||||
}
|
||||
}
|
||||
}
|
||||
411
app/Plugins/PluginManager.php
Normal file
411
app/Plugins/PluginManager.php
Normal file
|
|
@ -0,0 +1,411 @@
|
|||
<?php
|
||||
|
||||
namespace App\Plugins;
|
||||
|
||||
use App\Support\Audit;
|
||||
use App\Support\Update\Filesystem;
|
||||
use Illuminate\Contracts\Foundation\Application;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Findet, lädt und verwaltet Plugins.
|
||||
*
|
||||
* plugins-core/<slug>/ mitgeliefert (Teil jedes Updates)
|
||||
* plugins/<slug>/ vom Kunden installiert (geschützt, Updates lassen sie in Ruhe)
|
||||
*
|
||||
* Wiederherstellungsmodus: Vor dem Laden eines Plugins wird eine Markierung
|
||||
* geschrieben und danach entfernt. Bleibt sie liegen, ist der Prozess beim
|
||||
* Laden abgestürzt (Fatal Error) – das Plugin wird beim nächsten Aufruf
|
||||
* deaktiviert, das Portal bleibt erreichbar. Ausnahmen führen sofort dazu.
|
||||
*/
|
||||
class PluginManager
|
||||
{
|
||||
/** Ab diesem Alter gilt eine liegengebliebene Lade-Markierung als Absturz. */
|
||||
private const CRASH_AFTER_SECONDS = 30;
|
||||
|
||||
/** @var array<string, PluginManifest>|null */
|
||||
private ?array $manifests = null;
|
||||
|
||||
/** @var array<string, Plugin> */
|
||||
private array $loaded = [];
|
||||
|
||||
/** @var array<string, string> Slug => Grund */
|
||||
private array $problems = [];
|
||||
|
||||
/** @var array<string, bool> */
|
||||
private array $autoloaded = [];
|
||||
|
||||
public function __construct(
|
||||
private readonly Application $app,
|
||||
private readonly PluginState $state,
|
||||
private readonly ?string $corePath = null,
|
||||
private readonly ?string $customerPath = null,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array<string, PluginManifest>
|
||||
*/
|
||||
public function all(): array
|
||||
{
|
||||
if ($this->manifests !== null) {
|
||||
return $this->manifests;
|
||||
}
|
||||
|
||||
$this->manifests = [];
|
||||
|
||||
foreach ([[$this->corePath(), true], [$this->customerPath(), false]] as [$directory, $core]) {
|
||||
foreach (glob($directory.'/*/plugin.json') ?: [] as $file) {
|
||||
try {
|
||||
$manifest = PluginManifest::fromDirectory(dirname($file), $core);
|
||||
} catch (Throwable $e) {
|
||||
$this->problems[basename(dirname($file))] = $e->getMessage();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($this->manifests[$manifest->slug])) {
|
||||
$this->problems[$manifest->slug] = 'Ein Plugin mit diesem Kürzel ist bereits vorhanden.';
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->manifests[$manifest->slug] = $manifest;
|
||||
}
|
||||
}
|
||||
|
||||
ksort($this->manifests);
|
||||
|
||||
return $this->manifests;
|
||||
}
|
||||
|
||||
public function find(string $slug): ?PluginManifest
|
||||
{
|
||||
return $this->all()[$slug] ?? null;
|
||||
}
|
||||
|
||||
public function isEnabled(string $slug): bool
|
||||
{
|
||||
$manifest = $this->find($slug);
|
||||
|
||||
return $manifest !== null && $this->state->isEnabled($manifest);
|
||||
}
|
||||
|
||||
public function isLoaded(string $slug): bool
|
||||
{
|
||||
return isset($this->loaded[$slug]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, Plugin>
|
||||
*/
|
||||
public function loaded(): array
|
||||
{
|
||||
return $this->loaded;
|
||||
}
|
||||
|
||||
public function problem(string $slug): ?string
|
||||
{
|
||||
return $this->problems[$slug] ?? $this->state->disabledReason($slug);
|
||||
}
|
||||
|
||||
/**
|
||||
* Aktive, lauffähige Plugins in Abhängigkeitsreihenfolge.
|
||||
*
|
||||
* @return list<PluginManifest>
|
||||
*/
|
||||
public function bootOrder(): array
|
||||
{
|
||||
$candidates = array_filter($this->all(), fn (PluginManifest $m) => $this->state->isEnabled($m));
|
||||
$ordered = [];
|
||||
$visiting = [];
|
||||
|
||||
$visit = function (PluginManifest $manifest) use (&$visit, &$ordered, &$visiting, $candidates): bool {
|
||||
if (isset($ordered[$manifest->slug])) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isset($visiting[$manifest->slug]) || $manifest->incompatibilities() !== []) {
|
||||
$this->problems[$manifest->slug] ??= implode(', ', $manifest->incompatibilities()) ?: 'Zirkuläre Abhängigkeit.';
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$visiting[$manifest->slug] = true;
|
||||
|
||||
foreach ($manifest->requiredPlugins() as $dependency) {
|
||||
if (! isset($candidates[$dependency]) || ! $visit($candidates[$dependency])) {
|
||||
$this->problems[$manifest->slug] ??= "benötigt das Plugin „{$dependency}“";
|
||||
unset($visiting[$manifest->slug]);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
unset($visiting[$manifest->slug]);
|
||||
$ordered[$manifest->slug] = $manifest;
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
foreach ($candidates as $manifest) {
|
||||
$visit($manifest);
|
||||
}
|
||||
|
||||
return array_values($ordered);
|
||||
}
|
||||
|
||||
/**
|
||||
* Phase 1: Autoload und register() aller aktiven Plugins.
|
||||
*/
|
||||
public function registerAll(): void
|
||||
{
|
||||
$this->recoverFromCrash();
|
||||
|
||||
foreach ($this->bootOrder() as $manifest) {
|
||||
$this->guard($manifest, function () use ($manifest) {
|
||||
$this->registerAutoload($manifest);
|
||||
$plugin = $this->instantiate($manifest);
|
||||
$plugin->register();
|
||||
$this->loaded[$manifest->slug] = $plugin;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Phase 2: Migrationen, Views, Routen und boot().
|
||||
*/
|
||||
public function bootAll(): void
|
||||
{
|
||||
foreach ($this->loaded as $slug => $plugin) {
|
||||
$manifest = $plugin->manifest;
|
||||
|
||||
$this->guard($manifest, function () use ($plugin, $manifest) {
|
||||
if (is_dir($manifest->migrationsPath())) {
|
||||
$this->app['migrator']->path($manifest->migrationsPath());
|
||||
}
|
||||
|
||||
if (is_dir($manifest->path.'/resources/views')) {
|
||||
$this->app['view']->addNamespace($manifest->slug, $manifest->path.'/resources/views');
|
||||
}
|
||||
|
||||
if (is_file($manifest->path.'/routes/web.php') && ! $this->app->routesAreCached()) {
|
||||
Route::middleware('web')->group($manifest->path.'/routes/web.php');
|
||||
}
|
||||
|
||||
$plugin->boot();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public function activate(string $slug): void
|
||||
{
|
||||
$manifest = $this->find($slug) ?? throw new RuntimeException('Plugin nicht gefunden.');
|
||||
|
||||
if ($problems = $manifest->incompatibilities()) {
|
||||
throw new RuntimeException('Das Plugin kann nicht aktiviert werden: '.implode(', ', $problems).'.');
|
||||
}
|
||||
|
||||
foreach ($manifest->requiredPlugins() as $dependency) {
|
||||
if (! $this->isEnabled($dependency)) {
|
||||
throw new RuntimeException("Bitte zuerst das Plugin „{$dependency}“ aktivieren.");
|
||||
}
|
||||
}
|
||||
|
||||
$this->registerAutoload($manifest);
|
||||
|
||||
if (is_dir($manifest->migrationsPath())) {
|
||||
Artisan::call('migrate', ['--path' => $manifest->migrationsPath(), '--realpath' => true, '--force' => true]);
|
||||
}
|
||||
|
||||
$this->instantiate($manifest)->activate();
|
||||
$this->state->setEnabled($slug, true);
|
||||
Audit::log('plugin.activated', ['plugin' => $slug, 'version' => $manifest->version]);
|
||||
}
|
||||
|
||||
public function deactivate(string $slug, ?string $reason = null): void
|
||||
{
|
||||
$manifest = $this->find($slug) ?? throw new RuntimeException('Plugin nicht gefunden.');
|
||||
|
||||
if ($reason === null && ($dependents = $this->dependents($slug)) !== []) {
|
||||
throw new RuntimeException('Wird noch benötigt von: '.implode(', ', $dependents).'.');
|
||||
}
|
||||
|
||||
if ($reason === null && isset($this->loaded[$slug])) {
|
||||
$this->loaded[$slug]->deactivate();
|
||||
}
|
||||
|
||||
$this->state->setEnabled($slug, false, $reason);
|
||||
Audit::log('plugin.deactivated', ['plugin' => $slug, 'reason' => $reason]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kunden-Plugin löschen, optional samt Daten (Tabellen aus den Migrationen).
|
||||
*/
|
||||
public function delete(string $slug, bool $removeData): void
|
||||
{
|
||||
$manifest = $this->find($slug) ?? throw new RuntimeException('Plugin nicht gefunden.');
|
||||
|
||||
if ($manifest->core) {
|
||||
throw new RuntimeException('Mitgelieferte Plugins können nur deaktiviert werden.');
|
||||
}
|
||||
|
||||
if ($this->isEnabled($slug)) {
|
||||
$this->deactivate($slug);
|
||||
}
|
||||
|
||||
if ($removeData) {
|
||||
$this->registerAutoload($manifest);
|
||||
$this->instantiate($manifest)->uninstall();
|
||||
|
||||
if (is_dir($manifest->migrationsPath())) {
|
||||
Artisan::call('migrate:reset', ['--path' => $manifest->migrationsPath(), '--realpath' => true, '--force' => true]);
|
||||
}
|
||||
}
|
||||
|
||||
Filesystem::deleteDirectory($manifest->path);
|
||||
$this->state->forget($slug);
|
||||
$this->manifests = null;
|
||||
Audit::log('plugin.deleted', ['plugin' => $slug, 'data_removed' => $removeData]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public function dependents(string $slug): array
|
||||
{
|
||||
return array_values(array_map(
|
||||
fn (PluginManifest $m) => $m->name,
|
||||
array_filter($this->all(), fn (PluginManifest $m) => $this->isEnabled($m->slug) && in_array($slug, $m->requiredPlugins(), true)),
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Verzeichnisse für Filament (Ressourcen, Seiten, Widgets) der geladenen Plugins.
|
||||
*
|
||||
* @return list<array{type: string, path: string, namespace: string}>
|
||||
*/
|
||||
public function filamentDiscovery(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach ($this->loaded as $plugin) {
|
||||
foreach (['Resources', 'Pages', 'Widgets'] as $type) {
|
||||
$path = $plugin->manifest->path."/src/Filament/{$type}";
|
||||
|
||||
if (is_dir($path)) {
|
||||
$result[] = ['type' => $type, 'path' => $path, 'namespace' => $plugin->manifest->namespace."Filament\\{$type}"];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function corePath(): string
|
||||
{
|
||||
return $this->corePath ?? base_path('plugins-core');
|
||||
}
|
||||
|
||||
public function customerPath(): string
|
||||
{
|
||||
return $this->customerPath ?? base_path('plugins');
|
||||
}
|
||||
|
||||
public function forgetDiscovered(): void
|
||||
{
|
||||
$this->manifests = null;
|
||||
}
|
||||
|
||||
private function instantiate(PluginManifest $manifest): Plugin
|
||||
{
|
||||
if (! class_exists($manifest->class)) {
|
||||
throw new RuntimeException("Plugin-Klasse {$manifest->class} nicht gefunden.");
|
||||
}
|
||||
|
||||
$plugin = new ($manifest->class)($this->app, $manifest);
|
||||
|
||||
if (! $plugin instanceof Plugin) {
|
||||
throw new RuntimeException("{$manifest->class} muss von ".Plugin::class.' erben.');
|
||||
}
|
||||
|
||||
return $plugin;
|
||||
}
|
||||
|
||||
private function registerAutoload(PluginManifest $manifest): void
|
||||
{
|
||||
if (isset($this->autoloaded[$manifest->slug])) {
|
||||
return;
|
||||
}
|
||||
|
||||
$prefix = $manifest->namespace;
|
||||
$base = $manifest->path.'/src/';
|
||||
|
||||
spl_autoload_register(function (string $class) use ($prefix, $base) {
|
||||
if (str_starts_with($class, $prefix)) {
|
||||
$file = $base.str_replace('\\', '/', substr($class, strlen($prefix))).'.php';
|
||||
|
||||
if (is_file($file)) {
|
||||
require $file;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Eigene Abhängigkeiten eines Plugins (gescoped, siehe docs/PLAN.md 4.2).
|
||||
if (is_file($manifest->path.'/vendor/autoload.php')) {
|
||||
require_once $manifest->path.'/vendor/autoload.php';
|
||||
}
|
||||
|
||||
$this->autoloaded[$manifest->slug] = true;
|
||||
}
|
||||
|
||||
private function guard(PluginManifest $manifest, callable $callback): void
|
||||
{
|
||||
$marker = $this->markerPath($manifest->slug);
|
||||
@file_put_contents($marker, (string) time());
|
||||
|
||||
try {
|
||||
$callback();
|
||||
} catch (Throwable $e) {
|
||||
unset($this->loaded[$manifest->slug]);
|
||||
$this->problems[$manifest->slug] = $e->getMessage();
|
||||
Log::error("Plugin {$manifest->slug} wurde wegen eines Fehlers deaktiviert: ".$e->getMessage(), ['exception' => $e]);
|
||||
|
||||
try {
|
||||
$this->deactivate($manifest->slug, 'Fehler beim Laden: '.$e->getMessage());
|
||||
} catch (Throwable) {
|
||||
$this->state->setEnabled($manifest->slug, false, 'Fehler beim Laden: '.$e->getMessage());
|
||||
}
|
||||
} finally {
|
||||
@unlink($marker);
|
||||
}
|
||||
}
|
||||
|
||||
private function recoverFromCrash(): void
|
||||
{
|
||||
foreach (glob($this->markerPath('*')) ?: [] as $marker) {
|
||||
if (time() - (int) @filemtime($marker) < self::CRASH_AFTER_SECONDS) {
|
||||
continue; // Lädt vermutlich gerade in einer parallelen Anfrage.
|
||||
}
|
||||
|
||||
$slug = substr(basename($marker), strlen('booting-'));
|
||||
Log::critical("Plugin {$slug} hat beim Laden einen schweren Fehler verursacht und wurde deaktiviert.");
|
||||
$this->state->setEnabled($slug, false, 'Schwerer Fehler beim Laden (das Portal wurde dadurch unterbrochen).');
|
||||
@unlink($marker);
|
||||
}
|
||||
}
|
||||
|
||||
private function markerPath(string $slug): string
|
||||
{
|
||||
$dir = storage_path('framework/plugins');
|
||||
|
||||
if (! is_dir($dir)) {
|
||||
@mkdir($dir, 0775, true);
|
||||
}
|
||||
|
||||
return $dir.'/booting-'.$slug;
|
||||
}
|
||||
}
|
||||
128
app/Plugins/PluginManifest.php
Normal file
128
app/Plugins/PluginManifest.php
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
<?php
|
||||
|
||||
namespace App\Plugins;
|
||||
|
||||
use App\Version;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Inhalt einer plugin.json.
|
||||
*
|
||||
* {
|
||||
* "slug": "mav-kalender",
|
||||
* "name": "MAV-Kalender",
|
||||
* "version": "1.0.0",
|
||||
* "description": "…",
|
||||
* "author": "…",
|
||||
* "namespace": "Acme\\MavKalender\\",
|
||||
* "class": "Acme\\MavKalender\\Plugin",
|
||||
* "requires": { "core": ">=0.3.0", "php": ">=8.3", "plugins": ["news"] },
|
||||
* "update_url": "https://…"
|
||||
* }
|
||||
*/
|
||||
final class PluginManifest
|
||||
{
|
||||
public const SLUG_PATTERN = '/^[a-z0-9]+(?:-[a-z0-9]+)*$/';
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
private function __construct(
|
||||
public readonly string $slug,
|
||||
public readonly string $name,
|
||||
public readonly string $version,
|
||||
public readonly string $description,
|
||||
public readonly string $author,
|
||||
public readonly string $namespace,
|
||||
public readonly string $class,
|
||||
public readonly string $path,
|
||||
public readonly bool $core,
|
||||
public readonly array $requires,
|
||||
public readonly ?string $updateUrl,
|
||||
) {}
|
||||
|
||||
public static function fromDirectory(string $path, bool $core): self
|
||||
{
|
||||
$file = rtrim($path, '/').'/plugin.json';
|
||||
$data = json_decode((string) @file_get_contents($file), true);
|
||||
|
||||
if (! is_array($data)) {
|
||||
throw new InvalidArgumentException('plugin.json fehlt oder ist kein gültiges JSON.');
|
||||
}
|
||||
|
||||
return self::fromArray($data, $path, $core);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public static function fromArray(array $data, string $path, bool $core): self
|
||||
{
|
||||
foreach (['slug', 'name', 'version', 'namespace', 'class'] as $field) {
|
||||
if (! is_string($data[$field] ?? null) || trim($data[$field]) === '') {
|
||||
throw new InvalidArgumentException("plugin.json: Feld „{$field}“ fehlt.");
|
||||
}
|
||||
}
|
||||
|
||||
if (! preg_match(self::SLUG_PATTERN, $data['slug'])) {
|
||||
throw new InvalidArgumentException('plugin.json: „slug“ darf nur Kleinbuchstaben, Ziffern und Bindestriche enthalten.');
|
||||
}
|
||||
|
||||
$namespace = rtrim($data['namespace'], '\\').'\\';
|
||||
|
||||
if (! str_starts_with(ltrim($data['class'], '\\'), $namespace)) {
|
||||
throw new InvalidArgumentException('plugin.json: „class“ muss im angegebenen Namespace liegen.');
|
||||
}
|
||||
|
||||
if (str_starts_with($namespace, 'App\\') || str_starts_with($namespace, 'Illuminate\\')) {
|
||||
throw new InvalidArgumentException('plugin.json: Der Namespace „App\\“ ist dem Kern vorbehalten.');
|
||||
}
|
||||
|
||||
return new self(
|
||||
slug: $data['slug'],
|
||||
name: $data['name'],
|
||||
version: $data['version'],
|
||||
description: (string) ($data['description'] ?? ''),
|
||||
author: (string) ($data['author'] ?? ''),
|
||||
namespace: $namespace,
|
||||
class: ltrim($data['class'], '\\'),
|
||||
path: rtrim($path, '/'),
|
||||
core: $core,
|
||||
requires: is_array($data['requires'] ?? null) ? $data['requires'] : [],
|
||||
updateUrl: is_string($data['update_url'] ?? null) ? $data['update_url'] : null,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public function requiredPlugins(): array
|
||||
{
|
||||
return array_values(array_filter((array) ($this->requires['plugins'] ?? []), 'is_string'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gründe, warum das Plugin in dieser Umgebung nicht laufen kann.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function incompatibilities(): array
|
||||
{
|
||||
$problems = [];
|
||||
|
||||
if (! VersionConstraint::satisfies(Version::VERSION, $this->requires['core'] ?? null)) {
|
||||
$problems[] = 'benötigt Inhaus '.$this->requires['core'];
|
||||
}
|
||||
|
||||
if (! VersionConstraint::satisfies(PHP_VERSION, $this->requires['php'] ?? null)) {
|
||||
$problems[] = 'benötigt PHP '.$this->requires['php'];
|
||||
}
|
||||
|
||||
return $problems;
|
||||
}
|
||||
|
||||
public function migrationsPath(): string
|
||||
{
|
||||
return $this->path.'/database/migrations';
|
||||
}
|
||||
}
|
||||
80
app/Plugins/PluginState.php
Normal file
80
app/Plugins/PluginState.php
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
<?php
|
||||
|
||||
namespace App\Plugins;
|
||||
|
||||
use App\Support\Update\AtomicFile;
|
||||
|
||||
/**
|
||||
* Aktivierungszustand der Plugins in storage/app/plugins.json – als Datei, damit
|
||||
* das Laden der Plugins keine Datenbankabfrage kostet und auch ohne DB klappt.
|
||||
* Mitgelieferte Plugins sind aktiv, solange nichts anderes vermerkt ist.
|
||||
*/
|
||||
class PluginState
|
||||
{
|
||||
/** @var array<string, array<string, mixed>>|null */
|
||||
private ?array $data = null;
|
||||
|
||||
public function __construct(private readonly ?string $file = null) {}
|
||||
|
||||
public function isEnabled(PluginManifest $manifest): bool
|
||||
{
|
||||
$entry = $this->all()[$manifest->slug] ?? null;
|
||||
|
||||
return is_array($entry) ? (bool) ($entry['enabled'] ?? false) : $manifest->core;
|
||||
}
|
||||
|
||||
public function setEnabled(string $slug, bool $enabled, ?string $reason = null): void
|
||||
{
|
||||
$this->update($slug, ['enabled' => $enabled, 'disabled_reason' => $enabled ? null : $reason]);
|
||||
}
|
||||
|
||||
public function disabledReason(string $slug): ?string
|
||||
{
|
||||
return $this->all()[$slug]['disabled_reason'] ?? null;
|
||||
}
|
||||
|
||||
public function forget(string $slug): void
|
||||
{
|
||||
$data = $this->all();
|
||||
unset($data[$slug]);
|
||||
$this->write($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array<string, mixed>>
|
||||
*/
|
||||
public function all(): array
|
||||
{
|
||||
if ($this->data === null) {
|
||||
$decoded = json_decode((string) @file_get_contents($this->path()), true);
|
||||
$this->data = is_array($decoded) ? $decoded : [];
|
||||
}
|
||||
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $values
|
||||
*/
|
||||
private function update(string $slug, array $values): void
|
||||
{
|
||||
$this->data = null;
|
||||
$data = $this->all();
|
||||
$data[$slug] = array_merge($data[$slug] ?? [], $values);
|
||||
$this->write($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, array<string, mixed>> $data
|
||||
*/
|
||||
private function write(array $data): void
|
||||
{
|
||||
AtomicFile::write($this->path(), json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
|
||||
$this->data = $data;
|
||||
}
|
||||
|
||||
private function path(): string
|
||||
{
|
||||
return $this->file ?? storage_path('app/plugins.json');
|
||||
}
|
||||
}
|
||||
58
app/Plugins/VersionConstraint.php
Normal file
58
app/Plugins/VersionConstraint.php
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
<?php
|
||||
|
||||
namespace App\Plugins;
|
||||
|
||||
/**
|
||||
* Einfache Versionsbedingungen für Plugin-Manifeste: „>=1.2“, „<2.0“, „^1.4“,
|
||||
* „~1.4“, „1.2.3“, „*“ – mehrere mit Leerzeichen oder Komma verknüpft (UND).
|
||||
*/
|
||||
final class VersionConstraint
|
||||
{
|
||||
public static function satisfies(string $version, ?string $constraint): bool
|
||||
{
|
||||
$constraint = trim((string) $constraint);
|
||||
|
||||
if ($constraint === '' || $constraint === '*') {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach (preg_split('/[\s,]+/', $constraint) ?: [] as $part) {
|
||||
if (! self::check(self::normalize($version), $part)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static function check(string $version, string $part): bool
|
||||
{
|
||||
if (str_starts_with($part, '^')) {
|
||||
$min = self::normalize(substr($part, 1));
|
||||
[$major, $minor] = array_map('intval', explode('.', $min));
|
||||
$max = $major > 0 ? ($major + 1).'.0.0' : '0.'.($minor + 1).'.0';
|
||||
|
||||
return version_compare($version, $min, '>=') && version_compare($version, $max, '<');
|
||||
}
|
||||
|
||||
if (str_starts_with($part, '~')) {
|
||||
$min = self::normalize(substr($part, 1));
|
||||
[$major, $minor] = array_map('intval', explode('.', $min));
|
||||
|
||||
return version_compare($version, $min, '>=') && version_compare($version, $major.'.'.($minor + 1).'.0', '<');
|
||||
}
|
||||
|
||||
if (preg_match('/^(>=|<=|>|<|==|=|!=)(.+)$/', $part, $m)) {
|
||||
return version_compare($version, self::normalize($m[2]), $m[1] === '=' ? '==' : $m[1]);
|
||||
}
|
||||
|
||||
return version_compare($version, self::normalize($part), '==');
|
||||
}
|
||||
|
||||
private static function normalize(string $version): string
|
||||
{
|
||||
$parts = explode('.', preg_replace('/[^0-9.].*$/', '', ltrim(trim($version), 'vV')));
|
||||
|
||||
return implode('.', array_slice(array_pad(array_map('intval', $parts), 3, 0), 0, 3));
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -2,13 +2,17 @@
|
|||
|
||||
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\Navigation;
|
||||
use App\Support\Permissions\PermissionResource;
|
||||
use App\Support\Permissions\Permissions;
|
||||
use App\Support\QuickLinks;
|
||||
use App\Support\Settings;
|
||||
use App\Support\Update\InstalledVersion;
|
||||
|
|
@ -36,9 +40,9 @@ class AppServiceProvider extends ServiceProvider
|
|||
$this->app->singleton(Settings::class);
|
||||
$this->app->singleton(Branding::class);
|
||||
$this->app->singleton(Avatars::class);
|
||||
$this->app->singleton(Navigation::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);
|
||||
|
|
@ -47,11 +51,27 @@ class AppServiceProvider extends ServiceProvider
|
|||
|
||||
public function boot(): void
|
||||
{
|
||||
CoreWidgets::register($this->app->make(Widgets::class));
|
||||
|
||||
// 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);
|
||||
// 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,9 @@ 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;
|
||||
use Filament\Http\Middleware\Authenticate;
|
||||
|
|
@ -29,7 +32,7 @@ class AdminPanelProvider extends PanelProvider
|
|||
{
|
||||
// Keine eigene Filament-Anmeldung: das Admin-Backend nutzt den Portal-Login
|
||||
// (und damit später auch Entra ID). Nicht angemeldete Personen landen auf /login.
|
||||
return $panel
|
||||
$panel = $panel
|
||||
->default()
|
||||
->id('admin')
|
||||
->path('admin')
|
||||
|
|
@ -39,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')
|
||||
|
|
@ -53,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,
|
||||
|
|
@ -76,5 +85,16 @@ class AdminPanelProvider extends PanelProvider
|
|||
->authMiddleware([
|
||||
Authenticate::class,
|
||||
]);
|
||||
|
||||
// Admin-Seiten der aktiven Plugins (src/Filament/{Resources,Pages,Widgets}).
|
||||
foreach (app(PluginManager::class)->filamentDiscovery() as $discovery) {
|
||||
match ($discovery['type']) {
|
||||
'Resources' => $panel->discoverResources(in: $discovery['path'], for: $discovery['namespace']),
|
||||
'Pages' => $panel->discoverPages(in: $discovery['path'], for: $discovery['namespace']),
|
||||
'Widgets' => $panel->discoverWidgets(in: $discovery['path'], for: $discovery['namespace']),
|
||||
};
|
||||
}
|
||||
|
||||
return $panel;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
35
app/Providers/PluginServiceProvider.php
Normal file
35
app/Providers/PluginServiceProvider.php
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Dashboard\Widgets;
|
||||
use App\Plugins\Hooks;
|
||||
use App\Plugins\PluginManager;
|
||||
use App\Plugins\PluginState;
|
||||
use App\Support\Abilities;
|
||||
use App\Support\Navigation;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
/**
|
||||
* Lädt die Plugins. Muss vor den Panel-Providern registriert sein, damit
|
||||
* Plugins ihre Admin-Seiten beitragen können.
|
||||
*/
|
||||
class PluginServiceProvider extends ServiceProvider
|
||||
{
|
||||
public function register(): void
|
||||
{
|
||||
$this->app->singleton(Hooks::class);
|
||||
$this->app->singleton(PluginState::class);
|
||||
$this->app->singleton(PluginManager::class);
|
||||
$this->app->singleton(Navigation::class);
|
||||
$this->app->singleton(Widgets::class);
|
||||
$this->app->singleton(Abilities::class);
|
||||
|
||||
$this->app->make(PluginManager::class)->registerAll();
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
$this->app->make(PluginManager::class)->bootAll();
|
||||
}
|
||||
}
|
||||
86
app/Support/Abilities.php
Normal file
86
app/Support/Abilities.php
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
/**
|
||||
* Registry der Rechte (Abilities). Kern und Plugins melden hier an, welche
|
||||
* Rechte es gibt – das Rollen-Formular und der Rechte-Prüfer bauen darauf auf.
|
||||
*
|
||||
* Globale Rechte gelten überall („Benutzer verwalten“). Objekt-Rechte gelten für
|
||||
* einzelne Objekte eines Typs („Beiträge schreiben in Kategorie MAV-Info“).
|
||||
*/
|
||||
class Abilities
|
||||
{
|
||||
/** @var array<string, array{label: string, group: string, resource: string|null}> */
|
||||
private array $abilities = [];
|
||||
|
||||
/** @var array<string, array{label: string, options: callable}> */
|
||||
private array $resourceTypes = [];
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$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');
|
||||
$this->define('appearance.manage', 'Erscheinungsbild und Schnellzugriffe', 'System');
|
||||
$this->define('updates.manage', 'Aktualisierungen, Lizenz und Systemzustand', 'System');
|
||||
$this->define('feedback.send', 'Rückmeldungen an den Hersteller senden', 'System');
|
||||
}
|
||||
|
||||
public function define(string $ability, string $label, string $group, ?string $resource = null): void
|
||||
{
|
||||
$this->abilities[$ability] = ['label' => $label, 'group' => $group, 'resource' => $resource];
|
||||
}
|
||||
|
||||
/**
|
||||
* Objekttyp, auf den sich Rechte beziehen können (z. B. „news_category“).
|
||||
*
|
||||
* @param callable(): array<int|string, string> $options ID => Bezeichnung
|
||||
*/
|
||||
public function resourceType(string $type, string $label, callable $options): void
|
||||
{
|
||||
$this->resourceTypes[$type] = ['label' => $label, 'options' => $options];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{label: string, group: string, resource: string|null}>
|
||||
*/
|
||||
public function all(): array
|
||||
{
|
||||
return $this->abilities;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{label: string, group: string, resource: string|null}>
|
||||
*/
|
||||
public function global(): array
|
||||
{
|
||||
return array_filter($this->abilities, fn (array $a) => $a['resource'] === null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{label: string, group: string, resource: string|null}>
|
||||
*/
|
||||
public function forResource(string $type): array
|
||||
{
|
||||
return array_filter($this->abilities, fn (array $a) => $a['resource'] === $type);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{label: string, options: callable}>
|
||||
*/
|
||||
public function resourceTypes(): array
|
||||
{
|
||||
return $this->resourceTypes;
|
||||
}
|
||||
|
||||
public function exists(string $ability): bool
|
||||
{
|
||||
return isset($this->abilities[$ability]);
|
||||
}
|
||||
|
||||
public function label(string $ability): string
|
||||
{
|
||||
return $this->abilities[$ability]['label'] ?? $ability;
|
||||
}
|
||||
}
|
||||
|
|
@ -2,24 +2,56 @@
|
|||
|
||||
namespace App\Support;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Plugins\Hooks;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* Hauptnavigation des Portals. Wird ab Phase 2 zu einer Registry, in die
|
||||
* Plugins eigene Einträge eintragen.
|
||||
* Hauptnavigation des Portals als Registry: Kern und Plugins tragen Einträge ein.
|
||||
*
|
||||
* app(Navigation::class)->add('news', 'Neuigkeiten', '/neuigkeiten', active: 'news.*', sort: 20);
|
||||
*/
|
||||
class Navigation
|
||||
{
|
||||
/**
|
||||
* @return list<array{label: string, href: string, active: bool}>
|
||||
*/
|
||||
public function items(Request $request): array
|
||||
/** @var array<string, array{label: string, href: string, active: list<string>, sort: int, ability: string|null}> */
|
||||
private array $items = [];
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
return [
|
||||
['label' => 'Startseite', 'href' => '/', 'active' => $request->routeIs('dashboard')],
|
||||
['label' => 'Neuigkeiten', 'href' => '/neuigkeiten', 'active' => $request->routeIs('news.*')],
|
||||
['label' => 'Termine', 'href' => '/termine', 'active' => $request->routeIs('events.*')],
|
||||
['label' => 'Personen', 'href' => '/personen', 'active' => $request->routeIs('people.*')],
|
||||
];
|
||||
$this->add('home', 'Startseite', '/', active: 'dashboard', sort: 0);
|
||||
$this->add('people', 'Personen', '/personen', active: 'people.*', sort: 90);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|list<string> $active Routennamen (mit *), bei denen der Eintrag aktiv ist
|
||||
*/
|
||||
public function add(string $key, string $label, string $href, string|array $active = [], int $sort = 50, ?string $ability = null): void
|
||||
{
|
||||
$this->items[$key] = ['label' => $label, 'href' => $href, 'active' => (array) $active, 'sort' => $sort, 'ability' => $ability];
|
||||
}
|
||||
|
||||
public function remove(string $key): void
|
||||
{
|
||||
unset($this->items[$key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{key: string, label: string, href: string, active: bool}>
|
||||
*/
|
||||
public function items(Request $request, ?User $user = null): array
|
||||
{
|
||||
$items = collect($this->items)
|
||||
->filter(fn (array $item) => $item['ability'] === null || ($user?->can($item['ability']) ?? false))
|
||||
->sortBy('sort')
|
||||
->map(fn (array $item, string $key) => [
|
||||
'key' => $key,
|
||||
'label' => $item['label'],
|
||||
'href' => $item['href'],
|
||||
'active' => $item['active'] !== [] && $request->routeIs(...$item['active']),
|
||||
])
|
||||
->values()
|
||||
->all();
|
||||
|
||||
return Hooks::apply('navigation.items', $items, $request, $user);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -8,6 +8,52 @@ use RecursiveIteratorIterator;
|
|||
|
||||
final class Filesystem
|
||||
{
|
||||
/**
|
||||
* Verzeichnis verschieben – per rename(), bei Dateisystemgrenzen per Kopie.
|
||||
*/
|
||||
public static function moveDirectory(string $from, string $to): bool
|
||||
{
|
||||
if (@rename($from, $to)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (! self::copyDirectory($from, $to)) {
|
||||
self::deleteDirectory($to);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
self::deleteDirectory($from);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static function copyDirectory(string $from, string $to): bool
|
||||
{
|
||||
if (! is_dir($to) && ! @mkdir($to, 0775, true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$items = new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator($from, FilesystemIterator::SKIP_DOTS),
|
||||
RecursiveIteratorIterator::SELF_FIRST,
|
||||
);
|
||||
|
||||
foreach ($items as $item) {
|
||||
$target = $to.'/'.substr($item->getPathname(), strlen(rtrim($from, '/')) + 1);
|
||||
|
||||
if ($item->isDir()) {
|
||||
if (! is_dir($target) && ! @mkdir($target, 0775, true)) {
|
||||
return false;
|
||||
}
|
||||
} elseif (! @copy($item->getPathname(), $target)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static function deleteDirectory(string $dir): void
|
||||
{
|
||||
if (! is_dir($dir)) {
|
||||
|
|
|
|||
|
|
@ -9,5 +9,5 @@ namespace App;
|
|||
*/
|
||||
final class Version
|
||||
{
|
||||
public const VERSION = '0.2.0';
|
||||
public const VERSION = '0.3.0';
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,9 +3,11 @@
|
|||
use App\Providers\AppServiceProvider;
|
||||
use App\Providers\Filament\AdminPanelProvider;
|
||||
use App\Providers\FortifyServiceProvider;
|
||||
use App\Providers\PluginServiceProvider;
|
||||
|
||||
return [
|
||||
AppServiceProvider::class,
|
||||
PluginServiceProvider::class,
|
||||
AdminPanelProvider::class,
|
||||
FortifyServiceProvider::class,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -109,7 +109,8 @@ return [
|
|||
|
||||
'testing' => [
|
||||
|
||||
'ensure_pages_exist' => true,
|
||||
// Plugin-Seiten („news::Index“) liegen außerhalb von resources/js/pages.
|
||||
'ensure_pages_exist' => false,
|
||||
|
||||
],
|
||||
|
||||
|
|
|
|||
|
|
@ -6,4 +6,8 @@ return [
|
|||
// eingerichtet, wenn storage/.installed existiert oder APP_ENV=local ist.
|
||||
'installed' => env('INHAUS_INSTALLED'),
|
||||
|
||||
// Wie DISALLOW_FILE_MODS bei WordPress: verbietet das Hochladen und Löschen von
|
||||
// Plugins über den Admin-Bereich (z. B. bei strengen IT-Richtlinien).
|
||||
'disallow_file_mods' => env('INHAUS_DISALLOW_FILE_MODS', false),
|
||||
|
||||
];
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
namespace Database\Factories;
|
||||
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
|
|
@ -31,14 +32,21 @@ class UserFactory extends Factory
|
|||
'department' => fake()->randomElement(['Verwaltung', 'Pflege', 'IT', 'Personal', 'Buchhaltung', 'Technik']),
|
||||
'location' => fake()->city(),
|
||||
'phone' => fake()->phoneNumber(),
|
||||
'is_admin' => false,
|
||||
'is_active' => true,
|
||||
];
|
||||
}
|
||||
|
||||
public function admin(): static
|
||||
{
|
||||
return $this->state(fn () => ['is_admin' => true]);
|
||||
return $this->afterCreating(fn (User $user) => $user->roles()->attach(Role::administration()->id, ['source' => 'manual', 'created_at' => now()]));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int|Role> $roles
|
||||
*/
|
||||
public function withRoles(array $roles): static
|
||||
{
|
||||
return $this->afterCreating(fn (User $user) => $user->syncManualRoles(array_map(fn ($r) => $r instanceof Role ? $r->id : $r, $roles)));
|
||||
}
|
||||
|
||||
public function inactive(): static
|
||||
|
|
|
|||
|
|
@ -0,0 +1,101 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Rollen und Rechte (docs/PLAN.md, Abschnitt 7).
|
||||
*
|
||||
* roles – Rollen, z. B. „MAV“ oder „Redaktion Hamburg“
|
||||
* role_user – Zuweisungen mit Herkunft: manuell oder über eine IdP-Gruppe (Phase 3)
|
||||
* grants – Rechte einer Rolle, global (resource_type = null) oder für ein Objekt
|
||||
* audiences – Zielgruppen: wer ein Objekt sehen darf (Rolle, Abteilung, Standort)
|
||||
*
|
||||
* Ersetzt das bisherige Feld users.is_admin durch die Systemrolle „Administration“.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('roles', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('name', 100);
|
||||
$table->string('slug', 100)->unique();
|
||||
$table->string('description', 500)->nullable();
|
||||
$table->boolean('is_system')->default(false);
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
Schema::create('role_user', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('role_id')->constrained()->cascadeOnDelete();
|
||||
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
|
||||
$table->string('source', 20)->default('manual');
|
||||
$table->string('source_ref', 191)->nullable();
|
||||
$table->timestamp('created_at')->nullable();
|
||||
|
||||
$table->unique(['role_id', 'user_id', 'source', 'source_ref']);
|
||||
$table->index(['user_id', 'role_id']);
|
||||
});
|
||||
|
||||
Schema::create('grants', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('role_id')->constrained()->cascadeOnDelete();
|
||||
$table->string('ability', 100);
|
||||
$table->string('resource_type', 50)->nullable();
|
||||
$table->unsignedBigInteger('resource_id')->nullable();
|
||||
$table->boolean('include_children')->default(false);
|
||||
$table->timestamps();
|
||||
|
||||
$table->index(['resource_type', 'resource_id']);
|
||||
$table->index(['role_id', 'ability']);
|
||||
});
|
||||
|
||||
Schema::create('audiences', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('resource_type', 50);
|
||||
$table->unsignedBigInteger('resource_id');
|
||||
$table->string('rule_type', 20);
|
||||
$table->string('rule_value', 191);
|
||||
|
||||
$table->index(['resource_type', 'resource_id']);
|
||||
$table->index(['rule_type', 'rule_value']);
|
||||
});
|
||||
|
||||
$now = now();
|
||||
$adminRole = DB::table('roles')->insertGetId([
|
||||
'name' => 'Administration',
|
||||
'slug' => 'administration',
|
||||
'description' => 'Voller Zugriff auf alle Bereiche und Einstellungen.',
|
||||
'is_system' => true,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
|
||||
DB::table('grants')->insert(['role_id' => $adminRole, 'ability' => '*', 'created_at' => $now, 'updated_at' => $now]);
|
||||
|
||||
DB::table('users')->where('is_admin', true)->pluck('id')->each(fn (int $userId) => DB::table('role_user')->insert([
|
||||
'role_id' => $adminRole, 'user_id' => $userId, 'source' => 'manual', 'created_at' => $now,
|
||||
]));
|
||||
|
||||
Schema::table('users', fn (Blueprint $table) => $table->dropColumn('is_admin'));
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('users', fn (Blueprint $table) => $table->boolean('is_admin')->default(false));
|
||||
|
||||
$adminRole = DB::table('roles')->where('slug', 'administration')->value('id');
|
||||
|
||||
if ($adminRole) {
|
||||
DB::table('users')->whereIn('id', DB::table('role_user')->where('role_id', $adminRole)->pluck('user_id'))->update(['is_admin' => true]);
|
||||
}
|
||||
|
||||
Schema::dropIfExists('audiences');
|
||||
Schema::dropIfExists('grants');
|
||||
Schema::dropIfExists('role_user');
|
||||
Schema::dropIfExists('roles');
|
||||
}
|
||||
};
|
||||
|
|
@ -2,15 +2,16 @@
|
|||
|
||||
namespace Database\Seeders;
|
||||
|
||||
use App\Models\Event;
|
||||
use App\Models\NewsCategory;
|
||||
use App\Models\NewsPost;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use App\Support\Branding;
|
||||
use Illuminate\Database\Seeder;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Inhaus\Plugins\Events\Models\Event;
|
||||
use Inhaus\Plugins\News\Models\NewsCategory;
|
||||
use Inhaus\Plugins\News\Models\NewsPost;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
|
|
@ -24,7 +25,7 @@ class DemoContentSeeder extends Seeder
|
|||
$authors = User::query()->inRandomOrder()->limit(5)->get();
|
||||
|
||||
$categories = collect([
|
||||
'Unternehmen', 'Arbeit & Bildung', 'Menschen', 'Nachhaltigkeit', 'Freizeit & Kultur', 'Verwaltung',
|
||||
'Unternehmen', 'Arbeit & Bildung', 'Menschen', 'Nachhaltigkeit', 'Freizeit & Kultur', 'Verwaltung', 'MAV-Info',
|
||||
])->mapWithKeys(fn (string $name, int $i) => [$name => NewsCategory::query()->create([
|
||||
'name' => $name,
|
||||
'slug' => Str::slug($name, language: 'de'),
|
||||
|
|
@ -59,6 +60,24 @@ class DemoContentSeeder extends Seeder
|
|||
]);
|
||||
}
|
||||
|
||||
// Beispiel für das Rechtesystem: Die MAV schreibt nur in „MAV-Info“.
|
||||
$mav = Role::query()->create(['name' => 'MAV', 'description' => 'Mitarbeitervertretung – schreibt in „MAV-Info“.']);
|
||||
$mav->grants()->create(['ability' => 'news.post.create', 'resource_type' => 'news_category', 'resource_id' => $categories['MAV-Info']->id]);
|
||||
$mav->grants()->create(['ability' => 'news.post.publish', 'resource_type' => 'news_category', 'resource_id' => $categories['MAV-Info']->id]);
|
||||
$mavMember = User::factory()->withRoles([$mav])->create([
|
||||
'first_name' => 'Grete', 'last_name' => 'Hoffmann', 'email' => 'mav@example.com',
|
||||
'job_title' => 'Vorsitzende der MAV', 'department' => 'Mitarbeitervertretung',
|
||||
]);
|
||||
|
||||
NewsPost::query()->create([
|
||||
'category_id' => $categories['MAV-Info']->id,
|
||||
'author_id' => $mavMember->id,
|
||||
'title' => 'MAV-Sprechstunde ab sofort jeden Dienstag',
|
||||
'teaser' => 'Wir sind für Ihre Fragen da – persönlich oder per Videoanruf.',
|
||||
'body' => $this->body('Wir sind für Ihre Fragen da – persönlich oder per Videoanruf.'),
|
||||
'published_at' => now()->subHours(30),
|
||||
]);
|
||||
|
||||
NewsPost::query()->create([
|
||||
'category_id' => $categories['Unternehmen']->id,
|
||||
'title' => 'Entwurf: Ausblick auf das zweite Halbjahr',
|
||||
|
|
|
|||
|
|
@ -131,6 +131,7 @@ plugins/mav-kalender/
|
|||
Einstellungsseiten, Admin-Ressourcen, Routen, Suche, Benachrichtigungen,
|
||||
geplante Jobs.
|
||||
- Stabile, versionierte Plugin-API (SemVer); Deprecations mit Vorlauf.
|
||||
- Entwickleranleitung: [`docs/PLUGINS.md`](PLUGINS.md).
|
||||
|
||||
### 4.4 Frontend von Plugins
|
||||
|
||||
|
|
@ -476,7 +477,7 @@ Kantinenplan, Ideenbox, Urlaubsanträge.
|
|||
| **0 – Fundament** ✅ | Laravel-Skeleton, Docker-Dev, CI-Matrix, `VERSION` + `CHANGELOG.md` + Build-Workflow (Assets/`vendor` mitversioniert), lokaler Login, User & Profil, Header mit Avatar, Design-System (Tailwind/shadcn-vue) mit Design-Tokens, **Basis-Branding (Portalname, Logo, Markenfarbe)**, Personenverzeichnis, Schnellzugriffe, Filament-Grundgerüst |
|
||||
| **0b – News & Termine (vorgezogen)** ✅ | Neuigkeiten mit Kategorien, Titelbild, Planung, Hervorhebung (Slider); Termine mit .ics-Export; Startseite nach Intranet-Vorbild. Redaktion vorerst nur im Admin-Backend – Rechte pro Kategorie, Redaktion im Portal und Umzug in Plugins folgen mit Phase 2 |
|
||||
| **1 – Betrieb & Lizenz** ✅ | **Self-Updater** (inkl. Wartungsmodus, Auto-Migration, Kanäle), **Lizenz-Speicher & -Client** (rotierendes Token), Seite „Aktualisierung“, **Rückmeldungen**, Web-Installer, Site Health, Cron-Varianten |
|
||||
| **2 – Plugin-System & Rechte** | Plugin-Loader, Hooks/Filter, Registries, Recovery-Modus, Import-Map-Frontend; Rollen, Grants, Zielgruppen, Rechte-Cache, Rechte-Prüfer |
|
||||
| **2 – Plugin-System & Rechte** ✅ | Plugin-Loader, Hooks/Filter, Registries, Recovery-Modus, Import-Map-Frontend; Rollen, Grants, Zielgruppen, Rechte-Cache, Rechte-Prüfer |
|
||||
| **3 – Entra ID** | OIDC-Login, JIT, Gruppen-/App-Rollen-Mapping (additiv), Graph-Profil- & Foto-Sync, Delta-Sync |
|
||||
| **4 – CMS** | Seitenbaum, Pagebuilder, Versionen; News-Freigabe-Workflow und Redaktion im Portal |
|
||||
| **5 – Branding & Theming** | Vollständige Seite „Erscheinungsbild“: Logo-Varianten, Farben inkl. Farbtreue & Kontrastprüfung, Schriften, Form, Login-Seite, E-Mails, Live-Vorschau, Entwurf/Veröffentlichen, Export/Import |
|
||||
|
|
|
|||
105
docs/PLUGINS.md
Normal file
105
docs/PLUGINS.md
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
# Plugins entwickeln
|
||||
|
||||
Inhaus lässt sich wie WordPress über Plugins erweitern. Auch die mitgelieferten
|
||||
Funktionen „Neuigkeiten“ und „Termine“ sind Plugins (`plugins-core/news`,
|
||||
`plugins-core/events`) – sie sind die beste Vorlage.
|
||||
|
||||
## Aufbau
|
||||
|
||||
```
|
||||
mein-plugin/
|
||||
plugin.json Manifest (Pflicht)
|
||||
src/Plugin.php Einstiegsklasse, erbt von App\Plugins\Plugin
|
||||
src/… weiterer PHP-Code (PSR-4 unter „namespace“)
|
||||
src/Filament/Resources/ Admin-Seiten (werden automatisch gefunden)
|
||||
src/Filament/Pages/
|
||||
database/migrations/ laufen bei Aktivierung und nach Updates
|
||||
routes/web.php Routen (Middleware „web“ ist gesetzt)
|
||||
resources/views/ Blade-Views, Namespace = Kürzel: view('mein-plugin::seite')
|
||||
vendor/ eigene Abhängigkeiten – bitte gescoped (Strauss/PHP-Scoper)
|
||||
```
|
||||
|
||||
### plugin.json
|
||||
|
||||
```json
|
||||
{
|
||||
"slug": "mein-plugin",
|
||||
"name": "Mein Plugin",
|
||||
"version": "1.0.0",
|
||||
"description": "Wofür das Plugin da ist.",
|
||||
"author": "Firma GmbH",
|
||||
"namespace": "Firma\\MeinPlugin\\",
|
||||
"class": "Firma\\MeinPlugin\\Plugin",
|
||||
"requires": { "core": ">=0.3.0", "php": ">=8.3", "plugins": ["news"] }
|
||||
}
|
||||
```
|
||||
|
||||
- `slug`: Kleinbuchstaben, Ziffern, Bindestriche; eindeutig. Kürzel mitgelieferter
|
||||
Plugins sind vergeben.
|
||||
- `namespace`: darf nicht mit `App\` beginnen.
|
||||
- `requires.core` / `requires.php`: Versionsbedingungen (`>=`, `<`, `^`, `~`, exakt).
|
||||
- `requires.plugins`: Plugins, die aktiv sein müssen.
|
||||
|
||||
### Einstiegsklasse
|
||||
|
||||
```php
|
||||
namespace Firma\MeinPlugin;
|
||||
|
||||
use App\Dashboard\Widgets;
|
||||
use App\Plugins\Hooks;
|
||||
use App\Plugins\Plugin as BasePlugin;
|
||||
use App\Support\Abilities;
|
||||
use App\Support\Navigation;
|
||||
|
||||
class Plugin extends BasePlugin
|
||||
{
|
||||
public function register(): void
|
||||
{
|
||||
// Menüpunkt im Portal
|
||||
$this->app->make(Navigation::class)->add('mein-plugin', 'Mein Bereich', '/mein-bereich', active: 'mein-plugin.*', sort: 40);
|
||||
|
||||
// Rechte, die im Rollen-Formular erscheinen
|
||||
$this->app->make(Abilities::class)->define('mein-plugin.manage', 'Mein Bereich verwalten', 'Mein Plugin');
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
Hooks::on('news.post.published', fn ($post) => /* … */ null);
|
||||
Hooks::filter('navigation.items', fn (array $items) => $items);
|
||||
}
|
||||
|
||||
public function activate(): void {} // nach „Aktivieren“ (Migrationen sind schon gelaufen)
|
||||
public function deactivate(): void {} // vor „Deaktivieren“
|
||||
public function uninstall(): void {} // bei „Mit Daten löschen“ (Tabellen entfernt der Kern)
|
||||
}
|
||||
```
|
||||
|
||||
## Rechte und Sichtbarkeit
|
||||
|
||||
- Globale Rechte: `$abilities->define('schluessel', 'Bezeichnung', 'Gruppe')`,
|
||||
prüfen mit `$user->can('schluessel')`.
|
||||
- Objekt-Rechte: `define(..., resource: 'mein_typ')` plus
|
||||
`$abilities->resourceType('mein_typ', 'Bezeichnung', fn () => [id => 'Name'])`;
|
||||
prüfen mit `$user->can('schluessel', ['mein_typ', $id])` oder einem Modell mit
|
||||
`permissionResource()`.
|
||||
- Zielgruppen: `App\Support\Permissions\Audiences::constrain($query, 'mein_typ', 'tabelle.id', $user)`
|
||||
und im Admin-Formular `App\Filament\Components\AudienceSection::make('mein_typ')`.
|
||||
- Admin-Seiten: Policies registrieren (`Gate::policy(Model::class, Policy::class)`)
|
||||
bzw. `canAccess()` an Filament-Seiten.
|
||||
|
||||
## Installation und Betrieb
|
||||
|
||||
- Als ZIP unter **Administration → Plugins** hochladen (ein gemeinsamer
|
||||
Ordner im Archiv ist erlaubt), dann aktivieren.
|
||||
- Kunden-Plugins liegen in `plugins/` und werden von Aktualisierungen nie verändert.
|
||||
- Wirft ein Plugin beim Laden einen Fehler – oder bringt es den PHP-Prozess zum
|
||||
Absturz –, wird es automatisch deaktiviert; der Grund steht auf der Plugins-Seite.
|
||||
- `INHAUS_DISALLOW_FILE_MODS=true` in der `.env` verbietet Hochladen und Löschen.
|
||||
|
||||
## Derzeit noch nicht für Kunden-Plugins
|
||||
|
||||
Vue-Seiten und Startseiten-Kacheln werden beim Build des Kerns mitkompiliert –
|
||||
das geht nur für mitgelieferte Plugins. Für Kunden-Plugins folgt mit dem
|
||||
öffentlichen Plugin-SDK (Phase 7) ein Weg über vorkompilierte ES-Module und
|
||||
eine Import-Map. Bis dahin können Kunden-Plugins Blade-Seiten, Admin-Seiten,
|
||||
Hooks, Rechte und Menüpunkte beitragen.
|
||||
13
plugins-core/events/plugin.json
Normal file
13
plugins-core/events/plugin.json
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
{
|
||||
"slug": "events",
|
||||
"name": "Termine",
|
||||
"version": "1.0.0",
|
||||
"description": "Veranstaltungen und Fortbildungen mit Kalender-Export.",
|
||||
"author": "Inhaus",
|
||||
"namespace": "Inhaus\\Plugins\\Events\\",
|
||||
"class": "Inhaus\\Plugins\\Events\\EventsPlugin",
|
||||
"requires": {
|
||||
"core": ">=0.3.0",
|
||||
"php": ">=8.3"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import EventDateBlock from '@/components/EventDateBlock.vue';
|
||||
import EventDateBlock from './EventDateBlock.vue';
|
||||
import { formatEventRange } from '@/lib/format';
|
||||
|
||||
defineProps({
|
||||
|
|
@ -3,7 +3,7 @@ import { computed } from 'vue';
|
|||
import { Link } from '@inertiajs/vue3';
|
||||
import { CalendarDays, MapPin, Video } from '@lucide/vue';
|
||||
import EmptyState from '@/components/EmptyState.vue';
|
||||
import EventDateBlock from '@/components/EventDateBlock.vue';
|
||||
import EventDateBlock from '../components/EventDateBlock.vue';
|
||||
import AppLayout from '@/layouts/AppLayout.vue';
|
||||
import { formatEventRange, formatMonthYear } from '@/lib/format';
|
||||
|
||||
|
|
@ -2,7 +2,7 @@
|
|||
import { Link } from '@inertiajs/vue3';
|
||||
import { ArrowLeft, CalendarPlus, Clock, MapPin, Video } from '@lucide/vue';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import EventDateBlock from '@/components/EventDateBlock.vue';
|
||||
import EventDateBlock from '../components/EventDateBlock.vue';
|
||||
import Panel from '@/components/Panel.vue';
|
||||
import AppLayout from '@/layouts/AppLayout.vue';
|
||||
import { formatEventRange } from '@/lib/format';
|
||||
19
plugins-core/events/resources/js/widgets/Upcoming.vue
Normal file
19
plugins-core/events/resources/js/widgets/Upcoming.vue
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
<script setup>
|
||||
import { CalendarDays } from '@lucide/vue';
|
||||
import EmptyState from '@/components/EmptyState.vue';
|
||||
import Panel from '@/components/Panel.vue';
|
||||
import EventListItem from '../components/EventListItem.vue';
|
||||
|
||||
defineProps({
|
||||
events: { type: Array, required: true },
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Panel title="Termine" action-label="Alle Termine" action-href="/termine">
|
||||
<div v-if="events.length" class="-my-3 divide-y">
|
||||
<EventListItem v-for="event in events" :key="event.id" :event="event" />
|
||||
</div>
|
||||
<EmptyState v-else :icon="CalendarDays" title="Keine anstehenden Termine" class="py-6" />
|
||||
</Panel>
|
||||
</template>
|
||||
10
plugins-core/events/routes/web.php
Normal file
10
plugins-core/events/routes/web.php
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Inhaus\Plugins\Events\Http\Controllers\EventController;
|
||||
|
||||
Route::middleware('auth')->group(function () {
|
||||
Route::get('/termine', [EventController::class, 'index'])->name('events.index');
|
||||
Route::get('/termine/{event}', [EventController::class, 'show'])->name('events.show');
|
||||
Route::get('/termine/{event}/kalender.ics', [EventController::class, 'ics'])->name('events.ics');
|
||||
});
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
namespace Inhaus\Plugins\Events;
|
||||
|
||||
use App\Models\Event;
|
||||
use Illuminate\Support\Str;
|
||||
use Inhaus\Plugins\Events\Models\Event;
|
||||
|
||||
/**
|
||||
* iCalendar-Export (RFC 5545) für einzelne Termine – zum Übernehmen in Outlook & Co.
|
||||
|
|
@ -1,15 +1,17 @@
|
|||
<?php
|
||||
|
||||
namespace Database\Factories;
|
||||
namespace Inhaus\Plugins\Events\Database\Factories;
|
||||
|
||||
use App\Models\Event;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
use Inhaus\Plugins\Events\Models\Event;
|
||||
|
||||
/**
|
||||
* @extends Factory<Event>
|
||||
*/
|
||||
class EventFactory extends Factory
|
||||
{
|
||||
protected $model = Event::class;
|
||||
|
||||
public function definition(): array
|
||||
{
|
||||
$start = now()->addDays(fake()->numberBetween(1, 30))->setTime(10, 0);
|
||||
27
plugins-core/events/src/EventsPlugin.php
Normal file
27
plugins-core/events/src/EventsPlugin.php
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Events;
|
||||
|
||||
use App\Dashboard\Widgets;
|
||||
use App\Models\User;
|
||||
use App\Plugins\Plugin;
|
||||
use App\Support\Abilities;
|
||||
use App\Support\Navigation;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Inhaus\Plugins\Events\Http\Resources\EventResource;
|
||||
use Inhaus\Plugins\Events\Models\Event;
|
||||
use Inhaus\Plugins\Events\Policies\EventPolicy;
|
||||
|
||||
class EventsPlugin extends Plugin
|
||||
{
|
||||
public function register(): void
|
||||
{
|
||||
$this->app->make(Navigation::class)->add('events', 'Termine', '/termine', active: 'events.*', sort: 30);
|
||||
$this->app->make(Abilities::class)->define('events.manage', 'Termine verwalten', 'Termine');
|
||||
Gate::policy(Event::class, EventPolicy::class);
|
||||
|
||||
$this->app->make(Widgets::class)->add('events.upcoming', 'events::Upcoming', 'aside', sort: 20, props: fn (User $user) => [
|
||||
'events' => EventResource::collection(Event::query()->upcoming()->visibleTo($user)->limit(4)->get())->resolve(),
|
||||
], mobileSort: 30);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,11 +1,8 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Events;
|
||||
namespace Inhaus\Plugins\Events\Filament\Resources\Events;
|
||||
|
||||
use App\Filament\Resources\Events\Pages\CreateEvent;
|
||||
use App\Filament\Resources\Events\Pages\EditEvent;
|
||||
use App\Filament\Resources\Events\Pages\ListEvents;
|
||||
use App\Models\Event;
|
||||
use App\Filament\Components\AudienceSection;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
|
|
@ -24,6 +21,10 @@ use Filament\Tables\Columns\TextColumn;
|
|||
use Filament\Tables\Filters\TernaryFilter;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Inhaus\Plugins\Events\Filament\Resources\Events\Pages\CreateEvent;
|
||||
use Inhaus\Plugins\Events\Filament\Resources\Events\Pages\EditEvent;
|
||||
use Inhaus\Plugins\Events\Filament\Resources\Events\Pages\ListEvents;
|
||||
use Inhaus\Plugins\Events\Models\Event;
|
||||
use UnitEnum;
|
||||
|
||||
class EventResource extends Resource
|
||||
|
|
@ -83,6 +84,7 @@ class EventResource extends Resource
|
|||
Section::make('Anzeige')
|
||||
->columnSpan(1)
|
||||
->schema([
|
||||
AudienceSection::make('event', 'Wer den Termin sieht. Leer lassen = alle.'),
|
||||
Toggle::make('is_published')->label('Veröffentlicht')->default(true),
|
||||
FileUpload::make('image_path')
|
||||
->label('Bild')
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Events\Pages;
|
||||
namespace Inhaus\Plugins\Events\Filament\Resources\Events\Pages;
|
||||
|
||||
use App\Filament\Resources\Events\EventResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
use Inhaus\Plugins\Events\Filament\Resources\Events\EventResource;
|
||||
|
||||
class CreateEvent extends CreateRecord
|
||||
{
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Events\Pages;
|
||||
namespace Inhaus\Plugins\Events\Filament\Resources\Events\Pages;
|
||||
|
||||
use App\Filament\Resources\Events\EventResource;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
use Inhaus\Plugins\Events\Filament\Resources\Events\EventResource;
|
||||
|
||||
class EditEvent extends EditRecord
|
||||
{
|
||||
|
|
@ -1,10 +1,10 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Events\Pages;
|
||||
namespace Inhaus\Plugins\Events\Filament\Resources\Events\Pages;
|
||||
|
||||
use App\Filament\Resources\Events\EventResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Inhaus\Plugins\Events\Filament\Resources\Events\EventResource;
|
||||
|
||||
class ListEvents extends ListRecords
|
||||
{
|
||||
|
|
@ -1,31 +1,32 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
namespace Inhaus\Plugins\Events\Http\Controllers;
|
||||
|
||||
use App\Http\Resources\EventResource;
|
||||
use App\Models\Event;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Support\Branding;
|
||||
use App\Support\Calendar;
|
||||
use Illuminate\Http\Response as HttpResponse;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Inhaus\Plugins\Events\Calendar;
|
||||
use Inhaus\Plugins\Events\Http\Resources\EventResource;
|
||||
use Inhaus\Plugins\Events\Models\Event;
|
||||
|
||||
class EventController extends Controller
|
||||
{
|
||||
public function index(): Response
|
||||
{
|
||||
return Inertia::render('Events/Index', [
|
||||
return Inertia::render('events::Index', [
|
||||
'events' => EventResource::collection(
|
||||
Event::query()->upcoming()->limit(200)->get()
|
||||
Event::query()->upcoming()->visibleTo(request()->user())->limit(200)->get()
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
public function show(Event $event): Response
|
||||
{
|
||||
abort_unless($event->is_published, 404);
|
||||
abort_unless($event->is_published && $event->isVisibleTo(request()->user()), 404);
|
||||
|
||||
return Inertia::render('Events/Show', [
|
||||
return Inertia::render('events::Show', [
|
||||
'event' => [
|
||||
...(new EventResource($event))->resolve(),
|
||||
'description_html' => $event->description_html,
|
||||
|
|
@ -35,7 +36,7 @@ class EventController extends Controller
|
|||
|
||||
public function ics(Event $event, Calendar $calendar, Branding $branding): HttpResponse
|
||||
{
|
||||
abort_unless($event->is_published, 404);
|
||||
abort_unless($event->is_published && $event->isVisibleTo(request()->user()), 404);
|
||||
|
||||
return response($calendar->toIcs($event, $branding->portalName()), 200, [
|
||||
'Content-Type' => 'text/calendar; charset=utf-8',
|
||||
|
|
@ -1,10 +1,10 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
namespace Inhaus\Plugins\Events\Http\Resources;
|
||||
|
||||
use App\Models\Event;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
use Inhaus\Plugins\Events\Models\Event;
|
||||
|
||||
/**
|
||||
* @mixin Event
|
||||
|
|
@ -1,14 +1,17 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
namespace Inhaus\Plugins\Events\Models;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Support\Images;
|
||||
use App\Support\Permissions\Audiences;
|
||||
use App\Support\RichText;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Inhaus\Plugins\Events\Database\Factories\EventFactory;
|
||||
|
||||
#[Fillable([
|
||||
'author_id', 'title', 'description', 'location', 'online_url',
|
||||
|
|
@ -18,6 +21,11 @@ class Event extends Model
|
|||
{
|
||||
use HasFactory;
|
||||
|
||||
protected static function newFactory(): EventFactory
|
||||
{
|
||||
return EventFactory::new();
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::saving(function (Event $event): void {
|
||||
|
|
@ -82,4 +90,23 @@ class Event extends Model
|
|||
{
|
||||
return app(Images::class)->url($this->image_path, $variant);
|
||||
}
|
||||
|
||||
/**
|
||||
* Nur Termine, die diese Person sehen darf (Zielgruppe des Termins).
|
||||
*
|
||||
* @param Builder<Event> $query
|
||||
*/
|
||||
public function scopeVisibleTo(Builder $query, ?User $user): void
|
||||
{
|
||||
if ($user?->can('events.manage')) {
|
||||
return;
|
||||
}
|
||||
|
||||
Audiences::constrain($query, 'event', 'events.id', $user);
|
||||
}
|
||||
|
||||
public function isVisibleTo(?User $user): bool
|
||||
{
|
||||
return (bool) $user?->can('events.manage') || Audiences::allows('event', $this->id, $user);
|
||||
}
|
||||
}
|
||||
29
plugins-core/events/src/Policies/EventPolicy.php
Normal file
29
plugins-core/events/src/Policies/EventPolicy.php
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Events\Policies;
|
||||
|
||||
use App\Models\User;
|
||||
use Inhaus\Plugins\Events\Models\Event;
|
||||
|
||||
class EventPolicy
|
||||
{
|
||||
public function viewAny(User $user): bool
|
||||
{
|
||||
return $user->can('events.manage');
|
||||
}
|
||||
|
||||
public function create(User $user): bool
|
||||
{
|
||||
return $user->can('events.manage');
|
||||
}
|
||||
|
||||
public function update(User $user, Event $event): bool
|
||||
{
|
||||
return $user->can('events.manage');
|
||||
}
|
||||
|
||||
public function delete(User $user, Event $event): bool
|
||||
{
|
||||
return $user->can('events.manage');
|
||||
}
|
||||
}
|
||||
13
plugins-core/news/plugin.json
Normal file
13
plugins-core/news/plugin.json
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
{
|
||||
"slug": "news",
|
||||
"name": "Neuigkeiten",
|
||||
"version": "1.0.0",
|
||||
"description": "Beiträge mit Kategorien, Titelbildern und Hervorhebung auf der Startseite.",
|
||||
"author": "Inhaus",
|
||||
"namespace": "Inhaus\\Plugins\\News\\",
|
||||
"class": "Inhaus\\Plugins\\News\\NewsPlugin",
|
||||
"requires": {
|
||||
"core": ">=0.3.0",
|
||||
"php": ">=8.3"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import CategoryLabel from '@/components/CategoryLabel.vue';
|
||||
import NewsImage from '@/components/NewsImage.vue';
|
||||
import CategoryLabel from './CategoryLabel.vue';
|
||||
import NewsImage from './NewsImage.vue';
|
||||
import { formatShortDate } from '@/lib/format';
|
||||
|
||||
defineProps({
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import CategoryLabel from '@/components/CategoryLabel.vue';
|
||||
import NewsImage from '@/components/NewsImage.vue';
|
||||
import CategoryLabel from './CategoryLabel.vue';
|
||||
import NewsImage from './NewsImage.vue';
|
||||
import { formatRelative } from '@/lib/format';
|
||||
|
||||
defineProps({
|
||||
|
|
@ -3,7 +3,7 @@ import { Link, router } from '@inertiajs/vue3';
|
|||
import { ChevronLeft, ChevronRight, Newspaper } from '@lucide/vue';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import EmptyState from '@/components/EmptyState.vue';
|
||||
import NewsCard from '@/components/NewsCard.vue';
|
||||
import NewsCard from '../components/NewsCard.vue';
|
||||
import AppLayout from '@/layouts/AppLayout.vue';
|
||||
|
||||
defineProps({
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import { ArrowLeft, Clock } from '@lucide/vue';
|
||||
import CategoryLabel from '@/components/CategoryLabel.vue';
|
||||
import NewsCard from '@/components/NewsCard.vue';
|
||||
import CategoryLabel from '../components/CategoryLabel.vue';
|
||||
import NewsCard from '../components/NewsCard.vue';
|
||||
import PersonAvatar from '@/components/PersonAvatar.vue';
|
||||
import AppLayout from '@/layouts/AppLayout.vue';
|
||||
import { formatDate } from '@/lib/format';
|
||||
17
plugins-core/news/resources/js/widgets/Areas.vue
Normal file
17
plugins-core/news/resources/js/widgets/Areas.vue
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
<script setup>
|
||||
import Panel from '@/components/Panel.vue';
|
||||
import NewsCard from '../components/NewsCard.vue';
|
||||
|
||||
defineProps({
|
||||
posts: { type: Array, required: true },
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Panel title="Aktuelles aus den Bereichen" action-label="Alle" action-href="/neuigkeiten">
|
||||
<!-- Mobil wischbar, ab sm als Raster -->
|
||||
<div class="-mx-5 flex snap-x scroll-px-5 gap-4 overflow-x-auto px-5 pb-1 [scrollbar-width:none] sm:mx-0 sm:grid sm:grid-cols-2 sm:overflow-visible sm:px-0 sm:pb-0 xl:grid-cols-4 [&::-webkit-scrollbar]:hidden">
|
||||
<NewsCard v-for="post in posts" :key="post.id" :post="post" class="w-[78%] shrink-0 snap-start sm:w-auto" />
|
||||
</div>
|
||||
</Panel>
|
||||
</template>
|
||||
11
plugins-core/news/resources/js/widgets/Hero.vue
Normal file
11
plugins-core/news/resources/js/widgets/Hero.vue
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
<script setup>
|
||||
import HeroSlider from '../components/HeroSlider.vue';
|
||||
|
||||
defineProps({
|
||||
posts: { type: Array, required: true },
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<HeroSlider :posts="posts" class="h-full" />
|
||||
</template>
|
||||
23
plugins-core/news/resources/js/widgets/Latest.vue
Normal file
23
plugins-core/news/resources/js/widgets/Latest.vue
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
<script setup>
|
||||
import { Newspaper } from '@lucide/vue';
|
||||
import EmptyState from '@/components/EmptyState.vue';
|
||||
import Panel from '@/components/Panel.vue';
|
||||
import NewsListItem from '../components/NewsListItem.vue';
|
||||
|
||||
defineProps({
|
||||
posts: { type: Array, required: true },
|
||||
canWrite: { type: Boolean, default: false },
|
||||
wide: { type: Boolean, default: false },
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Panel title="Neuigkeiten" action-label="Alle anzeigen" action-href="/neuigkeiten">
|
||||
<div v-if="posts.length" class="-my-3 divide-y" :class="{ 'sm:grid sm:grid-cols-2 sm:gap-x-6 sm:divide-y-0': wide }">
|
||||
<NewsListItem v-for="post in posts" :key="post.id" :post="post" />
|
||||
</div>
|
||||
<EmptyState v-else :icon="Newspaper" title="Noch keine Neuigkeiten" text="Sobald Beiträge veröffentlicht sind, erscheinen sie hier.">
|
||||
<a v-if="canWrite" href="/admin/neuigkeiten/neu" class="mt-4 text-sm font-medium text-brand-text hover:underline">Ersten Beitrag schreiben</a>
|
||||
</EmptyState>
|
||||
</Panel>
|
||||
</template>
|
||||
9
plugins-core/news/routes/web.php
Normal file
9
plugins-core/news/routes/web.php
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Inhaus\Plugins\News\Http\Controllers\NewsController;
|
||||
|
||||
Route::middleware('auth')->group(function () {
|
||||
Route::get('/neuigkeiten', [NewsController::class, 'index'])->name('news.index');
|
||||
Route::get('/neuigkeiten/{post:slug}', [NewsController::class, 'show'])->name('news.show');
|
||||
});
|
||||
|
|
@ -1,16 +1,18 @@
|
|||
<?php
|
||||
|
||||
namespace Database\Factories;
|
||||
namespace Inhaus\Plugins\News\Database\Factories;
|
||||
|
||||
use App\Models\NewsCategory;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
use Illuminate\Support\Str;
|
||||
use Inhaus\Plugins\News\Models\NewsCategory;
|
||||
|
||||
/**
|
||||
* @extends Factory<NewsCategory>
|
||||
*/
|
||||
class NewsCategoryFactory extends Factory
|
||||
{
|
||||
protected $model = NewsCategory::class;
|
||||
|
||||
public function definition(): array
|
||||
{
|
||||
$name = fake()->unique()->words(2, true);
|
||||
|
|
@ -1,15 +1,17 @@
|
|||
<?php
|
||||
|
||||
namespace Database\Factories;
|
||||
namespace Inhaus\Plugins\News\Database\Factories;
|
||||
|
||||
use App\Models\NewsPost;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
use Inhaus\Plugins\News\Models\NewsPost;
|
||||
|
||||
/**
|
||||
* @extends Factory<NewsPost>
|
||||
*/
|
||||
class NewsPostFactory extends Factory
|
||||
{
|
||||
protected $model = NewsPost::class;
|
||||
|
||||
public function definition(): array
|
||||
{
|
||||
return [
|
||||
|
|
@ -1,20 +1,23 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\NewsCategories;
|
||||
namespace Inhaus\Plugins\News\Filament\Resources\NewsCategories;
|
||||
|
||||
use App\Filament\Resources\NewsCategories\Pages\ManageNewsCategories;
|
||||
use App\Models\NewsCategory;
|
||||
use App\Filament\Components\AudienceSection;
|
||||
use App\Filament\Components\RoleGrantSelect;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Set;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Support\Str;
|
||||
use Inhaus\Plugins\News\Filament\Resources\NewsCategories\Pages\ManageNewsCategories;
|
||||
use Inhaus\Plugins\News\Models\NewsCategory;
|
||||
use UnitEnum;
|
||||
|
||||
class NewsCategoryResource extends Resource
|
||||
|
|
@ -50,6 +53,15 @@ class NewsCategoryResource extends Resource
|
|||
->unique(ignoreRecord: true),
|
||||
TextInput::make('description')->label('Beschreibung')->maxLength(500)->columnSpanFull(),
|
||||
TextInput::make('sort')->label('Reihenfolge')->numeric()->default(0),
|
||||
Section::make('Redaktion')
|
||||
->description('Welche Rollen in dieser Kategorie Beiträge schreiben und veröffentlichen dürfen – z. B. die MAV in „MAV-Info“.')
|
||||
->columnSpanFull()
|
||||
->columns(2)
|
||||
->schema([
|
||||
RoleGrantSelect::make('writers', 'Dürfen schreiben', 'news.post.create', 'news_category'),
|
||||
RoleGrantSelect::make('publishers', 'Dürfen veröffentlichen', 'news.post.publish', 'news_category'),
|
||||
]),
|
||||
AudienceSection::make('news_category', 'Wer Beiträge dieser Kategorie sieht. Leer lassen = alle.')->columnSpanFull(),
|
||||
]);
|
||||
}
|
||||
|
||||
|
|
@ -1,10 +1,10 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\NewsCategories\Pages;
|
||||
namespace Inhaus\Plugins\News\Filament\Resources\NewsCategories\Pages;
|
||||
|
||||
use App\Filament\Resources\NewsCategories\NewsCategoryResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ManageRecords;
|
||||
use Inhaus\Plugins\News\Filament\Resources\NewsCategories\NewsCategoryResource;
|
||||
|
||||
class ManageNewsCategories extends ManageRecords
|
||||
{
|
||||
|
|
@ -1,11 +1,7 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\NewsPosts;
|
||||
namespace Inhaus\Plugins\News\Filament\Resources\NewsPosts;
|
||||
|
||||
use App\Filament\Resources\NewsPosts\Pages\CreateNewsPost;
|
||||
use App\Filament\Resources\NewsPosts\Pages\EditNewsPost;
|
||||
use App\Filament\Resources\NewsPosts\Pages\ListNewsPosts;
|
||||
use App\Models\NewsPost;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\DeleteAction;
|
||||
|
|
@ -19,6 +15,7 @@ use Filament\Forms\Components\TextInput;
|
|||
use Filament\Forms\Components\Toggle;
|
||||
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;
|
||||
|
|
@ -26,6 +23,13 @@ use Filament\Tables\Columns\ImageColumn;
|
|||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\SelectFilter;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Inhaus\Plugins\News\Filament\Resources\NewsPosts\Pages\CreateNewsPost;
|
||||
use Inhaus\Plugins\News\Filament\Resources\NewsPosts\Pages\EditNewsPost;
|
||||
use Inhaus\Plugins\News\Filament\Resources\NewsPosts\Pages\ListNewsPosts;
|
||||
use Inhaus\Plugins\News\Models\NewsCategory;
|
||||
use Inhaus\Plugins\News\Models\NewsPost;
|
||||
use Inhaus\Plugins\News\Policies\NewsPostPolicy;
|
||||
use UnitEnum;
|
||||
|
||||
class NewsPostResource extends Resource
|
||||
|
|
@ -80,17 +84,27 @@ class NewsPostResource extends Resource
|
|||
->schema([
|
||||
Select::make('category_id')
|
||||
->label('Kategorie')
|
||||
->relationship('category', 'name')
|
||||
->relationship('category', 'name', fn (Builder $query) => static::onlyWritableCategories($query))
|
||||
->required(fn () => ! auth()->user()->can('news.manage'))
|
||||
->rule(fn () => function (string $attribute, mixed $value, \Closure $fail) {
|
||||
if ($value && ! static::onlyWritableCategories(NewsCategory::query())->whereKey($value)->exists()) {
|
||||
$fail('In dieser Kategorie dürfen Sie keine Beiträge schreiben.');
|
||||
}
|
||||
})
|
||||
->live()
|
||||
->preload()
|
||||
->searchable(),
|
||||
DateTimePicker::make('published_at')
|
||||
->label('Veröffentlichen am')
|
||||
->disabled(fn (Get $get) => ! static::canPublishIn($get('category_id')))
|
||||
->hint(fn (Get $get) => static::canPublishIn($get('category_id')) ? null : 'Veröffentlichung durch die Redaktion')
|
||||
->helperText('Leer lassen = Entwurf. Ein Datum in der Zukunft plant den Beitrag.')
|
||||
->seconds(false)
|
||||
->native(false)
|
||||
->displayFormat('d.m.Y H:i'),
|
||||
Toggle::make('is_featured')
|
||||
->label('Auf der Startseite hervorheben')
|
||||
->disabled(fn (Get $get) => ! static::canPublishIn($get('category_id')))
|
||||
->helperText('Hervorgehobene Beiträge mit Titelbild erscheinen groß im Slider.'),
|
||||
FileUpload::make('cover_path')
|
||||
->label('Titelbild')
|
||||
|
|
@ -106,6 +120,33 @@ class NewsPostResource extends Resource
|
|||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Redakteure sehen nur Beiträge aus Kategorien, in denen sie schreiben dürfen.
|
||||
*/
|
||||
public static function getEloquentQuery(): Builder
|
||||
{
|
||||
$query = parent::getEloquentQuery();
|
||||
$ids = auth()->user()?->permissions()->ids('news.post.create', 'news_category') ?? [];
|
||||
|
||||
return $ids === true || auth()->user()?->can('news.manage') ? $query : $query->whereIn('category_id', $ids);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<NewsCategory> $query
|
||||
* @return Builder<NewsCategory>
|
||||
*/
|
||||
public static function onlyWritableCategories(Builder $query): Builder
|
||||
{
|
||||
$ids = auth()->user()?->permissions()->ids('news.post.create', 'news_category') ?? [];
|
||||
|
||||
return $ids === true || auth()->user()?->can('news.manage') ? $query : $query->whereIn('id', $ids);
|
||||
}
|
||||
|
||||
public static function canPublishIn(mixed $categoryId): bool
|
||||
{
|
||||
return app(NewsPostPolicy::class)->publish(auth()->user(), $categoryId ? (int) $categoryId : null);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\NewsPosts\Pages;
|
||||
namespace Inhaus\Plugins\News\Filament\Resources\NewsPosts\Pages;
|
||||
|
||||
use App\Filament\Resources\NewsPosts\NewsPostResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
use Inhaus\Plugins\News\Filament\Resources\NewsPosts\NewsPostResource;
|
||||
|
||||
class CreateNewsPost extends CreateRecord
|
||||
{
|
||||
|
|
@ -13,6 +13,11 @@ class CreateNewsPost extends CreateRecord
|
|||
{
|
||||
$data['author_id'] = auth()->id();
|
||||
|
||||
if (! NewsPostResource::canPublishIn($data['category_id'] ?? null)) {
|
||||
$data['published_at'] = null;
|
||||
$data['is_featured'] = false;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\News\Filament\Resources\NewsPosts\Pages;
|
||||
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
use Inhaus\Plugins\News\Filament\Resources\NewsPosts\NewsPostResource;
|
||||
|
||||
class EditNewsPost extends EditRecord
|
||||
{
|
||||
protected static string $resource = NewsPostResource::class;
|
||||
|
||||
protected function mutateFormDataBeforeSave(array $data): array
|
||||
{
|
||||
if (! NewsPostResource::canPublishIn($data['category_id'] ?? $this->record->category_id)) {
|
||||
$data['published_at'] = $this->record->published_at;
|
||||
$data['is_featured'] = $this->record->is_featured;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
DeleteAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,10 +1,10 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\NewsPosts\Pages;
|
||||
namespace Inhaus\Plugins\News\Filament\Resources\NewsPosts\Pages;
|
||||
|
||||
use App\Filament\Resources\NewsPosts\NewsPostResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Inhaus\Plugins\News\Filament\Resources\NewsPosts\NewsPostResource;
|
||||
|
||||
class ListNewsPosts extends ListRecords
|
||||
{
|
||||
|
|
@ -1,30 +1,32 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
namespace Inhaus\Plugins\News\Http\Controllers;
|
||||
|
||||
use App\Http\Resources\NewsPostResource;
|
||||
use App\Models\NewsCategory;
|
||||
use App\Models\NewsPost;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Inhaus\Plugins\News\Http\Resources\NewsPostResource;
|
||||
use Inhaus\Plugins\News\Models\NewsCategory;
|
||||
use Inhaus\Plugins\News\Models\NewsPost;
|
||||
|
||||
class NewsController extends Controller
|
||||
{
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$categories = NewsCategory::query()->orderBy('sort')->orderBy('name')->get(['id', 'name', 'slug']);
|
||||
$categories = NewsCategory::query()->visibleTo($request->user())->orderBy('sort')->orderBy('name')->get(['id', 'name', 'slug']);
|
||||
$category = $categories->firstWhere('slug', $request->query('kategorie'));
|
||||
|
||||
$posts = NewsPost::query()
|
||||
->published()
|
||||
->visibleTo($request->user())
|
||||
->with('category')
|
||||
->when($category, fn ($query) => $query->where('category_id', $category->id))
|
||||
->latest('published_at')
|
||||
->paginate(12)
|
||||
->withQueryString();
|
||||
|
||||
return Inertia::render('News/Index', [
|
||||
return Inertia::render('news::Index', [
|
||||
'posts' => NewsPostResource::collection($posts),
|
||||
'categories' => $categories->map(fn (NewsCategory $c) => ['name' => $c->name, 'slug' => $c->slug]),
|
||||
'activeCategory' => $category?->slug,
|
||||
|
|
@ -33,11 +35,11 @@ class NewsController extends Controller
|
|||
|
||||
public function show(NewsPost $post): Response
|
||||
{
|
||||
abort_unless($post->isPublished(), 404);
|
||||
abort_unless($post->isPublished() && $post->isVisibleTo(request()->user()), 404);
|
||||
|
||||
$post->load(['category', 'author']);
|
||||
|
||||
return Inertia::render('News/Show', [
|
||||
return Inertia::render('news::Show', [
|
||||
'post' => [
|
||||
...(new NewsPostResource($post))->resolve(),
|
||||
'body_html' => $post->body_html,
|
||||
|
|
@ -52,6 +54,7 @@ class NewsController extends Controller
|
|||
'related' => NewsPostResource::collection(
|
||||
NewsPost::query()
|
||||
->published()
|
||||
->visibleTo(request()->user())
|
||||
->with('category')
|
||||
->whereKeyNot($post->id)
|
||||
->when($post->category_id, fn ($query) => $query->where('category_id', $post->category_id))
|
||||
|
|
@ -1,10 +1,10 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
namespace Inhaus\Plugins\News\Http\Resources;
|
||||
|
||||
use App\Models\NewsPost;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
use Inhaus\Plugins\News\Models\NewsPost;
|
||||
|
||||
/**
|
||||
* @mixin NewsPost
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue