Loheide-eu-mitarbeiterplatt.../app/Filament/Resources/IdentityProviders/IdentityProviderResource.php
Friederich Loheide 6269d3302c
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m43s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m52s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m49s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m49s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 2m12s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 2m22s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 1m57s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 1m59s
CI / Build-Artefakte aktuell (pull_request) Successful in 57s
Beliebige Entra-Attribute ins Profil übernehmen; eigene Profilfelder
- Profilfelder frei definierbar (Typ, Sichtbarkeit, selbst pflegbar), Werte als JSON am Benutzer
- Attribut-Zuordnung je Anbieter statt fester Feldliste: jedes Graph-Attribut inkl.
  verschachtelter Pfade, onPremisesExtensionAttributes und Verzeichniserweiterungen
- Erweiterungsattribute per Knopf aus Entra laden
- $select dynamisch aus der Zuordnung; Delta-Abgleich startet bei geänderter Zuordnung neu
- Rückfall auf Grundattribute, wenn einzelne Attribute nicht lesbar sind
- Ältere Konfiguration (synced_fields) wird weiter gelesen

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

269 lines
17 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\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
{
$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.'),
]),
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 Mandanten.'),
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“ – erhält jede Person, die sich über Entra anmeldet.'),
]),
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'),
]),
]);
}
/**
* @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('Typ')->formatStateUsing(fn () => 'Microsoft Entra ID'),
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)
->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'),
];
}
}