Loheide-eu-mitarbeiterplatt.../app/Identity/Entra/MappingTester.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

124 lines
5.7 KiB
PHP
Raw Permalink 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\Identity\Entra;
use App\Identity\IdentityException;
use App\Models\IdentityProvider;
use App\Models\IdpGroupMapping;
use App\Models\Role;
/**
* „Mapping testen“: Welche Gruppen und App-Rollen liefert Entra für eine Person,
* und welche Rollen entstehen daraus im Portal?
*/
class MappingTester
{
/**
* @return array{user: array<string, mixed>, groups: list<array{id: string, name: string, roles: list<string>}>, app_roles: list<array{value: string, roles: list<string>}>, roles: list<string>}
*/
public function test(IdentityProvider $provider, string $userPrincipal): array
{
$client = new EntraClient($provider);
$token = $client->appToken();
$user = $client->graph($token)->get('/users/'.rawurlencode($userPrincipal), ['$select' => 'id,displayName,mail,userPrincipalName,accountEnabled']);
if ($user->status() === 404) {
throw new IdentityException('Diese Person gibt es in Entra ID nicht.');
}
$client->assertGraph($user);
$id = (string) $user->json('id');
$groups = $client->graphAll($token, '/users/'.$id.'/transitiveMemberOf/microsoft.graph.group?$select=id,displayName&$top=999');
$servicePrincipal = $client->graph($token)->get("/servicePrincipals(appId='".$client->clientId()."')", ['$select' => 'id,appRoles']);
$appRoles = [];
if ($servicePrincipal->successful()) {
$values = collect((array) $servicePrincipal->json('appRoles', []))->pluck('value', 'id');
$assignments = $client->graphAll($token, '/users/'.$id.'/appRoleAssignments?$top=999');
$groupIds = array_column($groups, 'id');
foreach ($assignments as $assignment) {
if (($assignment['resourceId'] ?? null) === $servicePrincipal->json('id') && $values->has($assignment['appRoleId'] ?? '')) {
$appRoles[] = $values[$assignment['appRoleId']];
}
}
// Über Gruppen zugewiesene App-Rollen
foreach ($client->graphAll($token, '/servicePrincipals/'.$servicePrincipal->json('id').'/appRoleAssignedTo?$top=999') as $assignment) {
if (($assignment['principalType'] ?? '') === 'Group' && in_array($assignment['principalId'], $groupIds, true) && $values->has($assignment['appRoleId'] ?? '')) {
$appRoles[] = $values[$assignment['appRoleId']];
}
}
}
$mappings = $provider->mappings()->with('role')->get();
$roleNames = fn (string $kind, string $external) => $mappings
->filter(fn (IdpGroupMapping $m) => $m->kind === $kind && strtolower($m->external_id) === strtolower($external))
->map(fn (IdpGroupMapping $m) => $m->role->name)->values()->all();
$groupRows = array_map(fn (array $g) => ['id' => $g['id'], 'name' => $g['displayName'] ?? $g['id'], 'roles' => $roleNames(IdpGroupMapping::GROUP, $g['id'])], $groups);
usort($groupRows, fn ($a, $b) => [empty($a['roles']), $a['name']] <=> [empty($b['roles']), $b['name']]);
$appRoleRows = array_map(fn (string $v) => ['value' => $v, 'roles' => $roleNames(IdpGroupMapping::APP_ROLE, $v)], array_values(array_unique($appRoles)));
$roles = collect($groupRows)->pluck('roles')->flatten()->merge(collect($appRoleRows)->pluck('roles')->flatten());
if ($default = $provider->setting('default_role_id')) {
$roles->push(Role::query()->find($default)?->name.' (Standardrolle)');
}
return [
'user' => [
'name' => $user->json('displayName'),
'email' => $user->json('mail') ?: $user->json('userPrincipalName'),
'enabled' => (bool) $user->json('accountEnabled', true),
],
'groups' => $groupRows,
'app_roles' => $appRoleRows,
'roles' => $roles->filter()->unique()->values()->all(),
];
}
/**
* Gruppensuche für das Mapping-Formular.
*
* @return array<string, string> Objekt-ID => Anzeigename
*/
public function searchGroups(IdentityProvider $provider, string $search): array
{
$client = new EntraClient($provider);
$response = $client->graph($client->appToken())
->withHeaders(['ConsistencyLevel' => 'eventual'])
->get('/groups', ['$search' => '"displayName:'.str_replace('"', '', $search).'"', '$select' => 'id,displayName', '$top' => 20]);
$client->assertGraph($response);
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;
}
}