Loheide-eu-mitarbeiterplatt.../app/Filament/Resources/IdentityProviders/IdentityProviderResource.php
Friederich Loheide 4fcc41ed30
All checks were successful
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 2m41s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 2m48s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 3m15s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 3m17s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 3m48s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 3m41s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 3m33s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m26s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 3m59s
Phase 6 (Teil 2): OpenID Connect, LDAP/AD und SAML 2
- Gemeinsamer Treiber-Unterbau (App\Identity\IdentityDriver, IdentityDrivers,
  IdentityLogin, AttributeProfile); Entra ID nutzt ihn ebenfalls
- Plugins oidc, ldap und saml mit Profil- und Gruppen-Zuordnung
- Admin: Verfahren wählen, Formular je Verfahren, zuletzt empfangene Angaben
- onelogin/php-saml als neue Abhängigkeit

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 12:38:32 +00:00

441 lines
26 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Filament\Resources\IdentityProviders;
use App\Filament\Resources\IdentityProviders\Pages\CreateIdentityProvider;
use App\Filament\Resources\IdentityProviders\Pages\EditIdentityProvider;
use App\Filament\Resources\IdentityProviders\Pages\ListIdentityProviders;
use App\Filament\Resources\IdentityProviders\Pages\TestMapping;
use App\Http\Controllers\Auth\IdentityLoginController;
use App\Identity\Entra\EntraAttributes;
use App\Identity\Entra\EntraDirectorySync;
use App\Identity\Entra\MappingTester;
use App\Identity\IdentityDriver;
use App\Identity\IdentityDrivers;
use App\Identity\IdentityLogin;
use App\Models\IdentityProvider;
use App\Models\IdpGroupMapping;
use App\Models\Role;
use App\Support\ProfileFields;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TagsInput;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Carbon;
use Illuminate\Support\HtmlString;
use Throwable;
use UnitEnum;
class IdentityProviderResource extends Resource
{
protected static ?string $model = IdentityProvider::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedKey;
protected static string|UnitEnum|null $navigationGroup = 'Benutzer & Rechte';
protected static ?int $navigationSort = 4;
protected static ?string $modelLabel = 'Anmeldung (Identity Provider)';
protected static ?string $pluralModelLabel = 'Anmeldung';
protected static ?string $navigationLabel = 'Anmeldung';
protected static ?string $slug = 'anmeldung';
public static function canAccess(): bool
{
return auth()->user()?->can('identity.manage') ?? false;
}
public static function form(Schema $schema): Schema
{
$type = static::typeFor($schema);
if ($type !== IdentityProvider::ENTRA) {
return static::genericForm($schema, $type);
}
return static::entraForm($schema);
}
/**
* Verfahren des bearbeiteten bzw. neu anzulegenden Anbieters.
*/
public static function typeFor(Schema $schema): string
{
$record = $schema->getRecord();
if ($record instanceof IdentityProvider) {
return (string) $record->type;
}
$livewire = $schema->getLivewire();
return property_exists($livewire, 'type') && is_string($livewire->type) ? $livewire->type : IdentityProvider::ENTRA;
}
public static function entraForm(Schema $schema): Schema
{
$guid = '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i';
return $schema
->columns(1)
->components([
Section::make('Microsoft Entra ID')
->columns(2)
->schema([
Hidden::make('type')->default(IdentityProvider::ENTRA),
TextInput::make('name')->label('Bezeichnung')->required()->maxLength(100)->default('Microsoft Entra ID'),
TextInput::make('config.button_label')->label('Text auf dem Anmeldeknopf')->placeholder('Mit Microsoft anmelden')->maxLength(60),
Toggle::make('enabled')->label('Anmeldung aktiv')->helperText('Zeigt „Mit Microsoft anmelden“ auf der Anmeldeseite. Die Anmeldung mit Passwort bleibt für Notfälle erhalten.')->columnSpanFull(),
]),
Section::make('App-Registrierung')
->description('Aus dem Microsoft Entra Admin Center → App-Registrierungen.')
->columns(2)
->schema([
Text::make(fn (?IdentityProvider $record) => new HtmlString(
'Umleitungs-URI (Typ „Web“): <code>'.e($record ? IdentityLoginController::callbackUrlFor($record) : url('/auth/<kürzel>/callback')).'</code><br>'
.'API-Berechtigungen (Microsoft Graph): delegiert <em>User.Read</em>, <em>GroupMember.Read.All</em>; '
.'für den Hintergrund-Abgleich zusätzlich Anwendung <em>User.Read.All</em>, <em>GroupMember.Read.All</em> und <em>Application.Read.All</em> (für App-Rollen) – jeweils mit Administratorzustimmung.'
))->columnSpanFull(),
TextInput::make('config.tenant_id')->label('Verzeichnis-ID (Mandant)')->required()->regex($guid)
->validationMessages(['regex' => 'Bitte die Verzeichnis-ID als GUID angeben (nicht den Domainnamen).']),
TextInput::make('config.client_id')->label('Anwendungs-ID (Client)')->required()->regex($guid)
->validationMessages(['regex' => 'Bitte die Anwendungs-ID als GUID angeben.']),
TextInput::make('config.client_secret')->label('Geheimer Clientschlüssel')->password()->revealable()
->required(fn (string $operation) => $operation === 'create')
->helperText(fn (string $operation) => $operation === 'edit' ? 'Leer lassen, um den gespeicherten Schlüssel zu behalten.' : 'Der Wert (nicht die ID) des Geheimnisses.'),
]),
static::accountsSection('Personen, die sich über Entra anmelden'),
Section::make('Profil')
->key('profile')
->description('Jedes Microsoft-Graph-Attribut lässt sich einem Profilfeld zuordnen – auch Personalnummer, Kostenstelle, lokale Erweiterungsattribute oder eigene Verzeichniserweiterungen. Zugeordnete Felder sind im Portal schreibgeschützt. Eigene Felder legen Sie unter „Profilfelder“ an.')
->afterHeader([
Action::make('loadExtensions')->label('Erweiterungsattribute laden')->icon(Heroicon::OutlinedArrowPath)
->color('gray')->size('sm')
->visible(fn (string $operation) => $operation === 'edit')
->action(function (IdentityProvider $record) {
try {
$names = app(MappingTester::class)->loadExtensionProperties($record);
Notification::make()->success()->title(count($names).' Verzeichniserweiterungen gefunden')
->body($names === [] ? 'Im Mandanten sind keine Erweiterungen für Benutzer registriert.' : 'Sie stehen jetzt in der Attributauswahl zur Verfügung.')
->send();
} catch (Throwable $e) {
Notification::make()->danger()->title('Erweiterungen konnten nicht geladen werden')
->body($e->getMessage().' Benötigt die Anwendungsberechtigung Directory.Read.All.')->send();
}
}),
])
->schema([
Repeater::make('config.attribute_map')
->hiddenLabel()
->columns(3)
->addActionLabel('Zuordnung hinzufügen')
->reorderable(false)
->default(fn () => collect(EntraAttributes::DEFAULT_MAP)->map(fn ($attribute, $target) => ['target' => $target, 'attribute' => $attribute])->values()->all())
->itemLabel(fn (array $state) => static::profileTargets()[$state['target'] ?? ''] ?? null)
->collapsible(false)
->schema([
Select::make('target')->label('Profilfeld')->required()->native(false)
->options(fn () => static::profileTargets())
->disableOptionsWhenSelectedInSiblingRepeaterItems(),
Select::make('suggestion')->label('Attribut auswählen')->placeholder('Aus der Liste übernehmen …')->searchable()->native(false)
->options(fn (?IdentityProvider $record) => collect(EntraAttributes::suggestions($record))
->mapWithKeys(fn ($label, $path) => [$path => $label.' · '.$path])->all())
->live()
->afterStateUpdated(fn (?string $state, Set $set) => $state ? $set('attribute', $state) : null)
->dehydrated(false),
TextInput::make('attribute')->label('Graph-Attribut')->required()->maxLength(191)
->regex(EntraAttributes::PATH_PATTERN)
->validationMessages(['regex' => 'Attributname oder Pfad mit Punkten, z. B. employeeOrgData.costCenter.'])
->datalist(fn (?IdentityProvider $record) => array_keys(EntraAttributes::suggestions($record)))
->placeholder('z. B. employeeId'),
]),
Text::make('Pfade mit Punkt lesen verschachtelte Werte (employeeOrgData.costCenter, businessPhones.0). Listen werden mit Komma verbunden. Manche Attribute brauchen zusätzliche Berechtigungen, z. B. employeeHireDate die Berechtigung User-LifeCycleInfo.Read.All.'),
Toggle::make('config.sync_manager')->label('Vorgesetzte*n aus Entra übernehmen')->default(true),
Toggle::make('config.sync_photo')->label('Profilfoto aus Entra übernehmen')->default(true),
]),
Section::make('Hintergrund-Abgleich')
->description('Übernimmt Änderungen und deaktiviert Konten, die in Entra deaktiviert oder gelöscht wurden – auch ohne Anmeldung. Läuft alle 15 Minuten mit den Hintergrundaufgaben.')
->columns(2)
->schema([
Toggle::make('config.directory_sync')->label('Abgleich aktiv')->live(),
Toggle::make('config.directory_create_users')->label('Alle Konten vorab anlegen')
->helperText('Sonst werden Konten erst bei der ersten Anmeldung angelegt.')
->visible(fn (Get $get) => (bool) $get('config.directory_sync')),
Text::make(fn (?IdentityProvider $record) => static::syncStatus($record))->columnSpanFull()
->visible(fn (?IdentityProvider $record, Get $get) => $record && $get('config.directory_sync')),
]),
Section::make('Gruppen und App-Rollen → Rollen')
->description('Personen in diesen Entra-Gruppen bzw. mit diesen App-Rollen erhalten die Rolle im Portal. Rollen sind additiv; manuell vergebene Rollen bleiben unberührt. Mehrere Zeilen je Gruppe für mehrere Rollen.')
->schema([
Repeater::make('mappings')
->relationship()
->hiddenLabel()
->columns(4)
->defaultItems(0)
->addActionLabel('Zuordnung hinzufügen')
->schema([
Select::make('kind')->label('Art')->options([IdpGroupMapping::GROUP => 'Gruppe', IdpGroupMapping::APP_ROLE => 'App-Rolle'])
->default(IdpGroupMapping::GROUP)->required()->live(),
Select::make('group_lookup')->label('Gruppe suchen')
->searchable()
->visible(fn (Get $get) => $get('kind') === IdpGroupMapping::GROUP)
->getSearchResultsUsing(function (string $search, $livewire) {
try {
return app(MappingTester::class)->searchGroups($livewire->getRecord(), $search);
} catch (Throwable) {
return [];
}
})
->getOptionLabelUsing(fn (?string $value) => $value)
->live()
->afterStateUpdated(function (?string $state, Set $set, $component) {
if ($state) {
$set('external_id', $state);
$set('external_name', trim(preg_replace('/\s*\([0-9a-f]{8}…\)$/', '', (string) $component->getOptionLabel())));
}
})
->helperText('Erfordert den Hintergrund-Abgleich (Anwendungsberechtigung).')
->dehydrated(false),
TextInput::make('external_id')
->label(fn (Get $get) => $get('kind') === IdpGroupMapping::APP_ROLE ? 'Wert der App-Rolle' : 'Objekt-ID der Gruppe')
->required()->maxLength(191),
TextInput::make('external_name')->label('Bezeichnung')->maxLength(191),
Select::make('role_id')->label('Rolle im Portal')->required()
->options(fn () => Role::query()->orderBy('name')->pluck('name', 'id')->all()),
])
->visible(fn (string $operation) => $operation === 'edit'),
Text::make('Zuordnungen lassen sich nach dem ersten Speichern pflegen.')->visible(fn (string $operation) => $operation === 'create'),
]),
]);
}
/**
* Formular für Verfahren aus Plugins (OpenID Connect, LDAP, SAML …).
*/
public static function genericForm(Schema $schema, string $type): Schema
{
$driver = app(IdentityDrivers::class)->get($type);
if (! $driver) {
return $schema->components([
Section::make('Verfahren nicht verfügbar')->schema([
Text::make('Das Plugin für dieses Anmeldeverfahren („'.$type.'“) ist deaktiviert oder nicht installiert. Die Einstellungen bleiben erhalten; die Anmeldung ist abgeschaltet, bis das Plugin wieder aktiv ist.'),
]),
]);
}
return $schema
->columns(1)
->components([
Section::make($driver->label())
->description($driver->description())
->columns(2)
->schema([
Hidden::make('type')->default($type),
TextInput::make('name')->label('Bezeichnung')->required()->maxLength(100)->default($driver->label())
->helperText('Erscheint in Meldungen, z. B. „Anmeldung über …“.'),
TextInput::make('config.button_label')->label('Text auf dem Anmeldeknopf')->maxLength(60)
->placeholder(fn (?IdentityProvider $record) => $record?->buttonLabel() ?? 'Mit … anmelden'),
Toggle::make('enabled')->label('Anmeldung aktiv')->columnSpanFull()
->helperText('Zeigt den Knopf auf der Anmeldeseite. Die Anmeldung mit Passwort bleibt für Notfälle erhalten.'),
Text::make(new HtmlString('<span style="color: rgb(220 38 38)">'.e((string) $driver->unavailableReason()).'</span>'))
->visible($driver->unavailableReason() !== null)->columnSpanFull(),
]),
Section::make('Verbindung')
->key('connection')
->description(fn (?IdentityProvider $record) => new HtmlString($driver->connectionHelp($record)))
->afterHeader(fn (string $operation) => $operation === 'edit' ? $driver->adminActions() : [])
->columns(2)
->schema($driver->connectionSchema()),
static::accountsSection('Personen, die sich über dieses Verfahren anmelden'),
Section::make('Profil')
->description('Welche Angaben des Anbieters in welches Profilfeld kommen. Zugeordnete Felder sind im Portal schreibgeschützt. Eigene Felder legen Sie unter „Profilfelder“ an.')
->schema([
Repeater::make('config.attribute_map')
->hiddenLabel()
->columns(3)
->addActionLabel('Zuordnung hinzufügen')
->reorderable(false)
->default(fn () => collect($driver->defaultAttributeMap())->map(fn ($attribute, $target) => ['target' => $target, 'attribute' => $attribute])->values()->all())
->itemLabel(fn (array $state) => static::profileTargets()[$state['target'] ?? ''] ?? null)
->schema([
Select::make('target')->label('Profilfeld')->required()->native(false)
->options(fn () => static::profileTargets())
->disableOptionsWhenSelectedInSiblingRepeaterItems(),
Select::make('suggestion')->label('Auswählen')->placeholder('Aus der Liste übernehmen …')->searchable()->native(false)
->options(fn (?IdentityProvider $record) => static::attributeOptions($driver, $record))
->live()
->afterStateUpdated(fn (?string $state, Set $set) => $state ? $set('attribute', $state) : null)
->dehydrated(false),
TextInput::make('attribute')->label($driver->attributeLabel())->required()->maxLength(191)
->regex($driver->attributePattern())
->validationMessages(['regex' => 'Bitte einen Attributnamen ohne Leerzeichen angeben.']),
]),
Toggle::make('config.sync_manager')->label('Vorgesetzte*n übernehmen')->default(true)->visible($driver->supportsManager())
->helperText('Verknüpft wird, sobald sich die vorgesetzte Person einmal angemeldet hat.'),
Toggle::make('config.sync_photo')->label('Profilfoto übernehmen')->default(true)->visible($driver->supportsPhoto()),
]),
Section::make('Zuletzt empfangene Angaben')
->description('Was der Anbieter bei der letzten Anmeldung übermittelt hat – hilft bei den Zuordnungen oben und unten.')
->collapsible()
->schema([Text::make(fn (?IdentityProvider $record) => static::lastSeenHtml($record))])
->visible(fn (string $operation) => $operation === 'edit'),
Section::make('Gruppen → Rollen')
->description('Personen in diesen Gruppen erhalten die Rolle im Portal. Rollen sind additiv; manuell vergebene Rollen bleiben unberührt. Groß- und Kleinschreibung spielt keine Rolle.')
->schema([
Repeater::make('mappings')
->relationship()
->hiddenLabel()
->columns(3)
->defaultItems(0)
->addActionLabel('Zuordnung hinzufügen')
->schema([
Hidden::make('kind')->default(IdpGroupMapping::GROUP),
TextInput::make('external_id')->label($driver->groupValueLabel())->required()->maxLength(191),
TextInput::make('external_name')->label('Bezeichnung')->maxLength(191),
Select::make('role_id')->label('Rolle im Portal')->required()
->options(fn () => Role::query()->orderBy('name')->pluck('name', 'id')->all()),
])
->visible(fn (string $operation) => $operation === 'edit'),
Text::make('Zuordnungen lassen sich nach dem ersten Speichern pflegen.')->visible(fn (string $operation) => $operation === 'create'),
]),
]);
}
public static function accountsSection(string $defaultRoleHelp): Section
{
return Section::make('Konten')
->columns(2)
->schema([
Toggle::make('config.auto_provision')->label('Konto bei erster Anmeldung anlegen')->default(true),
Toggle::make('config.link_by_email')->label('Bestehende Konten über die E-Mail-Adresse verknüpfen')->default(true),
TagsInput::make('config.allowed_domains')->label('Erlaubte E-Mail-Domains')->placeholder('firma.de')
->helperText('Leer = alle Konten des Anbieters.'),
Select::make('config.default_role_id')->label('Standardrolle für alle')
->options(fn () => Role::query()->where('slug', '!=', Role::ADMINISTRATION)->orderBy('name')->pluck('name', 'id')->all())
->helperText('z. B. „Mitarbeitende“ – erhalten alle '.$defaultRoleHelp.'.'),
]);
}
/**
* @return array<string, string>
*/
private static function attributeOptions(IdentityDriver $driver, ?IdentityProvider $record): array
{
$options = collect($driver->attributeSuggestions($record))->mapWithKeys(fn ($label, $name) => [$name => $label.' · '.$name]);
// Tatsächlich empfangene Attribute der letzten Anmeldung.
foreach (array_keys(($record ? IdentityLogin::lastSeen($record) : null)['attributes'] ?? []) as $name) {
$options[$name] ??= $name.' (zuletzt empfangen)';
}
return $options->all();
}
public static function lastSeenHtml(?IdentityProvider $record): HtmlString
{
$seen = $record ? IdentityLogin::lastSeen($record) : null;
if (! $seen) {
return new HtmlString('<span style="opacity:.7">Noch keine Anmeldung seit der Einrichtung.</span>');
}
$rows = '';
foreach ($seen['attributes'] as $name => $value) {
$rows .= '<tr><td style="padding:3px 12px 3px 0;vertical-align:top;font-family:ui-monospace,monospace;font-size:12px;word-break:break-all">'.e($name).'</td>'
.'<td style="padding:3px 0;word-break:break-word">'.e($value).'</td></tr>';
}
return new HtmlString(
'<p style="margin-bottom:8px">'.e(Carbon::createFromTimestamp($seen['at'])->locale('de')->diffForHumans()).' · Kennung <code>'.e($seen['subject']).'</code></p>'
.'<table style="width:100%;font-size:13px">'.$rows.'</table>'
.'<p style="margin-top:8px"><strong>Gruppen:</strong> '.($seen['groups'] === [] ? 'keine' : e(implode(' · ', $seen['groups']))).'</p>'
);
}
/**
* @return array<string, string> Zielfeld => Bezeichnung
*/
public static function profileTargets(): array
{
return IdentityProvider::PROFILE_TARGETS
+ collect(app(ProfileFields::class)->options())->mapWithKeys(fn ($label, $key) => ['custom.'.$key => $label.' (Profilfeld)'])->all();
}
public static function syncStatus(?IdentityProvider $record): HtmlString
{
if (! $record) {
return new HtmlString('');
}
$status = app(EntraDirectorySync::class)->status($record);
$when = fn (?int $ts) => $ts ? Carbon::createFromTimestamp($ts)->locale('de')->diffForHumans() : 'noch nie';
return new HtmlString(
'Letzter Lauf: '.e($when($status['last_run_at'] ?? null))
.' · Benutzer vollständig abgeglichen: '.e($when($status['users_synced_at'] ?? null))
.' · Gruppen: '.e($when($status['groups_synced_at'] ?? null))
.(! empty($status['last_error']) ? '<br><span style="color: rgb(220 38 38)">Fehler: '.e($status['last_error']).'</span>' : '')
);
}
public static function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('name')->label('Bezeichnung')->weight('medium'),
TextColumn::make('type')->label('Verfahren')
->formatStateUsing(fn (string $state) => app(IdentityDrivers::class)->get($state)?->label() ?? $state.' (Plugin deaktiviert)'),
IconColumn::make('enabled')->label('Aktiv')->boolean(),
TextColumn::make('mappings_count')->label('Zuordnungen')->counts('mappings'),
TextColumn::make('identities_count')->label('Verknüpfte Konten')->counts('identities'),
])
->recordActions([
Action::make('test')->label('Mapping testen')->icon(Heroicon::OutlinedBeaker)
->visible(fn (IdentityProvider $record) => $record->type === IdentityProvider::ENTRA)
->url(fn (IdentityProvider $record) => static::getUrl('test', ['record' => $record])),
EditAction::make(),
]);
}
public static function getPages(): array
{
return [
'index' => ListIdentityProviders::route('/'),
'create' => CreateIdentityProvider::route('/neu'),
'edit' => EditIdentityProvider::route('/{record}/bearbeiten'),
'test' => TestMapping::route('/{record}/testen'),
];
}
}