Beliebige Entra-Attribute ins Profil übernehmen; eigene Profilfelder
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

- 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>
This commit is contained in:
Friederich Loheide 2026-09-26 08:09:57 +00:00
parent 51c94cd0cf
commit 6269d3302c
79 changed files with 1442 additions and 273 deletions

View file

@ -7,21 +7,23 @@ 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\CheckboxList;
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;
@ -107,11 +109,51 @@ class IdentityProviderResource extends Resource
]),
Section::make('Profil')
->description('Gewählte Felder kommen aus Entra ID und sind im Portal schreibgeschützt. Nicht gewählte pflegen die Personen selbst.')
->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([
CheckboxList::make('config.synced_fields')->hiddenLabel()->columns(3)
->options(IdentityProvider::SYNCABLE_FIELDS)
->default(['first_name', 'last_name', 'email', 'job_title', 'department', 'location', 'phone', 'mobile', 'manager']),
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),
]),
@ -172,6 +214,15 @@ class IdentityProviderResource extends Resource
]);
}
/**
* @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) {

View file

@ -20,6 +20,13 @@ class EditIdentityProvider extends EditRecord
{
$data['config']['client_secret'] = null;
// Ältere Konfiguration (feste Feldliste) als Zuordnung anzeigen.
if (! is_array($data['config']['attribute_map'] ?? null)) {
$data['config']['attribute_map'] = collect($this->record->attributeMap())
->map(fn ($attribute, $target) => ['target' => $target, 'attribute' => $attribute])->values()->all();
$data['config']['sync_manager'] = $this->record->syncsManager();
}
return $data;
}
@ -32,6 +39,11 @@ class EditIdentityProvider extends EditRecord
$data['config']['client_secret'] = $this->record->setting('client_secret');
}
// Geladene Erweiterungen liegen nur in der Datenbank, nicht im Formular.
$data['config']['extension_properties'] = $this->record->fresh()?->setting('extension_properties', []) ?? [];
$data['config']['attribute_map'] = array_values((array) ($data['config']['attribute_map'] ?? []));
unset($data['config']['synced_fields']);
return $data;
}

View file

@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\ProfileFields\Pages;
use App\Filament\Resources\ProfileFields\ProfileFieldResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ManageRecords;
class ManageProfileFields extends ManageRecords
{
protected static string $resource = ProfileFieldResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make()->label('Profilfeld anlegen'),
];
}
}

View file

@ -0,0 +1,96 @@
<?php
namespace App\Filament\Resources\ProfileFields;
use App\Filament\Resources\ProfileFields\Pages\ManageProfileFields;
use App\Models\ProfileField;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
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;
/**
* Frei definierbare Profilfelder – etwa Personalnummer, Kostenstelle, Eintrittsdatum.
* Können von den Personen selbst gepflegt oder aus Entra ID übernommen werden.
*/
class ProfileFieldResource extends Resource
{
protected static ?string $model = ProfileField::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedIdentification;
protected static string|UnitEnum|null $navigationGroup = 'Benutzer & Rechte';
protected static ?int $navigationSort = 3;
protected static ?string $modelLabel = 'Profilfeld';
protected static ?string $pluralModelLabel = 'Profilfelder';
protected static ?string $slug = 'profilfelder';
public static function canAccess(): bool
{
return auth()->user()?->can('users.manage') ?? false;
}
public static function form(Schema $schema): Schema
{
return $schema
->columns(2)
->components([
TextInput::make('label')->label('Bezeichnung')->required()->maxLength(100),
TextInput::make('key')->label('Technischer Schlüssel')
->helperText('Wird aus der Bezeichnung erzeugt, wenn leer. Nachträglich nicht änderbar.')
->regex('/^[a-z][a-z0-9_]*$/')
->validationMessages(['regex' => 'Nur Kleinbuchstaben, Ziffern und Unterstriche, beginnend mit einem Buchstaben.'])
->maxLength(60)
->unique(ignoreRecord: true)
->disabledOn('edit'),
Select::make('type')->label('Typ')->options(ProfileField::TYPES)->default('text')->required()->native(false),
Select::make('visibility')->label('Sichtbarkeit')->options(ProfileField::VISIBILITIES)->default('public')->required()->native(false),
Toggle::make('editable')->label('Von der Person selbst pflegbar')->default(true)
->helperText('Aus Entra ID übernommene Felder sind unabhängig davon schreibgeschützt.'),
TextInput::make('sort')->label('Reihenfolge')->numeric()->default(0)->minValue(0),
TextInput::make('help')->label('Hinweis im Profilformular')->maxLength(255)->columnSpanFull(),
]);
}
public static function table(Table $table): Table
{
return $table
->defaultSort('sort')
->reorderable('sort')
->columns([
TextColumn::make('label')->label('Bezeichnung')->weight('medium'),
TextColumn::make('key')->label('Schlüssel')->fontFamily('mono')->color('gray'),
TextColumn::make('type')->label('Typ')->formatStateUsing(fn (string $state) => ProfileField::TYPES[$state] ?? $state),
TextColumn::make('visibility')->label('Sichtbarkeit')->badge()
->formatStateUsing(fn (string $state) => $state === 'public' ? 'Alle' : 'Eingeschränkt')
->color(fn (string $state) => $state === 'public' ? 'gray' : 'warning'),
IconColumn::make('editable')->label('Selbst pflegbar')->boolean(),
])
->recordActions([
EditAction::make(),
DeleteAction::make()->modalDescription('Die gespeicherten Werte bleiben erhalten, werden aber nicht mehr angezeigt.'),
])
->emptyStateHeading('Noch keine Profilfelder')
->emptyStateDescription('Zum Beispiel Personalnummer, Kostenstelle oder Eintrittsdatum – selbst gepflegt oder aus Entra ID übernommen.');
}
public static function getPages(): array
{
return [
'index' => ManageProfileFields::route('/'),
];
}
}

View file

@ -2,12 +2,16 @@
namespace App\Filament\Resources\Users\Schemas;
use App\Models\ProfileField;
use App\Models\Role;
use App\Models\User;
use App\Support\ProfileFields;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Illuminate\Validation\Rules\Password;
@ -16,6 +20,30 @@ class UserForm
{
public const PHONE_REGEX = '/^[0-9+()\/\-.\s]{3,50}$/';
/**
* Eingabefelder für die frei definierten Profilfelder.
*
* @return list<Component>
*/
private static function customFields(): array
{
return app(ProfileFields::class)->all()->map(function (ProfileField $field) {
$name = 'custom_fields.'.$field->key;
$hint = $field->visibility === 'restricted' ? 'Nur für die Person und die Personalverwaltung sichtbar.' : null;
$component = match ($field->type) {
'textarea' => Textarea::make($name)->rows(3)->maxLength(5000)->columnSpanFull(),
'date' => DatePicker::make($name)->native(false)->displayFormat('d.m.Y'),
'email' => TextInput::make($name)->email()->maxLength(255),
'url' => TextInput::make($name)->url()->maxLength(500),
'phone' => TextInput::make($name)->tel()->telRegex(self::PHONE_REGEX)->maxLength(50),
default => TextInput::make($name)->maxLength(255),
};
return $component->label($field->label)->helperText($hint);
})->values()->all();
}
public static function configure(Schema $schema): Schema
{
return $schema
@ -79,6 +107,11 @@ class UserForm
->rule(Password::default())
->dehydrated(fn (?string $state) => filled($state)),
]),
Section::make('Weitere Angaben')
->columnSpan(2)
->columns(2)
->schema(fn () => self::customFields())
->visible(fn () => app(ProfileFields::class)->all()->isNotEmpty()),
]);
}
}

View file

@ -4,6 +4,7 @@ namespace App\Http\Controllers;
use App\Http\Resources\PersonResource;
use App\Models\User;
use App\Support\ProfileFields;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
@ -71,6 +72,7 @@ class PeopleController extends Controller
'phone' => $user->phone,
'mobile' => $user->mobile,
'about' => $user->about,
'fields' => app(ProfileFields::class)->visibleValues($user, auth()->user()),
'avatar_url' => $user->avatarUrl(256),
'manager' => $user->manager?->is_active ? [
'id' => $user->manager->id,

View file

@ -5,6 +5,7 @@ namespace App\Http\Controllers;
use App\Http\Requests\UpdateProfileRequest;
use App\Models\User;
use App\Support\Avatars;
use App\Support\ProfileFields;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
@ -19,9 +20,10 @@ class ProfileController extends Controller
return to_route('people.show', $request->user());
}
public function edit(Request $request): Response
public function edit(Request $request, ProfileFields $profileFields): Response
{
$user = $request->user();
$managed = $user->managedFields();
return Inertia::render('Profile/Edit', [
'profile' => [
@ -35,14 +37,20 @@ class ProfileController extends Controller
'has_password' => $user->password !== null,
],
// Felder, die Microsoft Entra ID pflegt – im Portal nur lesbar.
'managed' => $user->managedFields(),
'managed' => $managed,
'customFields' => $profileFields->formFor($user, $managed),
]);
}
public function update(UpdateProfileRequest $request): RedirectResponse
public function update(UpdateProfileRequest $request, ProfileFields $profileFields): RedirectResponse
{
$user = $request->user();
$user->update(collect($request->validated())->except($user->managedFields())->all());
$managed = $user->managedFields();
$user->update(collect($request->validated())->except([...$managed, 'custom_fields'])->all());
if ($request->has('custom_fields')) {
$profileFields->mergeUserInput($user, (array) $request->validated('custom_fields', []), $managed);
}
return back()->with('status', 'profile-updated');
}

View file

@ -2,6 +2,7 @@
namespace App\Http\Requests;
use App\Support\ProfileFields;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
@ -27,6 +28,8 @@ class UpdateProfileRequest extends FormRequest
'phone' => ['nullable', 'string', 'max:50'],
'mobile' => ['nullable', 'string', 'max:50'],
'about' => ['nullable', 'string', 'max:2000'],
'custom_fields' => ['nullable', 'array'],
...app(ProfileFields::class)->rules(),
];
}
@ -45,6 +48,7 @@ class UpdateProfileRequest extends FormRequest
'phone' => 'Telefon',
'mobile' => 'Mobil',
'about' => 'Über mich',
...app(ProfileFields::class)->all()->mapWithKeys(fn ($field) => ['custom_fields.'.$field->key => $field->label])->all(),
];
}
}

View file

@ -0,0 +1,141 @@
<?php
namespace App\Identity\Entra;
use App\Models\IdentityProvider;
use Illuminate\Support\Arr;
/**
* Graph-Benutzerattribute: Vorschlagsliste, Standardzuordnung, $select-Aufbau
* und das Auslesen verschachtelter Werte.
*
* Ein Attribut ist ein Pfad in der Graph-Antwort, z. B. „jobTitle“,
* „employeeOrgData.costCenter“, „onPremisesExtensionAttributes.extensionAttribute3“,
* „businessPhones.0“ oder „extension_<appId>_personalnummer“.
*/
final class EntraAttributes
{
/** Wird immer abgefragt – für Kontoanlage, Verknüpfung und Offboarding. */
public const BASE_SELECT = ['id', 'displayName', 'givenName', 'surname', 'mail', 'userPrincipalName', 'accountEnabled', 'userType'];
/** Standardzuordnung Profilfeld => Attribut (entspricht dem bisherigen Verhalten). */
public const DEFAULT_MAP = [
'first_name' => 'givenName',
'last_name' => 'surname',
'email' => 'mail',
'job_title' => 'jobTitle',
'department' => 'department',
'location' => 'officeLocation',
'phone' => 'businessPhones.0',
'mobile' => 'mobilePhone',
];
/** Häufige Attribute als Vorschläge im Formular. */
public const COMMON = [
'givenName' => 'Vorname',
'surname' => 'Nachname',
'displayName' => 'Anzeigename',
'mail' => 'E-Mail-Adresse',
'userPrincipalName' => 'Benutzerprinzipalname',
'jobTitle' => 'Position',
'department' => 'Abteilung',
'companyName' => 'Firmenname',
'officeLocation' => 'Büro',
'businessPhones.0' => 'Telefon (geschäftlich)',
'mobilePhone' => 'Mobiltelefon',
'faxNumber' => 'Fax',
'streetAddress' => 'Straße',
'postalCode' => 'Postleitzahl',
'city' => 'Ort',
'state' => 'Bundesland',
'country' => 'Land',
'usageLocation' => 'Nutzungsstandort',
'preferredLanguage' => 'Bevorzugte Sprache',
'employeeId' => 'Personalnummer',
'employeeType' => 'Mitarbeitertyp',
'employeeHireDate' => 'Eintrittsdatum',
'employeeLeaveDateTime' => 'Austrittsdatum',
'employeeOrgData.costCenter' => 'Kostenstelle',
'employeeOrgData.division' => 'Bereich',
'otherMails' => 'Weitere E-Mail-Adressen',
'proxyAddresses' => 'Proxyadressen',
'onPremisesSamAccountName' => 'Anmeldename (lokal)',
'onPremisesDistinguishedName' => 'Distinguished Name (lokal)',
'onPremisesExtensionAttributes.extensionAttribute1' => 'Erweiterungsattribut 1 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute2' => 'Erweiterungsattribut 2 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute3' => 'Erweiterungsattribut 3 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute4' => 'Erweiterungsattribut 4 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute5' => 'Erweiterungsattribut 5 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute6' => 'Erweiterungsattribut 6 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute7' => 'Erweiterungsattribut 7 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute8' => 'Erweiterungsattribut 8 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute9' => 'Erweiterungsattribut 9 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute10' => 'Erweiterungsattribut 10 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute11' => 'Erweiterungsattribut 11 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute12' => 'Erweiterungsattribut 12 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute13' => 'Erweiterungsattribut 13 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute14' => 'Erweiterungsattribut 14 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute15' => 'Erweiterungsattribut 15 (lokal)',
];
/** Erlaubte Schreibweise eines Attributpfads. */
public const PATH_PATTERN = '/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)*$/';
/**
* $select für /me, /users/{id} und /users/delta.
*/
public static function select(IdentityProvider $provider): string
{
$top = array_map(fn (string $path) => self::topLevel($path), array_values($provider->attributeMap()));
return implode(',', array_values(array_unique([...self::BASE_SELECT, ...$top])));
}
public static function topLevel(string $path): string
{
return explode('.', $path, 2)[0];
}
/**
* Wert eines Attributpfads als Text. Listen werden mit Komma verbunden,
* Wahrheitswerte als „Ja“/„Nein“ ausgegeben; leere Werte ergeben null.
*
* @param array<string, mixed> $graphUser
*/
public static function value(array $graphUser, string $path): ?string
{
$value = $graphUser;
foreach (explode('.', $path) as $segment) {
if (! is_array($value) || ! array_key_exists($segment, $value)) {
return null;
}
$value = $value[$segment];
}
if (is_array($value)) {
$value = implode(', ', array_filter(Arr::flatten($value), fn ($v) => is_scalar($v) && $v !== ''));
} elseif (is_bool($value)) {
$value = $value ? 'Ja' : 'Nein';
}
$value = is_scalar($value) ? trim((string) $value) : '';
return $value === '' ? null : $value;
}
/**
* Vorschlagsliste fürs Formular: häufige Attribute plus geladene Verzeichniserweiterungen.
*
* @return array<string, string> Pfad => Beschreibung
*/
public static function suggestions(?IdentityProvider $provider): array
{
$extensions = collect((array) $provider?->setting('extension_properties', []))
->mapWithKeys(fn ($name) => [(string) $name => 'Verzeichniserweiterung'])
->all();
return self::COMMON + $extensions;
}
}

View file

@ -75,7 +75,14 @@ class EntraDirectorySync
private function syncUsers(IdentityProvider $provider, EntraClient $client, string $token, float $deadline): void
{
$url = $this->state($provider, 'next_link') ?: $this->state($provider, 'delta_link') ?: '/users/delta?$select='.EntraProfile::SELECT;
$select = EntraAttributes::select($provider);
// Neue Attribute zugeordnet: Der alte Delta-Link liefert sie nicht – einmal komplett abgleichen.
if ($this->state($provider, 'select') !== $select) {
$this->saveState($provider, ['delta_link' => null, 'next_link' => null, 'select' => $select]);
}
$url = $this->state($provider, 'next_link') ?: $this->state($provider, 'delta_link') ?: '/users/delta?$select='.$select;
while ($url && microtime(true) < $deadline) {
$response = $client->graph($token)->get($url);
@ -131,7 +138,7 @@ class EntraDirectorySync
// Ohne Vorab-Anlage: nur bestehende Konten per E-Mail verknüpfen.
try {
$user = $this->sync->resolveUser($provider, $subject, EntraProfile::fromGraph($graphUser), (bool) $createAllowed);
$user = $this->sync->resolveUser($provider, $subject, EntraProfile::fromGraph($provider, $graphUser), (bool) $createAllowed);
} catch (IdentityException) {
return; // z. B. nicht erlaubte E-Mail-Domain – dieses Konto überspringen
}
@ -144,11 +151,7 @@ class EntraDirectorySync
}
// Delta liefert nur geänderte Felder – fehlende Felder nicht leeren.
$profile = array_intersect_key(EntraProfile::fromGraph($graphUser), array_flip(array_map(fn ($key) => match ($key) {
'givenName' => 'first_name', 'surname' => 'last_name', 'mail' => 'email', 'jobTitle' => 'job_title',
'department' => 'department', 'officeLocation' => 'location', 'businessPhones' => 'phone', 'mobilePhone' => 'mobile',
'displayName' => 'display_name', default => '-',
}, array_keys($graphUser))));
$profile = EntraProfile::fromGraph($provider, $graphUser, partial: true);
$this->sync->syncProfile($provider, $identity->user, $profile);
}
@ -156,7 +159,7 @@ class EntraDirectorySync
private function syncPhotosAndManagers(IdentityProvider $provider, EntraClient $client, string $token, float $deadline): void
{
$withPhoto = (bool) $provider->setting('sync_photo', true);
$withManager = in_array('manager', $provider->syncedFields(), true);
$withManager = $provider->syncsManager();
if (! $withPhoto && ! $withManager) {
return;

View file

@ -84,10 +84,18 @@ class EntraLogin
$overage = isset($claims['_claim_names']['groups']) || ($claims['hasgroups'] ?? false);
try {
$me = $client->graph($token)->get('/me', ['$select' => EntraProfile::SELECT]);
$me = $client->graph($token)->get('/me', ['$select' => EntraAttributes::select($provider)]);
// Einzelne Attribute brauchen weitere Berechtigungen (z. B. employeeHireDate) –
// dann wenigstens die Grundangaben übernehmen.
if ($me->clientError() && $me->status() !== 401) {
Log::warning('Entra-Anmeldung: Zugeordnete Attribute nicht abrufbar ('.$me->status().'), nutze Grundangaben.');
$me = $client->graph($token)->get('/me', ['$select' => implode(',', EntraAttributes::BASE_SELECT)]);
}
$client->assertGraph($me);
$withManager = in_array('manager', $provider->syncedFields(), true);
$withManager = $provider->syncsManager();
$managerSubject = null;
if ($withManager) {
@ -95,7 +103,7 @@ class EntraLogin
$managerSubject = $manager->successful() ? $manager->json('id') : null;
}
$profile = EntraProfile::fromGraph((array) $me->json(), $managerSubject, $withManager);
$profile = EntraProfile::fromGraph($provider, (array) $me->json(), $managerSubject, $withManager);
} catch (Throwable $e) {
Log::warning('Entra-Anmeldung: Profil aus Graph nicht abrufbar, nutze ID-Token. '.$e->getMessage());
$profile = EntraProfile::fromClaims($claims);

View file

@ -2,31 +2,57 @@
namespace App\Identity\Entra;
use App\Models\IdentityProvider;
/**
* Normalisiert Entra-/Graph-Benutzerdaten auf die Profilfelder des Portals.
* Normalisiert Entra-/Graph-Benutzerdaten auf die Profilfelder des Portals –
* gemäß der Attribut-Zuordnung des Anbieters.
*
* Ergebnis: display_name, Kernfelder (first_name, email, …), freie Felder unter
* „custom“ und – falls abgefragt – manager_subject.
*/
final class EntraProfile
{
/** Felder, die bei Graph abgefragt werden. */
public const SELECT = 'id,displayName,givenName,surname,mail,userPrincipalName,jobTitle,department,officeLocation,businessPhones,mobilePhone,accountEnabled,userType';
/**
* @param array<string, mixed> $graphUser Antwort von /me bzw. /users/{id}
* @param array<string, mixed> $graphUser Antwort von /me, /users/{id} oder /users/delta
* @param bool $partial Delta-Antwort: nur Felder liefern, deren Attribut enthalten ist
* @return array<string, mixed>
*/
public static function fromGraph(array $graphUser, ?string $managerSubject = null, bool $withManager = false): array
public static function fromGraph(IdentityProvider $provider, array $graphUser, ?string $managerSubject = null, bool $withManager = false, bool $partial = false): array
{
$profile = [
'display_name' => $graphUser['displayName'] ?? null,
'first_name' => $graphUser['givenName'] ?? null,
'last_name' => $graphUser['surname'] ?? null,
'email' => $graphUser['mail'] ?? (str_contains((string) ($graphUser['userPrincipalName'] ?? ''), '#EXT#') ? null : ($graphUser['userPrincipalName'] ?? null)),
'job_title' => $graphUser['jobTitle'] ?? null,
'department' => $graphUser['department'] ?? null,
'location' => $graphUser['officeLocation'] ?? null,
'phone' => $graphUser['businessPhones'][0] ?? null,
'mobile' => $graphUser['mobilePhone'] ?? null,
];
$present = fn (string $path) => ! $partial || array_key_exists(EntraAttributes::topLevel($path), $graphUser);
$profile = [];
if ($present('displayName')) {
$profile['display_name'] = EntraAttributes::value($graphUser, 'displayName');
}
// Grundwerte für Kontoanlage und Verknüpfung; die Zuordnung überschreibt sie.
foreach (['first_name' => 'givenName', 'last_name' => 'surname', 'email' => 'mail'] as $field => $path) {
if ($present($path)) {
$profile[$field] = EntraAttributes::value($graphUser, $path);
}
}
foreach ($provider->attributeMap() as $target => $path) {
if (! $present($path)) {
continue;
}
$value = EntraAttributes::value($graphUser, $path);
if (str_starts_with($target, 'custom.')) {
$profile['custom'][substr($target, 7)] = $value;
} else {
$profile[$target] = $value;
}
}
// Gastkonten haben oft keine „mail“; der UPN ist dann eine #EXT#-Adresse.
if (array_key_exists('email', $profile) && $profile['email'] === null && ! $partial) {
$upn = (string) ($graphUser['userPrincipalName'] ?? '');
$profile['email'] = $upn !== '' && ! str_contains($upn, '#EXT#') ? $upn : null;
}
if ($withManager) {
$profile['manager_subject'] = $managerSubject;

View file

@ -97,4 +97,28 @@ class MappingTester
return collect((array) $response->json('value', []))->mapWithKeys(fn ($g) => [$g['id'] => $g['displayName'].' ('.substr($g['id'], 0, 8).'…)'])->all();
}
/**
* Verzeichniserweiterungen des Mandanten (extension_<appId>_<name>) für Benutzer –
* etwa aus Entra Connect synchronisierte AD-Attribute. Wird in der Konfiguration
* gespeichert und im Formular als Vorschlag angeboten.
*
* @return list<string>
*/
public function loadExtensionProperties(IdentityProvider $provider): array
{
$client = new EntraClient($provider);
$response = $client->graph($client->appToken())->post('/directoryObjects/getAvailableExtensionProperties', (object) []);
$client->assertGraph($response);
$names = collect((array) $response->json('value', []))
->filter(fn ($property) => in_array('User', (array) ($property['targetObjects'] ?? []), true))
->pluck('name')
->filter(fn ($name) => is_string($name) && preg_match(EntraAttributes::PATH_PATTERN, $name))
->unique()->sort()->values()->all();
$provider->update(['config' => array_merge((array) $provider->config, ['extension_properties' => $names])]);
return $names;
}
}

View file

@ -9,6 +9,8 @@ use App\Models\UserIdentity;
use App\Support\Audit;
use App\Support\Avatars;
use App\Support\Permissions\Permissions;
use App\Support\ProfileFields;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
@ -20,7 +22,10 @@ use Throwable;
*/
class IdentitySync
{
public function __construct(private readonly Avatars $avatars) {}
public function __construct(
private readonly Avatars $avatars,
private readonly ProfileFields $profileFields,
) {}
/**
* Konto zu einer externen Identität finden, verknüpfen oder anlegen.
@ -113,11 +118,56 @@ class IdentitySync
: null;
}
$custom = $this->customFieldChanges($user, $fields, (array) ($profile['custom'] ?? []));
if ($custom !== null) {
$changes['custom_fields'] = $custom;
}
if ($changes !== []) {
$user->forceFill($changes)->save();
}
}
/**
* Freie Profilfelder aus dem Anbieter übernehmen. Datumswerte werden als
* Y-m-d gespeichert, Werte ohne Felddefinition ignoriert.
*
* @param list<string> $fields
* @param array<string, string|null> $incoming
* @return array<string, string>|null null = keine Änderung
*/
private function customFieldChanges(User $user, array $fields, array $incoming): ?array
{
$definitions = $this->profileFields->all()->keyBy('key');
$values = (array) ($user->custom_fields ?? []);
$before = $values;
foreach ($incoming as $key => $value) {
$field = $definitions->get($key);
if (! $field || ! in_array('custom.'.$key, $fields, true)) {
continue;
}
if ($value !== null && $field->type === 'date') {
try {
$value = Carbon::parse($value)->format('Y-m-d');
} catch (Throwable) {
// Unlesbares Datum: unverändert übernehmen.
}
}
if ($value === null) {
unset($values[$key]);
} else {
$values[$key] = $value;
}
}
return $values === $before ? null : $values;
}
/**
* Profilfoto übernehmen, wenn es sich geändert hat. null = kein Foto beim Anbieter.
*/

View file

@ -2,6 +2,7 @@
namespace App\Models;
use App\Identity\Entra\EntraAttributes;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
@ -12,7 +13,9 @@ use Illuminate\Support\Str;
*
* config (verschlüsselt): tenant_id, client_id, client_secret, button_label,
* auto_provision, link_by_email, allowed_domains, default_role_id,
* synced_fields, sync_photo, directory_sync, directory_create_users
* attribute_map (Liste aus target + attribute), sync_manager, sync_photo,
* extension_properties, directory_sync, directory_create_users
* (älter: synced_fields – wird noch gelesen, siehe attributeMap())
*/
#[Fillable(['type', 'name', 'slug', 'enabled', 'config'])]
class IdentityProvider extends Model
@ -20,7 +23,8 @@ class IdentityProvider extends Model
public const ENTRA = 'entra';
/** Profilfelder, die aus dem Identity Provider übernommen werden können. */
public const SYNCABLE_FIELDS = [
/** Kernfelder des Profils, die aus einem Attribut befüllt werden können. */
public const PROFILE_TARGETS = [
'first_name' => 'Vorname',
'last_name' => 'Nachname',
'email' => 'E-Mail-Adresse',
@ -29,7 +33,6 @@ class IdentityProvider extends Model
'location' => 'Standort',
'phone' => 'Telefon',
'mobile' => 'Mobil',
'manager' => 'Vorgesetzte*r',
];
protected static function booted(): void
@ -53,11 +56,50 @@ class IdentityProvider extends Model
}
/**
* Zuordnung Profilfeld => Graph-Attribut. Ziele sind Kernfelder („job_title“)
* oder freie Profilfelder („custom.personalnummer“). Ohne gespeicherte Zuordnung
* gilt die Standardzuordnung für die früher gewählten Felder.
*
* @return array<string, string>
*/
public function attributeMap(): array
{
$rows = $this->setting('attribute_map');
if (! is_array($rows)) {
$legacy = (array) $this->setting('synced_fields', array_keys(EntraAttributes::DEFAULT_MAP));
return array_intersect_key(EntraAttributes::DEFAULT_MAP, array_flip($legacy));
}
$map = [];
foreach ($rows as $row) {
$target = (string) ($row['target'] ?? '');
$attribute = trim((string) ($row['attribute'] ?? ''));
if ($attribute !== '' && preg_match(EntraAttributes::PATH_PATTERN, $attribute)
&& (array_key_exists($target, self::PROFILE_TARGETS) || str_starts_with($target, 'custom.'))) {
$map[$target] = $attribute;
}
}
return $map;
}
public function syncsManager(): bool
{
return (bool) $this->setting('sync_manager', in_array('manager', (array) $this->setting('synced_fields', ['manager']), true));
}
/**
* Felder, die dieser Anbieter pflegt (im Portal schreibgeschützt).
*
* @return list<string>
*/
public function syncedFields(): array
{
return array_values(array_intersect((array) $this->setting('synced_fields', []), array_keys(self::SYNCABLE_FIELDS)));
return [...array_keys($this->attributeMap()), ...($this->syncsManager() ? ['manager'] : [])];
}
public function buttonLabel(): string

View file

@ -0,0 +1,41 @@
<?php
namespace App\Models;
use App\Support\ProfileFields;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
#[Fillable(['key', 'label', 'type', 'visibility', 'editable', 'help', 'sort'])]
class ProfileField extends Model
{
public const TYPES = [
'text' => 'Text',
'textarea' => 'Mehrzeiliger Text',
'email' => 'E-Mail-Adresse',
'phone' => 'Telefonnummer',
'url' => 'Link',
'date' => 'Datum',
];
public const VISIBILITIES = [
'public' => 'Für alle sichtbar',
'restricted' => 'Nur die Person selbst und die Personalverwaltung',
];
protected static function booted(): void
{
static::saving(function (ProfileField $field) {
$field->key = $field->key ?: Str::slug($field->label, '_', 'de');
});
static::saved(fn () => app(ProfileFields::class)->flush());
static::deleted(fn () => app(ProfileFields::class)->flush());
}
protected function casts(): array
{
return ['editable' => 'boolean'];
}
}

View file

@ -23,7 +23,7 @@ use Illuminate\Support\Str;
#[Fillable([
'name', 'first_name', 'last_name', 'email', 'password',
'job_title', 'department', 'location', 'phone', 'mobile', 'about',
'job_title', 'department', 'location', 'phone', 'mobile', 'about', 'custom_fields',
'is_active', 'theme',
])]
#[Hidden(['password', 'remember_token'])]
@ -51,6 +51,7 @@ class User extends Authenticatable implements FilamentUser, HasAvatar
return [
'email_verified_at' => 'datetime',
'last_login_at' => 'datetime',
'custom_fields' => 'array',
'password' => 'hashed',
'is_active' => 'boolean',
];

View file

@ -13,6 +13,7 @@ use App\Support\Installation;
use App\Support\License\LicenseStore;
use App\Support\Permissions\PermissionResource;
use App\Support\Permissions\Permissions;
use App\Support\ProfileFields;
use App\Support\QuickLinks;
use App\Support\Settings;
use App\Support\Update\InstalledVersion;
@ -43,6 +44,7 @@ class AppServiceProvider extends ServiceProvider
$this->app->singleton(QuickLinks::class);
$this->app->singleton(LicenseStore::class);
$this->app->singleton(Permissions::class);
$this->app->singleton(ProfileFields::class);
$this->app->singleton(BackgroundTasks::class);
$this->app->singleton(InstalledVersion::class);
$this->app->singleton(UpdateProgress::class);

View file

@ -5,6 +5,7 @@ namespace App\Providers\Filament;
use App\Filament\AvatarProviders\InitialsAvatarProvider;
use App\Filament\Pages\Feedback;
use App\Filament\Resources\IdentityProviders\IdentityProviderResource;
use App\Filament\Resources\ProfileFields\ProfileFieldResource;
use App\Filament\Resources\Roles\RoleResource;
use App\Filament\Resources\Users\UserResource;
use App\Plugins\PluginManager;
@ -63,6 +64,7 @@ class AdminPanelProvider extends PanelProvider
->resources([
UserResource::class,
RoleResource::class,
ProfileFieldResource::class,
IdentityProviderResource::class,
])
->discoverPages(in: app_path('Filament/Pages'), for: 'App\Filament\Pages')

View file

@ -0,0 +1,147 @@
<?php
namespace App\Support;
use App\Models\ProfileField;
use App\Models\User;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Throwable;
/**
* Frei definierbare Profilfelder: Definitionen (gecacht), Sichtbarkeit und Validierung.
*/
class ProfileFields
{
private const CACHE_KEY = 'profile-fields';
/** @var Collection<int, ProfileField>|null */
private ?Collection $fields = null;
/**
* @return Collection<int, ProfileField>
*/
public function all(): Collection
{
try {
// Im Cache nur Arrays – Laravel deserialisiert dort keine Objekte.
return $this->fields ??= ProfileField::hydrate(Cache::rememberForever(
self::CACHE_KEY,
fn () => ProfileField::query()->orderBy('sort')->orderBy('label')->get()->map->getAttributes()->all(),
));
} catch (Throwable $e) {
report($e);
return collect();
}
}
public function flush(): void
{
$this->fields = null;
Cache::forget(self::CACHE_KEY);
}
/**
* @return array<string, string> Schlüssel => Bezeichnung
*/
public function options(): array
{
return $this->all()->pluck('label', 'key')->all();
}
/**
* Felder mit Werten, die $viewer bei $person sehen darf.
*
* @return list<array{key: string, label: string, type: string, value: string}>
*/
public function visibleValues(User $person, ?User $viewer): array
{
$seesRestricted = $viewer && ($viewer->is($person) || $viewer->can('users.manage'));
$values = (array) ($person->custom_fields ?? []);
return $this->all()
->filter(fn (ProfileField $field) => $field->visibility === 'public' || $seesRestricted)
->filter(fn (ProfileField $field) => filled($values[$field->key] ?? null))
->map(fn (ProfileField $field) => [
'key' => $field->key,
'label' => $field->label,
'type' => $field->type,
'value' => $this->display($field, (string) $values[$field->key]),
])
->values()
->all();
}
/**
* Definitionen und Werte für das Bearbeitungsformular der Person selbst.
*
* @param list<string> $managed vom Identity Provider gepflegte Felder („custom.<key>“)
* @return list<array<string, mixed>>
*/
public function formFor(User $user, array $managed): array
{
$values = (array) ($user->custom_fields ?? []);
return $this->all()->map(fn (ProfileField $field) => [
'key' => $field->key,
'label' => $field->label,
'type' => $field->type,
'help' => $field->help,
'restricted' => $field->visibility === 'restricted',
'value' => $values[$field->key] ?? '',
'readonly' => ! $field->editable || in_array('custom.'.$field->key, $managed, true),
'managed' => in_array('custom.'.$field->key, $managed, true),
])->values()->all();
}
/**
* @return array<string, list<mixed>>
*/
public function rules(string $prefix = 'custom_fields'): array
{
return $this->all()->mapWithKeys(fn (ProfileField $field) => [
"{$prefix}.{$field->key}" => array_merge(['nullable'], match ($field->type) {
'email' => ['email', 'max:255'],
'url' => ['url', 'max:500'],
'date' => ['date'],
'phone' => ['string', 'max:50'],
'textarea' => ['string', 'max:5000'],
default => ['string', 'max:255'],
}),
])->all();
}
/**
* Nur die Felder übernehmen, die die Person selbst pflegen darf.
*
* @param array<string, mixed> $input
* @param list<string> $managed
*/
public function mergeUserInput(User $user, array $input, array $managed): void
{
$values = (array) ($user->custom_fields ?? []);
foreach ($this->all() as $field) {
if ($field->editable && ! in_array('custom.'.$field->key, $managed, true) && array_key_exists($field->key, $input)) {
$values[$field->key] = filled($input[$field->key]) ? (string) $input[$field->key] : null;
}
}
$user->forceFill(['custom_fields' => array_filter($values, fn ($v) => $v !== null)])->save();
}
private function display(ProfileField $field, string $value): string
{
if ($field->type === 'date') {
try {
return Carbon::parse($value)->format('d.m.Y');
} catch (Throwable) {
return $value;
}
}
return $value;
}
}