presseportale/resources/views/livewire/admin/users/create.blade.php
Kevin Adametz 77f8f9cb35 security: Rechteausweitung schließen & Admin-Panel feingranular gaten (K1, H1, H2, M8)
- users:manage/roles:manage auf allen User-/Rollen-Masken erzwungen;
  is_super_admin aus $fillable entfernt und nur per autorisiertem
  forceFill setzbar; zentraler Gate::before-Super-Admin-Kurzschluss (K1/M8).
- Nicht-Super-Admins können Super-Admin-Konten nicht mehr bearbeiten (Fix#2);
  Impersonation mit Rangprüfung, keine Token-Erstellung während Impersonation (H1).
- Destruktive/verwaltende Admin-Aktionen (CRM/Billing/Compliance/Struktur)
  hängen an neuen admin-only Permissions; Editor behält reine Content-Rechte (H2).
- Kanonischer Permission-Katalog (App\Authorization\Permission) als Single
  Source of Truth für Seeder und Monitoring.

Deployment: `php artisan db:seed --class=RolesAndPermissionsSeeder` auf allen
Umgebungen ausführen (neue Permissions).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-14 13:48:50 +00:00

378 lines
14 KiB
PHP

<?php
use App\Enums\Portal;
use App\Enums\RegistrationType;
use App\Models\Company;
use App\Models\User;
use App\Services\Admin\AdminPerformanceCache;
use Illuminate\Database\Eloquent\Collection;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Volt\Component;
use Spatie\Permission\Models\Role;
new #[Layout('components.layouts.app'), Title('Benutzer anlegen')] class extends Component
{
use \App\Livewire\Concerns\HasFullTextSearch;
use \App\Livewire\Concerns\ProvidesUserFormRules;
public string $name = '';
public string $agencyName = '';
public string $email = '';
public string $portal = '';
public string $registrationType = '';
public string $language = 'de';
public bool $isActive = true;
public bool $isSuperAdmin = false;
/** @var array<int, string> */
public array $selectedRoles = [];
/** @var array<int, int> */
public array $linkedCompanyIds = [];
/** @var array<int, string> */
public array $companyRoles = [];
public string $companyLookup = '';
public ?int $selectedLookupCompanyId = null;
/**
* @var array{
* salutation_key:?string,
* title:?string,
* name:?string,
* address1:?string,
* address2:?string,
* postal_code:?string,
* city:?string,
* country_code:?string
* }
*/
public array $billing = [
'salutation_key' => null,
'title' => null,
'name' => null,
'address1' => null,
'address2' => null,
'postal_code' => null,
'city' => null,
'country_code' => null,
];
public function mount(): void
{
$this->authorize('users:manage');
$this->portal = Portal::Both->value;
$this->registrationType = RegistrationType::ExistingLegacy->value;
}
public function updatedSelectedLookupCompanyId(): void
{
if ($this->selectedLookupCompanyId) {
$this->addLinkedCompany();
}
}
public function addLinkedCompany(): void
{
if (! $this->selectedLookupCompanyId) {
return;
}
$this->linkedCompanyIds = array_map('intval', $this->linkedCompanyIds);
if (! in_array($this->selectedLookupCompanyId, $this->linkedCompanyIds, true)) {
$this->linkedCompanyIds[] = $this->selectedLookupCompanyId;
}
$this->companyRoles[$this->selectedLookupCompanyId] ??= 'member';
$this->companyLookup = '';
$this->selectedLookupCompanyId = null;
}
public function removeLinkedCompany(int $companyId): void
{
$this->linkedCompanyIds = array_values(array_filter(
$this->linkedCompanyIds,
fn (int|string $id): bool => (int) $id !== $companyId
));
unset($this->companyRoles[$companyId]);
}
public function save(): void
{
$this->authorize('users:manage');
$validated = $this->validate([
...$this->userIdentityRules(),
...$this->userRolesAndCompaniesRules(),
...$this->userBillingRules(),
]);
$user = User::query()->create([
'name' => $validated['name'],
'agency_name' => $validated['agencyName'] ?: null,
'email' => $validated['email'],
'portal' => $validated['portal'],
'registration_type' => $validated['registrationType'],
'language' => $validated['language'],
'is_active' => $this->isActive,
'password' => null,
]);
// Super-Admin-Rang darf nur ein Super-Admin vergeben (is_super_admin ist
// nicht mass-assignable, siehe User::$fillable).
if ($this->isSuperAdmin && auth()->user()->is_super_admin) {
$user->forceFill(['is_super_admin' => true])->save();
}
$user->syncRoles($validated['selectedRoles']);
$user->syncCompaniesWithRoles($validated['linkedCompanyIds'], $validated['companyRoles']);
if ($this->billingIsComplete()) {
$user->billingAddress()->create([
'salutation_key' => $validated['billing']['salutation_key'] ?: null,
'title' => $validated['billing']['title'] ?: null,
'name' => (string) $validated['billing']['name'],
'address1' => (string) $validated['billing']['address1'],
'address2' => $validated['billing']['address2'] ?: null,
'postal_code' => (string) $validated['billing']['postal_code'],
'city' => (string) $validated['billing']['city'],
'country_code' => strtoupper((string) $validated['billing']['country_code']),
]);
}
session()->flash('success', __('Benutzer wurde angelegt und verknuepft.'));
$this->redirect(route('admin.users.edit', $user->id), navigate: true);
}
public function with(): array
{
$companyLookupResults = collect();
$companyLookupTerm = trim($this->companyLookup);
if (mb_strlen($companyLookupTerm) >= 1) {
$companyLookupResults = Company::withoutGlobalScopes()
->whereNotIn('id', $this->linkedCompanyIds ?: [-1])
->where(function ($query) use ($companyLookupTerm): void {
if ($this->supportsFullTextSearch($companyLookupTerm)) {
$query->whereFullText(['name', 'email', 'slug'], $companyLookupTerm);
return;
}
$query
->where('name', 'like', '%'.$companyLookupTerm.'%')
->orWhere('slug', 'like', '%'.$companyLookupTerm.'%')
->orWhere('email', 'like', '%'.$companyLookupTerm.'%');
})
->orderBy('name')
->limit(50)
->get(['id', 'name', 'slug', 'email']);
}
return [
'availableRoles' => $this->availableRoles(),
'linkedCompanies' => Company::withoutGlobalScopes()
->whereIn('id', $this->linkedCompanyIds ?: [-1])
->orderBy('name')
->get(['id', 'name', 'slug', 'email']),
'companyLookupResults' => $companyLookupResults,
'salutations' => config('salutations.items', []),
'countries' => config('countries.items', []),
'portalOptions' => Portal::cases(),
'registrationTypeOptions' => RegistrationType::cases(),
];
}
private function availableRoles(): Collection
{
return app(AdminPerformanceCache::class)->remember(AdminPerformanceCache::RoleOptions, AdminPerformanceCache::OptionsTtl, fn () => Role::query()
->orderBy('name')
->get(['id', 'name']));
}
protected function billingIsComplete(): bool
{
return filled($this->billing['name'])
&& filled($this->billing['address1'])
&& filled($this->billing['postal_code'])
&& filled($this->billing['city'])
&& filled($this->billing['country_code']);
}
}; ?>
<form wire:submit="save" class="space-y-8">
{{-- ============== PAGE HEADER ============== --}}
<x-portal.page-header
:badge="__('Admin Backend')"
:eyebrow="__('Administration · Benutzer · Neu')"
:title="__('Benutzer anlegen')"
:description="__('Rollen, Firmen und optional Rechnungsadresse direkt mitsetzen.')"
>
<x-slot:actions>
<flux:button variant="filled" icon="arrow-left" href="{{ route('admin.users.index') }}" wire:navigate>
{{ __('Zurück') }}
</flux:button>
</x-slot:actions>
</x-portal.page-header>
<article class="panel">
<div class="panel-head">
<span class="section-eyebrow">{{ __('Basisdaten') }}</span>
</div>
<div class="p-5">
<div class="grid gap-4 sm:grid-cols-2">
<flux:field>
<flux:label>{{ __('Name') }}</flux:label>
<flux:input wire:model="name" />
<flux:error name="name" />
</flux:field>
<flux:field>
<flux:label>{{ __('E-Mail') }}</flux:label>
<flux:input wire:model="email" type="email" />
<flux:error name="email" />
</flux:field>
<flux:field class="sm:col-span-2">
<flux:label>{{ __('Agentur-/Verteilername') }}</flux:label>
<flux:input wire:model="agencyName" />
<flux:description>{{ __('Erscheint öffentlich als Übermittler („übermittelt von …") unter den Mitteilungen dieses Accounts.') }}</flux:description>
<flux:error name="agencyName" />
</flux:field>
<flux:field>
<flux:label>{{ __('Portal') }}</flux:label>
<flux:select wire:model="portal">
@foreach($portalOptions as $portalOption)
<option value="{{ $portalOption->value }}">{{ $portalOption->label() }}</option>
@endforeach
</flux:select>
<flux:error name="portal" />
</flux:field>
<flux:field>
<flux:label>{{ __('Registrierungstyp') }}</flux:label>
<flux:select wire:model="registrationType">
@foreach($registrationTypeOptions as $registrationTypeOption)
<option value="{{ $registrationTypeOption->value }}">{{ $registrationTypeOption->label() }}</option>
@endforeach
</flux:select>
<flux:error name="registrationType" />
</flux:field>
</div>
<div class="mt-4 flex flex-wrap gap-6">
<flux:checkbox wire:model="isActive" label="{{ __('Aktiv') }}" />
<flux:checkbox wire:model="isSuperAdmin" label="{{ __('Super Admin') }}" />
</div>
</div>
</article>
<article class="panel">
<div class="panel-head">
<span class="section-eyebrow">{{ __('Rollenzuweisung') }}</span>
</div>
<div class="p-5">
<x-portal.user-role-fields :roles="$availableRoles" />
</div>
</article>
<article class="panel">
<div class="panel-head">
<span class="section-eyebrow">{{ __('Firmenverknüpfung') }}</span>
</div>
<div class="p-5">
<div class="mb-4">
<flux:select
wire:model.live="selectedLookupCompanyId"
variant="combobox"
:filter="false"
placeholder="{{ __('Firma suchen und hinzufügen…') }}"
>
<x-slot name="input">
<flux:select.input
wire:model.live.debounce.300ms="companyLookup"
placeholder="{{ __('Name, Slug oder E-Mail…') }}"
/>
</x-slot>
@foreach($companyLookupResults as $company)
<flux:select.option :value="$company->id" wire:key="create-company-{{ $company->id }}">
{{ $company->name }}@if($company->email)<span class="ml-1 text-zinc-400">· {{ $company->email }}</span>@endif
</flux:select.option>
@endforeach
<x-slot name="empty">
<flux:select.option.empty>
@if(blank(trim($companyLookup)))
{{ __('Mindestens 1 Zeichen eingeben…') }}
@else
{{ __('Keine Firma gefunden.') }}
@endif
</flux:select.option.empty>
</x-slot>
</flux:select>
</div>
<div class="space-y-3">
@forelse ($linkedCompanies as $company)
<div class="grid gap-3 rounded-[5px] border border-[color:var(--color-bg-rule)] bg-[color:var(--color-bg-elev)] p-3 sm:grid-cols-[1fr,160px,auto] sm:items-center">
<div>
<div class="text-[13px] font-semibold text-[color:var(--color-ink)]">{{ $company->name }}</div>
<div class="text-[11px] text-[color:var(--color-ink-3)] font-mono">{{ $company->slug }}</div>
</div>
<flux:select wire:model="companyRoles.{{ $company->id }}">
<option value="member">{{ __('Member') }}</option>
<option value="responsible">{{ __('Responsible') }}</option>
<option value="owner">{{ __('Owner') }}</option>
</flux:select>
<flux:button size="sm" variant="filled" icon="x-mark"
wire:click="removeLinkedCompany({{ $company->id }})">
{{ __('Entfernen') }}
</flux:button>
</div>
@empty
<p class="text-[12.5px] text-[color:var(--color-ink-3)] m-0">{{ __('Noch keine Firma verknüpft.') }}</p>
@endforelse
</div>
</div>
</article>
<article class="panel">
<div class="panel-head">
<span class="section-eyebrow">{{ __('Rechnungsadresse (optional)') }}</span>
</div>
<div class="p-5">
<x-portal.user-billing-fields :salutations="$salutations" :countries="$countries" />
</div>
</article>
<article class="panel">
<div class="p-5 flex justify-end gap-3">
<flux:button variant="filled" href="{{ route('admin.users.index') }}" wire:navigate>
{{ __('Abbrechen') }}
</flux:button>
<flux:button type="submit" variant="primary" icon="check">
{{ __('Benutzer anlegen') }}
</flux:button>
</div>
</article>
</form>