Phase 6 (Teil 2): OpenID Connect, LDAP/AD und SAML 2
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
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
- 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>
This commit is contained in:
parent
0ab0838050
commit
4fcc41ed30
172 changed files with 18940 additions and 293 deletions
|
|
@ -10,6 +10,9 @@ 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;
|
||||
|
|
@ -63,6 +66,33 @@ class IdentityProviderResource extends Resource
|
|||
}
|
||||
|
||||
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';
|
||||
|
||||
|
|
@ -96,17 +126,7 @@ class IdentityProviderResource extends Resource
|
|||
->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.'),
|
||||
]),
|
||||
static::accountsSection('Personen, die sich über Entra anmelden'),
|
||||
|
||||
Section::make('Profil')
|
||||
->key('profile')
|
||||
|
|
@ -214,6 +234,156 @@ class IdentityProviderResource extends Resource
|
|||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
|
|
@ -245,13 +415,15 @@ class IdentityProviderResource extends Resource
|
|||
return $table
|
||||
->columns([
|
||||
TextColumn::make('name')->label('Bezeichnung')->weight('medium'),
|
||||
TextColumn::make('type')->label('Typ')->formatStateUsing(fn () => 'Microsoft Entra ID'),
|
||||
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(),
|
||||
]);
|
||||
|
|
|
|||
|
|
@ -3,24 +3,45 @@
|
|||
namespace App\Filament\Resources\IdentityProviders\Pages;
|
||||
|
||||
use App\Filament\Resources\IdentityProviders\IdentityProviderResource;
|
||||
use App\Identity\IdentityDrivers;
|
||||
use App\Models\IdentityProvider;
|
||||
use App\Support\Audit;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
use Livewire\Attributes\Locked;
|
||||
|
||||
class CreateIdentityProvider extends CreateRecord
|
||||
{
|
||||
protected static string $resource = IdentityProviderResource::class;
|
||||
|
||||
/** Verfahren aus ?typ= – bestimmt das Formular. */
|
||||
#[Locked]
|
||||
public string $type = IdentityProvider::ENTRA;
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$type = (string) request()->query('typ', IdentityProvider::ENTRA);
|
||||
abort_unless(app(IdentityDrivers::class)->has($type), 404);
|
||||
$this->type = $type;
|
||||
|
||||
parent::mount();
|
||||
}
|
||||
|
||||
public function getTitle(): string
|
||||
{
|
||||
return app(IdentityDrivers::class)->get($this->type)->label().' anbinden';
|
||||
}
|
||||
|
||||
protected function mutateFormDataBeforeCreate(array $data): array
|
||||
{
|
||||
$data['type'] = IdentityProvider::ENTRA;
|
||||
$data['type'] = $this->type;
|
||||
$data['config']['attribute_map'] = array_values((array) ($data['config']['attribute_map'] ?? []));
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
protected function afterCreate(): void
|
||||
{
|
||||
Audit::log('identity.provider_created', ['provider' => $this->record->name]);
|
||||
Audit::log('identity.provider_created', ['provider' => $this->record->name, 'type' => $this->record->type]);
|
||||
}
|
||||
|
||||
protected function getRedirectUrl(): string
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
namespace App\Filament\Resources\IdentityProviders\Pages;
|
||||
|
||||
use App\Filament\Resources\IdentityProviders\IdentityProviderResource;
|
||||
use App\Models\IdentityProvider;
|
||||
use App\Support\Audit;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\DeleteAction;
|
||||
|
|
@ -18,7 +19,9 @@ class EditIdentityProvider extends EditRecord
|
|||
*/
|
||||
protected function mutateFormDataBeforeFill(array $data): array
|
||||
{
|
||||
$data['config']['client_secret'] = null;
|
||||
foreach ($this->secretFields() as $field) {
|
||||
$data['config'][$field] = null;
|
||||
}
|
||||
|
||||
// Ältere Konfiguration (feste Feldliste) als Zuordnung anzeigen.
|
||||
if (! is_array($data['config']['attribute_map'] ?? null)) {
|
||||
|
|
@ -35,18 +38,31 @@ class EditIdentityProvider extends EditRecord
|
|||
*/
|
||||
protected function mutateFormDataBeforeSave(array $data): array
|
||||
{
|
||||
if (blank($data['config']['client_secret'] ?? null)) {
|
||||
$data['config']['client_secret'] = $this->record->setting('client_secret');
|
||||
foreach ($this->secretFields() as $field) {
|
||||
if (blank($data['config'][$field] ?? null)) {
|
||||
$data['config'][$field] = $this->record->setting($field);
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->record->type === IdentityProvider::ENTRA) {
|
||||
// Geladene Erweiterungen liegen nur in der Datenbank, nicht im Formular.
|
||||
$data['config']['extension_properties'] = $this->record->fresh()?->setting('extension_properties', []) ?? [];
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
private function secretFields(): array
|
||||
{
|
||||
return $this->record->driver()?->secretFields() ?? ['client_secret', 'bind_password'];
|
||||
}
|
||||
|
||||
protected function afterSave(): void
|
||||
{
|
||||
Audit::log('identity.provider_updated', ['provider' => $this->record->name, 'enabled' => $this->record->enabled]);
|
||||
|
|
@ -56,8 +72,9 @@ class EditIdentityProvider extends EditRecord
|
|||
{
|
||||
return [
|
||||
Action::make('test')->label('Mapping testen')->icon(Heroicon::OutlinedBeaker)->color('gray')
|
||||
->visible($this->record->type === IdentityProvider::ENTRA)
|
||||
->url(fn () => IdentityProviderResource::getUrl('test', ['record' => $this->record])),
|
||||
DeleteAction::make()->modalDescription('Verknüpfungen und Rollen aus Entra-Gruppen werden entfernt. Die Konten selbst bleiben bestehen.'),
|
||||
DeleteAction::make()->modalDescription('Verknüpfungen und Rollen aus Gruppen dieses Anbieters werden entfernt. Die Konten selbst bleiben bestehen.'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,8 +3,11 @@
|
|||
namespace App\Filament\Resources\IdentityProviders\Pages;
|
||||
|
||||
use App\Filament\Resources\IdentityProviders\IdentityProviderResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use App\Identity\IdentityDrivers;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\ActionGroup;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
|
||||
class ListIdentityProviders extends ListRecords
|
||||
{
|
||||
|
|
@ -12,6 +15,14 @@ class ListIdentityProviders extends ListRecords
|
|||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [CreateAction::make()->label('Microsoft Entra ID anbinden')];
|
||||
$actions = collect(app(IdentityDrivers::class)->all())->map(fn ($driver, $type) => Action::make('create_'.$type)
|
||||
->label($driver->label())
|
||||
->tooltip($driver->description() ?: null)
|
||||
->url(IdentityProviderResource::getUrl('create', ['typ' => $type])))
|
||||
->values()->all();
|
||||
|
||||
return [
|
||||
ActionGroup::make($actions)->label('Anmeldeverfahren hinzufügen')->icon(Heroicon::OutlinedPlus)->button()->color('primary'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ namespace App\Filament\Resources\IdentityProviders\Pages;
|
|||
|
||||
use App\Filament\Resources\IdentityProviders\IdentityProviderResource;
|
||||
use App\Identity\Entra\MappingTester;
|
||||
use App\Models\IdentityProvider;
|
||||
use Filament\Resources\Pages\Concerns\InteractsWithRecord;
|
||||
use Filament\Resources\Pages\Page;
|
||||
use Throwable;
|
||||
|
|
@ -32,6 +33,7 @@ class TestMapping extends Page
|
|||
public function mount(int|string $record): void
|
||||
{
|
||||
$this->record = $this->resolveRecord($record);
|
||||
abort_unless($this->record->type === IdentityProvider::ENTRA, 404);
|
||||
}
|
||||
|
||||
public function test(MappingTester $tester): void
|
||||
|
|
|
|||
|
|
@ -46,8 +46,7 @@ class AppearanceController extends Controller
|
|||
{
|
||||
return Inertia::render('Auth/Login', [
|
||||
'canResetPassword' => true,
|
||||
'providers' => IdentityProvider::query()->where('enabled', true)->get()
|
||||
->map(fn (IdentityProvider $p) => ['slug' => $p->slug, 'type' => $p->type, 'label' => $p->buttonLabel()])->values(),
|
||||
'providers' => IdentityProvider::forLogin()->map->toLoginButton()->values(),
|
||||
'preview' => true,
|
||||
]);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,67 +3,63 @@
|
|||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Identity\Entra\EntraLogin;
|
||||
use App\Identity\IdentityDriver;
|
||||
use App\Identity\IdentityDrivers;
|
||||
use App\Identity\IdentityException;
|
||||
use App\Models\IdentityProvider;
|
||||
use App\Support\Audit;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* „Mit Microsoft anmelden“ – Weiterleitung und Rückkehr.
|
||||
* Anmeldung über einen Identity Provider – Weiterleitung, Rückkehr und (bei LDAP)
|
||||
* das eigene Anmeldeformular. Das Verfahren selbst steckt im Treiber.
|
||||
*/
|
||||
class IdentityLoginController extends Controller
|
||||
{
|
||||
public function redirect(IdentityProvider $provider, EntraLogin $login, Request $request): Response
|
||||
public function redirect(IdentityProvider $provider, Request $request): Response
|
||||
{
|
||||
abort_unless($provider->enabled && $provider->type === IdentityProvider::ENTRA, 404);
|
||||
|
||||
$start = $login->start($provider, $this->callbackUrl($provider));
|
||||
$request->session()->put('identity_login', $start['session']);
|
||||
|
||||
return redirect()->away($start['url']);
|
||||
return $this->driver($provider)->start($provider, $request);
|
||||
}
|
||||
|
||||
public function callback(IdentityProvider $provider, EntraLogin $login, Request $request): RedirectResponse
|
||||
public function callback(IdentityProvider $provider, Request $request): RedirectResponse
|
||||
{
|
||||
abort_unless($provider->enabled && $provider->type === IdentityProvider::ENTRA, 404);
|
||||
return $this->finish($provider, $request);
|
||||
}
|
||||
|
||||
$session = $request->session()->pull('identity_login');
|
||||
/**
|
||||
* Formular-Anmeldung (z. B. LDAP): Fehler zurück ins Formular statt zur Anmeldeseite.
|
||||
*/
|
||||
public function login(IdentityProvider $provider, Request $request): RedirectResponse
|
||||
{
|
||||
$request->validate(['username' => ['required', 'string', 'max:191'], 'password' => ['required', 'string', 'max:1000']]);
|
||||
|
||||
if ($request->filled('error')) {
|
||||
// z. B. Abbruch durch die Person oder fehlende Zustimmung in Entra
|
||||
Log::notice('Entra-Anmeldung abgebrochen: '.$request->string('error').' '.$request->string('error_description'));
|
||||
$key = 'identity-login:'.$provider->id.'|'.Str::transliterate(Str::lower((string) $request->input('username'))).'|'.$request->ip();
|
||||
|
||||
return $this->fail($request->string('error')->toString() === 'access_denied'
|
||||
? 'Die Anmeldung wurde abgebrochen.'
|
||||
: 'Microsoft hat die Anmeldung abgelehnt. Bitte wenden Sie sich an die Administration.');
|
||||
if (RateLimiter::tooManyAttempts($key, 5)) {
|
||||
return back()->withErrors(['username' => 'Zu viele Anmeldeversuche. Bitte in '.RateLimiter::availableIn($key).' Sekunden erneut versuchen.'])->onlyInput('username');
|
||||
}
|
||||
|
||||
if (! is_array($session) || ! hash_equals($session['state'] ?? '', (string) $request->query('state')) || ($session['provider'] ?? null) !== (string) $provider->id) {
|
||||
return $this->fail('Die Anmeldung ist abgelaufen. Bitte erneut versuchen.');
|
||||
RateLimiter::hit($key, 60);
|
||||
$response = $this->finish($provider, $request, inline: true);
|
||||
|
||||
if (Auth::check()) {
|
||||
RateLimiter::clear($key);
|
||||
}
|
||||
|
||||
try {
|
||||
$user = $login->complete($provider, (string) $request->query('code'), $this->callbackUrl($provider), $session);
|
||||
} catch (IdentityException $e) {
|
||||
return $this->fail($e->getMessage());
|
||||
} catch (Throwable $e) {
|
||||
report($e);
|
||||
return $response;
|
||||
}
|
||||
|
||||
return $this->fail('Die Anmeldung über Microsoft ist fehlgeschlagen. Bitte später erneut versuchen.');
|
||||
}
|
||||
public function metadata(IdentityProvider $provider): Response
|
||||
{
|
||||
$driver = app(IdentityDrivers::class)->get($provider->type);
|
||||
|
||||
Auth::login($user, remember: true);
|
||||
$request->session()->regenerate();
|
||||
$user->forceFill(['last_login_at' => now()])->saveQuietly();
|
||||
Audit::log('identity.login', ['provider' => $provider->name], $user->id);
|
||||
|
||||
return redirect()->intended('/');
|
||||
return $driver?->metadata($provider) ?? abort(404);
|
||||
}
|
||||
|
||||
public static function callbackUrlFor(IdentityProvider $provider): string
|
||||
|
|
@ -71,13 +67,41 @@ class IdentityLoginController extends Controller
|
|||
return url('/auth/'.$provider->slug.'/callback');
|
||||
}
|
||||
|
||||
private function callbackUrl(IdentityProvider $provider): string
|
||||
private function finish(IdentityProvider $provider, Request $request, bool $inline = false): RedirectResponse
|
||||
{
|
||||
return self::callbackUrlFor($provider);
|
||||
$driver = $this->driver($provider);
|
||||
|
||||
try {
|
||||
$user = $driver->complete($provider, $request);
|
||||
} catch (IdentityException $e) {
|
||||
return $this->fail($e->getMessage(), $inline);
|
||||
} catch (Throwable $e) {
|
||||
report($e);
|
||||
|
||||
return $this->fail('Die Anmeldung über „'.$provider->name.'“ ist fehlgeschlagen. Bitte später erneut versuchen.', $inline);
|
||||
}
|
||||
|
||||
$intended = $driver->intendedUrl($provider, $request);
|
||||
|
||||
Auth::login($user, remember: true);
|
||||
$request->session()->regenerate();
|
||||
$user->forceFill(['last_login_at' => now()])->saveQuietly();
|
||||
Audit::log('identity.login', ['provider' => $provider->name], $user->id);
|
||||
|
||||
return $intended ? redirect($intended) : redirect()->intended('/');
|
||||
}
|
||||
|
||||
private function fail(string $message): RedirectResponse
|
||||
private function driver(IdentityProvider $provider): IdentityDriver
|
||||
{
|
||||
return redirect('/login')->with('identity_error', $message);
|
||||
abort_unless($provider->enabled && ($driver = $provider->driver()) && $driver->unavailableReason() === null, 404);
|
||||
|
||||
return $driver;
|
||||
}
|
||||
|
||||
private function fail(string $message, bool $inline): RedirectResponse
|
||||
{
|
||||
return $inline
|
||||
? back()->withErrors(['username' => $message])->onlyInput('username')
|
||||
: redirect('/login')->with('identity_error', $message);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
112
app/Identity/AttributeProfile.php
Normal file
112
app/Identity/AttributeProfile.php
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
<?php
|
||||
|
||||
namespace App\Identity;
|
||||
|
||||
use App\Models\IdentityProvider;
|
||||
|
||||
/**
|
||||
* Baut aus den Attributen eines Anbieters (Claims, LDAP-Attribute, SAML-Attribute)
|
||||
* das normalisierte Profil – gemäß der Attribut-Zuordnung des Anbieters.
|
||||
*/
|
||||
final class AttributeProfile
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $attributes
|
||||
* @param array<string, string> $defaults Grundwerte (display_name, first_name, last_name, email) => Attribut
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function build(IdentityProvider $provider, array $attributes, array $defaults): array
|
||||
{
|
||||
$profile = [];
|
||||
|
||||
foreach ($defaults as $field => $attribute) {
|
||||
$profile[$field] = self::value($attributes, $attribute);
|
||||
}
|
||||
|
||||
foreach ($provider->attributeMap() as $target => $attribute) {
|
||||
$value = self::value($attributes, $attribute);
|
||||
|
||||
if (str_starts_with($target, 'custom.')) {
|
||||
$profile['custom'][substr($target, 7)] = $value;
|
||||
} else {
|
||||
$profile[$target] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $profile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wert eines Attributs als Text. Erst exakter Name (auch ohne Groß-/Kleinschreibung,
|
||||
* wie bei LDAP), dann Pfad mit Punkten für verschachtelte Claims. Listen werden mit
|
||||
* Komma verbunden.
|
||||
*
|
||||
* @param array<string, mixed> $attributes
|
||||
*/
|
||||
public static function value(array $attributes, string $name): ?string
|
||||
{
|
||||
$value = self::raw($attributes, $name);
|
||||
|
||||
if (is_array($value)) {
|
||||
$value = implode(', ', array_filter(array_map(fn ($v) => is_scalar($v) ? trim((string) $v) : null, $value), fn ($v) => $v !== null && $v !== ''));
|
||||
} elseif (is_bool($value)) {
|
||||
$value = $value ? 'ja' : 'nein';
|
||||
} elseif (! is_scalar($value)) {
|
||||
$value = null;
|
||||
}
|
||||
|
||||
$value = $value === null ? null : trim((string) $value);
|
||||
|
||||
return $value === '' || ($value !== null && ! mb_check_encoding($value, 'UTF-8')) ? null : $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Liste von Werten (z. B. Gruppen).
|
||||
*
|
||||
* @param array<string, mixed> $attributes
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function values(array $attributes, string $name): array
|
||||
{
|
||||
$value = self::raw($attributes, $name);
|
||||
$list = is_array($value) ? $value : ($value === null ? [] : [$value]);
|
||||
|
||||
return array_values(array_filter(array_map(fn ($v) => is_scalar($v) ? trim((string) $v) : '', $list), fn ($v) => $v !== ''));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $attributes
|
||||
*/
|
||||
public static function raw(array $attributes, string $name): mixed
|
||||
{
|
||||
if ($name === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (array_key_exists($name, $attributes)) {
|
||||
return $attributes[$name];
|
||||
}
|
||||
|
||||
foreach ($attributes as $key => $value) {
|
||||
if (is_string($key) && strcasecmp($key, $name) === 0) {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
|
||||
if (! str_contains($name, '.')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$value = $attributes;
|
||||
|
||||
foreach (explode('.', $name) as $segment) {
|
||||
if (! is_array($value) || ! array_key_exists($segment, $value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$value = $value[$segment];
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
114
app/Identity/Entra/EntraDriver.php
Normal file
114
app/Identity/Entra/EntraDriver.php
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
<?php
|
||||
|
||||
namespace App\Identity\Entra;
|
||||
|
||||
use App\Http\Controllers\Auth\IdentityLoginController;
|
||||
use App\Identity\IdentityDriver;
|
||||
use App\Identity\IdentityException;
|
||||
use App\Models\IdentityProvider;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* Microsoft Entra ID – OpenID Connect plus Microsoft Graph (Profil, Gruppen, Foto,
|
||||
* Hintergrund-Abgleich). Die Formularfelder stehen wegen ihres Umfangs direkt in
|
||||
* der Admin-Ressource.
|
||||
*/
|
||||
class EntraDriver extends IdentityDriver
|
||||
{
|
||||
public function __construct(private readonly EntraLogin $login) {}
|
||||
|
||||
public function type(): string
|
||||
{
|
||||
return IdentityProvider::ENTRA;
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Microsoft Entra ID';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Microsoft 365 / Azure AD mit Gruppen, App-Rollen, Profilfoto und Hintergrund-Abgleich.';
|
||||
}
|
||||
|
||||
public function defaultButtonLabel(IdentityProvider $provider): string
|
||||
{
|
||||
return 'Mit Microsoft anmelden';
|
||||
}
|
||||
|
||||
public function connectionSchema(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function secretFields(): array
|
||||
{
|
||||
return ['client_secret'];
|
||||
}
|
||||
|
||||
public function defaultAttributeMap(): array
|
||||
{
|
||||
return EntraAttributes::DEFAULT_MAP;
|
||||
}
|
||||
|
||||
public function attributePattern(): string
|
||||
{
|
||||
return EntraAttributes::PATH_PATTERN;
|
||||
}
|
||||
|
||||
public function attributeLabel(): string
|
||||
{
|
||||
return 'Graph-Attribut';
|
||||
}
|
||||
|
||||
public function supportsManager(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function supportsPhoto(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function supportsAppRoles(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function groupValueLabel(): string
|
||||
{
|
||||
return 'Objekt-ID der Gruppe';
|
||||
}
|
||||
|
||||
public function start(IdentityProvider $provider, Request $request): Response
|
||||
{
|
||||
$start = $this->login->start($provider, IdentityLoginController::callbackUrlFor($provider));
|
||||
$request->session()->put('identity_login', $start['session']);
|
||||
|
||||
return redirect()->away($start['url']);
|
||||
}
|
||||
|
||||
public function complete(IdentityProvider $provider, Request $request): User
|
||||
{
|
||||
$session = $request->session()->pull('identity_login');
|
||||
|
||||
if ($request->filled('error')) {
|
||||
// z. B. Abbruch durch die Person oder fehlende Zustimmung in Entra
|
||||
logger()->notice('Entra-Anmeldung abgebrochen: '.$request->string('error').' '.$request->string('error_description'));
|
||||
|
||||
throw new IdentityException($request->string('error')->toString() === 'access_denied'
|
||||
? 'Die Anmeldung wurde abgebrochen.'
|
||||
: 'Microsoft hat die Anmeldung abgelehnt. Bitte wenden Sie sich an die Administration.');
|
||||
}
|
||||
|
||||
if (! is_array($session) || ! hash_equals($session['state'] ?? '', (string) $request->query('state')) || ($session['provider'] ?? null) !== (string) $provider->id) {
|
||||
throw new IdentityException('Die Anmeldung ist abgelaufen. Bitte erneut versuchen.');
|
||||
}
|
||||
|
||||
return $this->login->complete($provider, (string) $request->query('code'), IdentityLoginController::callbackUrlFor($provider), $session);
|
||||
}
|
||||
}
|
||||
26
app/Identity/ExternalUser.php
Normal file
26
app/Identity/ExternalUser.php
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
<?php
|
||||
|
||||
namespace App\Identity;
|
||||
|
||||
/**
|
||||
* Eine beim Anbieter bestätigte Identität – so, wie sie der Kern weiterverarbeitet.
|
||||
*/
|
||||
final class ExternalUser
|
||||
{
|
||||
/**
|
||||
* @param string $subject dauerhafte, eindeutige Kennung beim Anbieter
|
||||
* @param array<string, mixed> $profile normalisiert (display_name, first_name, email, custom …), siehe AttributeProfile
|
||||
* @param list<string> $groups Gruppenwerte für die Rollen-Zuordnung
|
||||
* @param list<string> $appRoles
|
||||
* @param array<string, mixed> $attributes Rohdaten – für „Zuletzt empfangen“ im Admin
|
||||
* @param string|null|false $photo Binärdaten, null = kein Foto, false = unbekannt/nicht abgleichen
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $subject,
|
||||
public readonly array $profile,
|
||||
public readonly array $groups = [],
|
||||
public readonly array $appRoles = [],
|
||||
public readonly array $attributes = [],
|
||||
public readonly string|null|false $photo = false,
|
||||
) {}
|
||||
}
|
||||
167
app/Identity/IdentityDriver.php
Normal file
167
app/Identity/IdentityDriver.php
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
<?php
|
||||
|
||||
namespace App\Identity;
|
||||
|
||||
use App\Models\IdentityProvider;
|
||||
use App\Models\User;
|
||||
use Filament\Actions\Action;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* Ein Anmeldeverfahren (Entra ID, OpenID Connect, LDAP, SAML …). Plugins melden
|
||||
* weitere Verfahren über App\Identity\IdentityDrivers an.
|
||||
*
|
||||
* Ablauf: start() leitet zum Anbieter weiter oder zeigt ein eigenes Formular;
|
||||
* complete() wertet die Rückkehr aus. Die meisten Verfahren liefern dafür nur
|
||||
* authenticate() – Konto, Profil und Rollen übernimmt der Kern (IdentityLogin).
|
||||
*/
|
||||
abstract class IdentityDriver
|
||||
{
|
||||
/** Kürzel, wie es in identity_providers.type steht. */
|
||||
abstract public function type(): string;
|
||||
|
||||
/** z. B. „OpenID Connect“ */
|
||||
abstract public function label(): string;
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
public function defaultButtonLabel(IdentityProvider $provider): string
|
||||
{
|
||||
return 'Mit '.$provider->name.' anmelden';
|
||||
}
|
||||
|
||||
/**
|
||||
* Grund, warum das Verfahren auf diesem Server nicht nutzbar ist (z. B. fehlende
|
||||
* PHP-Erweiterung) – oder null.
|
||||
*/
|
||||
public function unavailableReason(): ?string
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filament-Felder für die Verbindung (Speicherort: config.*).
|
||||
*
|
||||
* @return list<mixed>
|
||||
*/
|
||||
abstract public function connectionSchema(): array;
|
||||
|
||||
/** Hinweistext über den Verbindungsfeldern (HTML erlaubt, bereits escaped). */
|
||||
public function connectionHelp(?IdentityProvider $provider): string
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Zusätzliche Aktionen am Verbindungsabschnitt im Admin (z. B. „Verbindung testen“).
|
||||
* Werden nur beim Bearbeiten angezeigt.
|
||||
*
|
||||
* @return list<Action>
|
||||
*/
|
||||
public function adminActions(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Konfigurationswerte, die nie ins Formular gelangen und beim Speichern mit
|
||||
* leerem Feld erhalten bleiben.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function secretFields(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Standardzuordnung Profilfeld => Attribut für neue Anbieter.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function defaultAttributeMap(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Vorschläge für die Attributauswahl: Attribut => Bezeichnung.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function attributeSuggestions(?IdentityProvider $provider): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/** Erlaubte Attributnamen – großzügig, weil SAML URIs und LDAP Bindestriche nutzt. */
|
||||
public function attributePattern(): string
|
||||
{
|
||||
return '/^[^\s<>"\'\\\\]{1,191}$/';
|
||||
}
|
||||
|
||||
public function attributeLabel(): string
|
||||
{
|
||||
return 'Attribut';
|
||||
}
|
||||
|
||||
public function supportsManager(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function supportsPhoto(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function supportsAppRoles(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Beschriftung für den Wert einer Gruppe in der Rollen-Zuordnung. */
|
||||
public function groupValueLabel(): string
|
||||
{
|
||||
return 'Gruppe (Wert wie übermittelt)';
|
||||
}
|
||||
|
||||
/** Anmeldung beginnen: Weiterleitung zum Anbieter oder eigenes Formular. */
|
||||
abstract public function start(IdentityProvider $provider, Request $request): Response;
|
||||
|
||||
/**
|
||||
* Rückkehr bzw. Formular auswerten und die angemeldete Person liefern.
|
||||
*
|
||||
* @throws IdentityException mit einer Meldung für die Person
|
||||
*/
|
||||
public function complete(IdentityProvider $provider, Request $request): User
|
||||
{
|
||||
return app(IdentityLogin::class)->finish($provider, $this->authenticate($provider, $request));
|
||||
}
|
||||
|
||||
/**
|
||||
* Identität beim Anbieter bestätigen.
|
||||
*
|
||||
* @throws IdentityException
|
||||
*/
|
||||
protected function authenticate(IdentityProvider $provider, Request $request): ExternalUser
|
||||
{
|
||||
throw new IdentityException('Dieses Anmeldeverfahren ist nicht vollständig eingerichtet.');
|
||||
}
|
||||
|
||||
/** Wohin es nach der Anmeldung geht (z. B. aus einem RelayState) – null = gemerkte Seite. */
|
||||
public function intendedUrl(IdentityProvider $provider, Request $request): ?string
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Zusätzliche öffentliche Antwort, z. B. SAML-Metadaten. */
|
||||
public function metadata(IdentityProvider $provider): ?Response
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
57
app/Identity/IdentityDrivers.php
Normal file
57
app/Identity/IdentityDrivers.php
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
<?php
|
||||
|
||||
namespace App\Identity;
|
||||
|
||||
use Illuminate\Contracts\Container\Container;
|
||||
|
||||
/**
|
||||
* Registry der Anmeldeverfahren. Der Kern bringt Entra ID mit, Plugins melden
|
||||
* weitere an: $drivers->add('oidc', OidcDriver::class).
|
||||
*/
|
||||
class IdentityDrivers
|
||||
{
|
||||
/** @var array<string, class-string<IdentityDriver>> */
|
||||
private array $classes = [];
|
||||
|
||||
/** @var array<string, IdentityDriver> */
|
||||
private array $instances = [];
|
||||
|
||||
public function __construct(private readonly Container $container) {}
|
||||
|
||||
/**
|
||||
* @param class-string<IdentityDriver> $class
|
||||
*/
|
||||
public function add(string $type, string $class): void
|
||||
{
|
||||
$this->classes[$type] = $class;
|
||||
unset($this->instances[$type]);
|
||||
}
|
||||
|
||||
public function has(string $type): bool
|
||||
{
|
||||
return isset($this->classes[$type]);
|
||||
}
|
||||
|
||||
public function get(string $type): ?IdentityDriver
|
||||
{
|
||||
if (! isset($this->classes[$type])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->instances[$type] ??= $this->container->make($this->classes[$type]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, IdentityDriver>
|
||||
*/
|
||||
public function all(): array
|
||||
{
|
||||
$all = [];
|
||||
|
||||
foreach (array_keys($this->classes) as $type) {
|
||||
$all[$type] = $this->get($type);
|
||||
}
|
||||
|
||||
return $all;
|
||||
}
|
||||
}
|
||||
86
app/Identity/IdentityLogin.php
Normal file
86
app/Identity/IdentityLogin.php
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
<?php
|
||||
|
||||
namespace App\Identity;
|
||||
|
||||
use App\Models\IdentityProvider;
|
||||
use App\Models\User;
|
||||
use App\Models\UserIdentity;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
/**
|
||||
* Gemeinsamer Abschluss jeder Anmeldung über einen Anbieter: Konto finden oder
|
||||
* anlegen, Profil, Rollen und Foto übernehmen.
|
||||
*/
|
||||
class IdentityLogin
|
||||
{
|
||||
public const LAST_SEEN_TTL = 60 * 60 * 24 * 14;
|
||||
|
||||
public function __construct(private readonly IdentitySync $sync) {}
|
||||
|
||||
public function finish(IdentityProvider $provider, ExternalUser $external): User
|
||||
{
|
||||
self::remember($provider, $external);
|
||||
|
||||
$user = $this->sync->resolveUser($provider, $external->subject, $external->profile, (bool) $provider->setting('auto_provision', true));
|
||||
|
||||
if (! $user) {
|
||||
throw new IdentityException('Für Ihr Konto bei „'.$provider->name.'“ gibt es kein Konto in diesem Portal. Bitte wenden Sie sich an die Administration.');
|
||||
}
|
||||
|
||||
if (! $user->is_active) {
|
||||
throw new IdentityException('Ihr Konto ist deaktiviert. Bitte wenden Sie sich an die Administration.');
|
||||
}
|
||||
|
||||
$identity = UserIdentity::query()->where('identity_provider_id', $provider->id)->where('subject', $external->subject)->firstOrFail();
|
||||
$identity->update(['last_login_at' => now(), 'email' => $external->profile['email'] ?? $identity->email]);
|
||||
|
||||
$this->sync->syncProfile($provider, $user, $external->profile);
|
||||
$this->sync->syncRoles($provider, $user, $external->groups, $external->appRoles);
|
||||
|
||||
if ($external->photo !== false && $provider->setting('sync_photo', false)) {
|
||||
$this->sync->syncPhoto($identity->fresh('user'), $external->photo);
|
||||
}
|
||||
|
||||
return $user->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* Zuletzt empfangene Angaben für die Administration (Hilfe bei der Zuordnung).
|
||||
*/
|
||||
public static function remember(IdentityProvider $provider, ExternalUser $external): void
|
||||
{
|
||||
$attributes = [];
|
||||
|
||||
foreach ($external->attributes as $key => $value) {
|
||||
if (count($attributes) >= 80) {
|
||||
break;
|
||||
}
|
||||
|
||||
$text = is_array($value) && ! array_is_list($value)
|
||||
? (string) json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
|
||||
: (is_array($value)
|
||||
? implode(', ', array_slice(array_map(fn ($v) => is_scalar($v) ? (string) $v : json_encode($v), $value), 0, 20))
|
||||
: (is_scalar($value) || $value === null ? (string) $value : json_encode($value)));
|
||||
|
||||
// Binärwerte (Fotos, GUIDs) nicht speichern.
|
||||
$attributes[(string) $key] = mb_check_encoding($text, 'UTF-8') ? mb_strimwidth($text, 0, 300, '…') : '(Binärdaten)';
|
||||
}
|
||||
|
||||
Cache::put('identity.last_seen.'.$provider->id, [
|
||||
'at' => now()->timestamp,
|
||||
'subject' => $external->subject,
|
||||
'attributes' => $attributes,
|
||||
'groups' => array_slice($external->groups, 0, 100),
|
||||
], self::LAST_SEEN_TTL);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{at: int, subject: string, attributes: array<string, string>, groups: list<string>}|null
|
||||
*/
|
||||
public static function lastSeen(IdentityProvider $provider): ?array
|
||||
{
|
||||
$value = Cache::get('identity.last_seen.'.$provider->id);
|
||||
|
||||
return is_array($value) ? $value : null;
|
||||
}
|
||||
}
|
||||
|
|
@ -57,7 +57,7 @@ class IdentitySync
|
|||
}
|
||||
|
||||
if (! $email) {
|
||||
throw new IdentityException('Für dieses Microsoft-Konto ist keine E-Mail-Adresse hinterlegt.');
|
||||
throw new IdentityException('Für Ihr Konto ist beim Anmeldedienst keine E-Mail-Adresse hinterlegt.');
|
||||
}
|
||||
|
||||
$user = User::query()->create([
|
||||
|
|
|
|||
|
|
@ -3,15 +3,21 @@
|
|||
namespace App\Models;
|
||||
|
||||
use App\Identity\Entra\EntraAttributes;
|
||||
use App\Identity\IdentityDriver;
|
||||
use App\Identity\IdentityDrivers;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Ein angebundener Identity Provider (zunächst Microsoft Entra ID).
|
||||
* Ein angebundener Identity Provider. Das Verfahren (type) liefert ein Treiber aus
|
||||
* App\Identity\IdentityDrivers – Entra ID im Kern, OpenID Connect, LDAP und SAML als Plugins.
|
||||
*
|
||||
* config (verschlüsselt): tenant_id, client_id, client_secret, button_label,
|
||||
* config (verschlüsselt), gemeinsam: button_label, auto_provision, link_by_email,
|
||||
* allowed_domains, default_role_id, attribute_map, sync_manager, sync_photo;
|
||||
* übrige Schlüssel je Verfahren. Entra: tenant_id, client_id, client_secret, button_label,
|
||||
* auto_provision, link_by_email, allowed_domains, default_role_id,
|
||||
* attribute_map (Liste aus target + attribute), sync_manager, sync_photo,
|
||||
* extension_properties, directory_sync, directory_create_users
|
||||
|
|
@ -50,6 +56,31 @@ class IdentityProvider extends Model
|
|||
];
|
||||
}
|
||||
|
||||
public function driver(): ?IdentityDriver
|
||||
{
|
||||
return app(IdentityDrivers::class)->get((string) $this->type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Aktive Anbieter, deren Verfahren verfügbar ist – für die Anmeldeseite.
|
||||
*
|
||||
* @return Collection<int, IdentityProvider>
|
||||
*/
|
||||
public static function forLogin(): Collection
|
||||
{
|
||||
return static::query()->where('enabled', true)->orderBy('name')->get()
|
||||
->filter(fn (IdentityProvider $p) => $p->driver()?->unavailableReason() === null && $p->driver() !== null)
|
||||
->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{slug: string, label: string, type: string}
|
||||
*/
|
||||
public function toLoginButton(): array
|
||||
{
|
||||
return ['slug' => $this->slug, 'label' => $this->buttonLabel(), 'type' => $this->type];
|
||||
}
|
||||
|
||||
public function setting(string $key, mixed $default = null): mixed
|
||||
{
|
||||
return data_get($this->config, $key, $default);
|
||||
|
|
@ -66,6 +97,10 @@ class IdentityProvider extends Model
|
|||
{
|
||||
$rows = $this->setting('attribute_map');
|
||||
|
||||
if (! is_array($rows) && $this->type !== self::ENTRA) {
|
||||
return $this->driver()?->defaultAttributeMap() ?? [];
|
||||
}
|
||||
|
||||
if (! is_array($rows)) {
|
||||
$legacy = (array) $this->setting('synced_fields', array_keys(EntraAttributes::DEFAULT_MAP));
|
||||
|
||||
|
|
@ -73,12 +108,13 @@ class IdentityProvider extends Model
|
|||
}
|
||||
|
||||
$map = [];
|
||||
$pattern = $this->driver()?->attributePattern() ?? EntraAttributes::PATH_PATTERN;
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$target = (string) ($row['target'] ?? '');
|
||||
$attribute = trim((string) ($row['attribute'] ?? ''));
|
||||
|
||||
if ($attribute !== '' && preg_match(EntraAttributes::PATH_PATTERN, $attribute)
|
||||
if ($attribute !== '' && preg_match($pattern, $attribute)
|
||||
&& (array_key_exists($target, self::PROFILE_TARGETS) || str_starts_with($target, 'custom.'))) {
|
||||
$map[$target] = $attribute;
|
||||
}
|
||||
|
|
@ -89,6 +125,10 @@ class IdentityProvider extends Model
|
|||
|
||||
public function syncsManager(): bool
|
||||
{
|
||||
if ($this->type !== self::ENTRA) {
|
||||
return (bool) $this->setting('sync_manager', false) && (bool) $this->driver()?->supportsManager();
|
||||
}
|
||||
|
||||
return (bool) $this->setting('sync_manager', in_array('manager', (array) $this->setting('synced_fields', ['manager']), true));
|
||||
}
|
||||
|
||||
|
|
@ -104,7 +144,7 @@ class IdentityProvider extends Model
|
|||
|
||||
public function buttonLabel(): string
|
||||
{
|
||||
return $this->setting('button_label') ?: 'Mit Microsoft anmelden';
|
||||
return $this->setting('button_label') ?: ($this->driver()?->defaultButtonLabel($this) ?? 'Mit '.$this->name.' anmelden');
|
||||
}
|
||||
|
||||
public function isEmailDomainAllowed(?string $email): bool
|
||||
|
|
|
|||
|
|
@ -5,6 +5,9 @@ namespace App\Providers;
|
|||
use App\Dashboard\CoreWidgets;
|
||||
use App\Dashboard\Widgets;
|
||||
use App\Editorial\Editorial;
|
||||
use App\Identity\Entra\EntraDriver;
|
||||
use App\Identity\IdentityDrivers;
|
||||
use App\Models\IdentityProvider;
|
||||
use App\Models\User;
|
||||
use App\Pagebuilder\Blocks;
|
||||
use App\Support\Abilities;
|
||||
|
|
@ -55,6 +58,12 @@ class AppServiceProvider extends ServiceProvider
|
|||
$this->app->singleton(Permissions::class);
|
||||
$this->app->singleton(ProfileFields::class);
|
||||
$this->app->singleton(Blocks::class);
|
||||
$this->app->singleton(IdentityDrivers::class, function ($app) {
|
||||
$drivers = new IdentityDrivers($app);
|
||||
$drivers->add(IdentityProvider::ENTRA, EntraDriver::class);
|
||||
|
||||
return $drivers;
|
||||
});
|
||||
$this->app->singleton(Editorial::class);
|
||||
$this->app->singleton(BackgroundTasks::class);
|
||||
$this->app->singleton(InstalledVersion::class);
|
||||
|
|
|
|||
|
|
@ -26,8 +26,7 @@ class FortifyServiceProvider extends ServiceProvider
|
|||
|
||||
Fortify::loginView(fn (Request $request) => Inertia::render('Auth/Login', [
|
||||
'canResetPassword' => true,
|
||||
'providers' => IdentityProvider::query()->where('enabled', true)->orderBy('name')->get()
|
||||
->map(fn (IdentityProvider $p) => ['slug' => $p->slug, 'label' => $p->buttonLabel(), 'type' => $p->type])->values(),
|
||||
'providers' => IdentityProvider::forLogin()->map->toLoginButton()->values(),
|
||||
'identityError' => $request->session()->get('identity_error'),
|
||||
'status' => $request->boolean('eingerichtet')
|
||||
? 'Die Einrichtung ist abgeschlossen. Sie können sich jetzt mit Ihrem Administratorkonto anmelden.'
|
||||
|
|
|
|||
|
|
@ -9,5 +9,5 @@ namespace App;
|
|||
*/
|
||||
final class Version
|
||||
{
|
||||
public const VERSION = '0.8.0';
|
||||
public const VERSION = '0.9.0';
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue