Betreiber richtet Mandanten vollständig ein: Adressen, Sperrseite, Systemwerte

Ein neu angelegter Mandant war eine Sackgasse. Er bekam keine Website, also
keinen Host, also keine Adresse – und der Host wird im Mandanten-Admin
eingetragen, den er ohne Adresse nicht erreicht. „Im Admin öffnen" half
nicht: ohne Domain landete es beim Mandanten des aktuellen Hosts.

Einsprungsadressen gehören jetzt dem Betreiber, weil Webspace und Hosting
ihm gehören und ein Mandant nicht die Adresse eines anderen auf sich
zeigen lassen darf. Im Mandanten-Formular: Websites mit ihren Adressen.
Beim Anlegen entstehen Website, Host-Einträge und eine leere Startseite –
ohne Startseite antwortet die Website mit 404. Im Mandanten-Admin sind die
Adressen nur noch sichtbar, nicht änderbar. Die Domain beim Hoster auf das
Verzeichnis zu legen bleibt ein Schritt von Hand.

Gesperrter Mandant: statt 404 ein Hinweis mit Status 503, Text je Mandant
einstellbar. 503 hält die Seiten im Suchindex, weil die Sperre vorübergehend
ist.

Behoben: `URL::forceRootUrl(APP_URL)` zwang **alle** Links auf einen festen
Host. Mit einem Mandanten unsichtbar; mit zwei Domains hätte jeder interne
Link der zweiten Website auf die erste gezeigt. Der Ursprung ist jetzt der
Host der aufgelösten Website.

Neu: systemweite Einstellungen sind im Betreiber-Bereich änderbar
(Löschfristen, Bot-Schutz, Flutgrenze, Sicherungen, Portal-Fristen,
Versandweg, SMTP, harte Mail-Umleitung, Tokens). Leer heißt: der Wert der
.env gilt wieder – und zwar sofort, nicht erst beim nächsten Start.
Geheimnisse liegen verschlüsselt. Datenbank-Zugang und APP_KEY bleiben in
der .env, weil sie gebraucht werden, um die Datenbank zu öffnen und das
Gespeicherte zu entschlüsseln.

253 Feature-Tests grün.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Lars StommerandClaude Opus 5 committed 2026-10-24 10:20:18 +02:00
1 parent d9383cf3e5
commit 03ad4667ac
25 files changed
+997 -184

No files matched your search

@@ -10,6 +10,8 @@
* The service switches of the tenant form. They live in their own table, so the form state is read and
* written separately from the landlord's own columns. Only wired services are written – a switch for a
* service nothing asks about would promise something that does not happen.
*
* Holds no Filament hooks; EditsTenantSetup calls these.
*/
trait EditsTenantServices
{
@@ -17,7 +19,7 @@ trait EditsTenantServices
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeFill(array $data): array
private function fillServices(array $data): array
{
$tenant = $this->record;
@@ -40,35 +42,7 @@ protected function mutateFormDataBeforeFill(array $data): array
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeCreate(array $data): array
{
return $this->withoutServices($data);
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeSave(array $data): array
{
return $this->withoutServices($data);
}
protected function afterCreate(): void
{
$this->saveServices();
}
protected function afterSave(): void
{
$this->saveServices();
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function withoutServices(array $data): array
private function takeServices(array $data): array
{
$this->services = is_array($data['services'] ?? null) ? $data['services'] : [];
@@ -0,0 +1,58 @@
<?php
namespace App\Filament\Operator\Concerns;
/**
* Everything the operator sets up for a landlord that does not live in the tenants table itself:
* the websites with their entry addresses, and the services that are unlocked.
*/
trait EditsTenantSetup
{
use EditsTenantServices;
use EditsTenantWebsites;
/** @var array<string, array<string, mixed>> */
public array $services = [];
/** @var list<array<string, mixed>> */
public array $websites = [];
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeFill(array $data): array
{
return $this->fillWebsites($this->fillServices($data));
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeCreate(array $data): array
{
return $this->takeWebsites($this->takeServices($data));
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeSave(array $data): array
{
return $this->takeWebsites($this->takeServices($data));
}
protected function afterCreate(): void
{
$this->saveServices();
$this->saveWebsites();
}
protected function afterSave(): void
{
$this->saveServices();
$this->saveWebsites();
}
}
@@ -0,0 +1,182 @@
<?php
namespace App\Filament\Operator\Concerns;
use App\Models\Page;
use App\Models\Site;
use App\Models\SiteDomain;
use App\Models\Tenant;
use App\Tenancy\TenantContext;
use Illuminate\Validation\ValidationException;
/**
* The websites of a landlord and the addresses they answer on. These belong to the operator: the webspace
* and the hosting are the operator's, and a landlord must not be able to point an address at themselves.
*
* Wiring a new domain to this directory stays a manual step at the hoster. What is kept here is the other
* half: which host belongs to which website, and through it to which landlord.
*
* Holds no Filament hooks; EditsTenantSetup calls these.
*/
trait EditsTenantWebsites
{
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function fillWebsites(array $data): array
{
$tenant = $this->record;
if (! $tenant instanceof Tenant) {
return $data;
}
$data['websites'] = $tenant->sites()->withoutGlobalScope('tenant')->with('domains')->get()
->map(fn (Site $site): array => [
'id' => $site->id,
'name' => $site->name,
'hosts' => $site->domains->pluck('host')->all(),
])
->all();
return $data;
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function takeWebsites(array $data): array
{
$this->websites = is_array($data['websites'] ?? null) ? array_values($data['websites']) : [];
$this->normaliseWebsites();
unset($data['websites']);
return $data;
}
/**
* Cleans the entered addresses and refuses what already belongs elsewhere, before anything is written.
*/
private function normaliseWebsites(): void
{
$seen = [];
foreach ($this->websites as $index => $website) {
$hosts = [];
foreach ((array) ($website['hosts'] ?? []) as $host) {
$host = SiteDomain::normalise(is_string($host) ? $host : null);
if ($host === '') {
continue;
}
if (in_array($host, $seen, true)) {
throw ValidationException::withMessages([
'data.websites' => 'Die Adresse '.$host.' ist mehrfach eingetragen.',
]);
}
$seen[] = $host;
$hosts[] = $host;
}
$this->websites[$index]['hosts'] = $hosts;
}
$this->refuseForeignHosts($seen);
}
/**
* @param list<string> $hosts
*/
private function refuseForeignHosts(array $hosts): void
{
$ownIds = collect($this->websites)->pluck('id')->filter()->all();
$taken = SiteDomain::query()
->whereIn('host', $hosts)
->whereNotIn('site_id', $ownIds ?: [0])
->pluck('host');
if ($taken->isNotEmpty()) {
throw ValidationException::withMessages([
'data.websites' => 'Gehört bereits zu einer anderen Website: '.$taken->implode(', '),
]);
}
}
/**
* Writes the websites. A website that is new gets an empty home page straight away, because a website
* without one answers 404 and the landlord would have no way in.
*/
private function saveWebsites(): void
{
$tenant = $this->record;
if (! $tenant instanceof Tenant) {
return;
}
app(TenantContext::class)->run($tenant, function () use ($tenant): void {
$keep = [];
foreach ($this->websites as $website) {
$name = trim((string) ($website['name'] ?? ''));
if ($name === '') {
continue;
}
$hosts = (array) ($website['hosts'] ?? []);
$site = $this->siteFor($tenant, $website['id'] ?? null, $name, $hosts);
$keep[] = $site->id;
$site->domains()->whereNotIn('host', $hosts ?: [''])->delete();
foreach ($hosts as $host) {
SiteDomain::query()->updateOrCreate(['host' => $host], ['site_id' => $site->id]);
}
}
$tenant->sites()->whereNotIn('id', $keep ?: [0])->each(fn (Site $site) => $site->delete());
});
}
/**
* @param list<string> $hosts
*/
private function siteFor(Tenant $tenant, mixed $id, string $name, array $hosts): Site
{
$site = $id ? Site::query()->whereKey($id)->first() : null;
if ($site !== null) {
$site->update(['name' => $name, 'domain' => $hosts[0] ?? null]);
return $site;
}
$site = Site::query()->create([
'tenant_id' => $tenant->id,
'name' => $name,
'domain' => $hosts[0] ?? null,
'is_default' => $tenant->sites()->count() === 0,
'theme' => config('themes.base'),
]);
Page::query()->create([
'site_id' => $site->id,
'slug' => Page::HOME,
'title' => $name,
'sections' => [],
'is_published' => true,
]);
return $site;
}
}
@@ -0,0 +1,114 @@
<?php
namespace App\Filament\Operator\Pages;
use App\Support\SystemSettings;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\Actions;
use Filament\Schemas\Components\EmbeddedSchema;
use Filament\Schemas\Components\Form;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
/**
* The settings of the whole installation. They are the baseline every landlord is bound by, and a
* landlord's admin never reaches this page.
*
* Empty means: the value from the server's .env applies again. Database credentials and APP_KEY are not
* here and cannot be – they are needed to open the database and to decrypt what is stored in it.
*/
class SystemSettingsPage extends Page
{
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedAdjustmentsHorizontal;
protected static ?string $navigationLabel = 'Einstellungen';
protected static ?string $title = 'Systemweite Einstellungen';
protected static ?string $slug = 'einstellungen';
protected static ?int $navigationSort = 3;
/** @var array<string, mixed> */
public array $data = [];
public function mount(): void
{
$this->form->fill(collect(SystemSettings::EDITABLE)
->mapWithKeys(fn (array $definition, string $key): array => [self::field($key) => SystemSettings::get($key)])
->all());
}
public function form(Schema $schema): Schema
{
$sections = collect(SystemSettings::EDITABLE)
->groupBy(fn (array $definition): string => $definition[2], preserveKeys: true)
->map(fn ($group, string $section) => Section::make($section)
->columns(2)
->schema($group->keys()->map(fn (string $key) => $this->field_($key))->all()));
return $schema
->statePath('data')
->components([
Text::make('Leer lassen heißt: der Wert aus der .env des Servers gilt wieder. Datenbank-Zugang und APP_KEY stehen bewusst nicht hier – sie werden gebraucht, um die Datenbank überhaupt zu öffnen und das Gespeicherte zu entschlüsseln.'),
...$sections->values()->all(),
]);
}
public function content(Schema $schema): Schema
{
return $schema->components([
Form::make([EmbeddedSchema::make('form')])
->id('form')
->livewireSubmitHandler('save')
->footer([Actions::make([Action::make('save')->label('Speichern')->submit('save')])]),
]);
}
public function save(): void
{
$data = $this->form->getState();
SystemSettings::save(collect(SystemSettings::EDITABLE)
->mapWithKeys(fn (array $definition, string $key): array => [$key => $data[self::field($key)] ?? null])
->all());
Notification::make()->title('Gespeichert')->success()->send();
}
/**
* Config keys contain dots, which Filament would read as nesting.
*/
private static function field(string $key): string
{
return str_replace('.', '__', $key);
}
private function field_(string $key): TextInput|Select
{
[$label, $kind, , $help] = SystemSettings::EDITABLE[$key];
$name = self::field($key);
if ($kind === 'mailer') {
return Select::make($name)
->label($label)
->helperText($help)
->options(['smtp' => 'SMTP (echter Versand)', 'log' => 'Nur Logdatei (kein Versand)', 'array' => 'Verwerfen (nur für Tests)']);
}
$field = TextInput::make($name)->label($label)->helperText($help);
return match ($kind) {
'int' => $field->numeric()->integer()->minValue(0),
'secret' => $field->password()->revealable()->autocomplete(false),
default => $field,
};
}
}
+36 -3
View File
@@ -11,6 +11,10 @@
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\TagsInput;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
@@ -52,9 +56,38 @@ public static function form(Schema $schema): Schema
->unique(ignoreRecord: true)
->maxLength(255),
Toggle::make('is_active')
->label('Aktiv')
->helperText('Ein gesperrter Mandant ist von außen nicht mehr erreichbar. Der Betreiber kommt weiter hinein.')
->default(true),
->label('Zugang freigeschaltet')
->helperText('Ausgeschaltet sehen Besucher statt der Webseite nur den Hinweis unten. Der Betreiber kommt weiter hinein.')
->default(true)
->live(),
Textarea::make('suspended_message')
->label('Hinweis bei gesperrtem Zugang')
->placeholder('Diese Webseite ist zurzeit nicht erreichbar. Bitte versuchen Sie es später noch einmal.')
->helperText('Leer = der Standardtext. Wird mit Status 503 ausgeliefert, damit Suchmaschinen die Seite nicht aus dem Index werfen.')
->rows(2)
->columnSpanFull(),
Section::make('Einsprungsadressen')
->description('Unter welchen Adressen dieser Mandant antwortet. Die Adresse muss zusätzlich beim Hoster einmalig auf dieses Verzeichnis gelegt werden – das passiert nicht hier. Ab dem zweiten Mandanten bekommt jede nicht eingetragene Adresse eine Fehlerseite.')
->columnSpanFull()
->schema([
Repeater::make('websites')
->label('Websites')
->addActionLabel('Weitere Website')
->defaultItems(1)
->itemLabel(fn (array $state): ?string => $state['name'] ?? null)
->schema([
Hidden::make('id'),
TextInput::make('name')
->label('Name der Website')
->required()
->maxLength(120),
TagsInput::make('hosts')
->label('Adressen')
->placeholder('beispiel.de')
->helperText('Jede Schreibweise ist eine eigene Adresse: „www.beispiel.de“ und „beispiel.de“ sind zwei. Die erste gilt als Hauptadresse und steht in Links an Gäste.')
->nestedRecursiveRules(['string', 'max:190']),
]),
]),
Section::make('Dienste')
->description('Was dieser Mandant nutzen darf. Ein gesperrter Dienst verschwindet auch aus seinem Admin – die Rolle eines Benutzers kann das nicht aufwiegen.')
->columnSpanFull()
@@ -2,16 +2,13 @@
namespace App\Filament\Operator\Tenants\Pages;
use App\Filament\Operator\Concerns\EditsTenantServices;
use App\Filament\Operator\Concerns\EditsTenantSetup;
use App\Filament\Operator\TenantResource;
use Filament\Resources\Pages\CreateRecord;
class CreateTenant extends CreateRecord
{
use EditsTenantServices;
use EditsTenantSetup;
protected static string $resource = TenantResource::class;
/** @var array<string, array<string, mixed>> */
public array $services = [];
}
@@ -2,16 +2,13 @@
namespace App\Filament\Operator\Tenants\Pages;
use App\Filament\Operator\Concerns\EditsTenantServices;
use App\Filament\Operator\Concerns\EditsTenantSetup;
use App\Filament\Operator\TenantResource;
use Filament\Resources\Pages\EditRecord;
class EditTenant extends EditRecord
{
use EditsTenantServices;
use EditsTenantSetup;
protected static string $resource = TenantResource::class;
/** @var array<string, array<string, mixed>> */
public array $services = [];
}
@@ -3,13 +3,11 @@
namespace App\Filament\Resources\Sites\Concerns;
use App\Models\Site;
use App\Models\SiteDomain;
use Illuminate\Validation\ValidationException;
/**
* The further hostnames of a website. The field "Domain" stays the main address used for guest links;
* everything entered here answers as well. Needed as soon as there is a second landlord, because from
* then on an unknown host is a 404 and "www" is a host of its own.
* Shows the hostnames of a website in the landlord's admin. Read only: addresses are given out by the
* operator, because every address also has to be wired to this directory at the hoster, and because a
* landlord must not be able to point somebody else's address at their own website.
*/
trait EditsSiteHosts
{
@@ -25,112 +23,11 @@ protected function mutateFormDataBeforeFill(array $data): array
return $data;
}
$primary = SiteDomain::normalise($site->domain);
$data['extra_hosts'] = $site->domains()
->where('host', '!=', (string) $site->domain)
->pluck('host')
->reject(fn (string $host): bool => $host === $primary)
->values()
->all();
return $data;
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeCreate(array $data): array
{
return $this->withoutHosts($data);
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeSave(array $data): array
{
return $this->withoutHosts($data);
}
protected function afterCreate(): void
{
$this->saveHosts();
}
protected function afterSave(): void
{
$this->saveHosts();
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function withoutHosts(array $data): array
{
$hosts = is_array($data['extra_hosts'] ?? null) ? $data['extra_hosts'] : [];
$this->extraHosts = array_values(array_filter(array_map(
fn (mixed $host): string => SiteDomain::normalise(is_string($host) ? $host : null),
$hosts,
)));
$this->refuseForeignHosts();
unset($data['extra_hosts']);
return $data;
}
/**
* A hostname that already answers for another website must not be taken over – otherwise one landlord
* could pull another landlord's visitors onto their own site just by typing that address here.
*/
private function refuseForeignHosts(): void
{
$site = $this->record;
$taken = SiteDomain::query()
->whereIn('host', $this->extraHosts)
->when($site instanceof Site, fn ($query) => $query->where('site_id', '!=', $site->id))
->pluck('host');
if ($taken->isNotEmpty()) {
throw ValidationException::withMessages([
'data.extra_hosts' => 'Gehört bereits zu einer anderen Website: '.$taken->implode(', '),
]);
}
}
private function saveHosts(): void
{
$site = $this->record;
if (! $site instanceof Site) {
return;
}
$primary = SiteDomain::normalise($site->domain);
$wanted = collect($this->extraHosts)
->filter()
->when(filled($primary), fn ($hosts) => $hosts->push($primary))
->unique()
->values();
$site->domains()->whereNotIn('host', $wanted->all())->delete();
foreach ($wanted as $host) {
// Never take a host away from another website: that would hand one landlord's visitors to another.
$owner = SiteDomain::query()->where('host', $host)->value('site_id');
if ($owner !== null && $owner !== $site->id) {
continue;
}
SiteDomain::query()->updateOrCreate(['host' => $host], ['site_id' => $site->id]);
}
}
}
@@ -2,16 +2,10 @@
namespace App\Filament\Resources\Sites\Pages;
use App\Filament\Resources\Sites\Concerns\EditsSiteHosts;
use App\Filament\Resources\Sites\SiteResource;
use Filament\Resources\Pages\CreateRecord;
class CreateSite extends CreateRecord
{
use EditsSiteHosts;
protected static string $resource = SiteResource::class;
/** @var list<string> */
public array $extraHosts = [];
}
@@ -13,9 +13,6 @@ class EditSite extends EditRecord
protected static string $resource = SiteResource::class;
/** @var list<string> */
public array $extraHosts = [];
protected function getHeaderActions(): array
{
return [
@@ -28,15 +28,14 @@ public static function configure(Schema $schema): Schema
TextInput::make('name')->label('Name')->required()->maxLength(120),
TextInput::make('domain')
->label('Hauptadresse')
->placeholder('www.fewo-stommer.de')
->helperText('Steht in Links an Gäste. Leer = Standard-Website, solange es nur diesen Mandanten gibt. Ab dem zweiten Mandanten antwortet nur eine eingetragene Adresse, alles andere bekommt 404.')
->unique(ignoreRecord: true)
->maxLength(190),
->helperText('Steht in Links an Gäste. Adressen werden vom Betreiber vergeben, weil sie beim Hoster eingerichtet werden müssen.')
->disabled()
->dehydrated(false),
TagsInput::make('extra_hosts')
->label('Weitere Adressen')
->placeholder('stommer.info')
->helperText('Jede Schreibweise ist eine eigene Adresse: „www.beispiel.de“ und „beispiel.de“ sind zwei. Alle hier eingetragenen liefern dieselbe Website. Enter nach jeder Adresse.')
->nestedRecursiveRules(['string', 'max:190'])
->label('Antwortet außerdem auf')
->placeholder('keine weitere Adresse')
->disabled()
->dehydrated(false)
->columnSpanFull(),
Select::make('theme')
->label('Theme')