Admin two-factor authentication (mandatory for admins), users:create command, operations handbook

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lars StommerandClaude Opus 5.5 committed 2026-10-22 16:52:44 +02:00
1 parent dea1029225
commit 13760f2c02
11 files changed
+353 -3

No files matched your search

+1
View File
@@ -13,6 +13,7 @@ # Ferienwohnung Stommer
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts.
- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal booking e-mails are a fast path (`app/Channels/Mail`, `ProcessPortalMail`): they create blocks with source `email`, which `SyncChannel` later confirms/replaces and never removes as stale. Portal analysis: `docs/PORTALE.md`.
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for admins via `RequireTwoFactorForAdmins`.
- Deployment: `scripts/deploy.sh <env> setup|deploy|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
- Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR).
- PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there).
+1
View File
@@ -13,6 +13,7 @@ # Ferienwohnung Stommer
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts.
- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal booking e-mails are a fast path (`app/Channels/Mail`, `ProcessPortalMail`): they create blocks with source `email`, which `SyncChannel` later confirms/replaces and never removes as stale. Portal analysis: `docs/PORTALE.md`.
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for admins via `RequireTwoFactorForAdmins`.
- Deployment: `scripts/deploy.sh <env> setup|deploy|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
- Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR).
- PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there).
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace App\Console\Commands;
use App\Enums\UserRole;
use App\Models\User;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Validation\Rules\Password;
use function Laravel\Prompts\password;
use function Laravel\Prompts\select;
use function Laravel\Prompts\text;
#[Signature('users:create {email? : E-Mail-Adresse} {--name= : Name} {--role= : admin, rentals oder content}')]
#[Description('Create an admin panel account (the password is entered interactively and never passed as an argument)')]
class CreateUser extends Command
{
/**
* Execute the console command.
*/
public function handle(): int
{
$email = $this->argument('email') ?? text('E-Mail-Adresse', required: true, validate: ['email' => 'email']);
$email = mb_strtolower(trim($email));
if (User::where('email', $email)->exists()) {
$this->error("Es gibt bereits einen Benutzer mit {$email}.");
return self::FAILURE;
}
$name = $this->option('name') ?? text('Name', required: true);
$role = $this->option('role') !== null
? UserRole::tryFrom($this->option('role'))
: UserRole::from(select('Rolle', collect(UserRole::cases())->mapWithKeys(fn (UserRole $role): array => [$role->value => "{$role->getLabel()} – {$role->getDescription()}"])->all(), default: UserRole::Admin->value));
if ($role === null) {
$this->error('Unbekannte Rolle. Erlaubt: '.implode(', ', array_column(UserRole::cases(), 'value')));
return self::FAILURE;
}
$password = password('Passwort (mind. 12 Zeichen)', required: true, validate: ['password' => Password::min(12)]);
if (password('Passwort wiederholen', required: true) !== $password) {
$this->error('Die Passwörter stimmen nicht überein.');
return self::FAILURE;
}
User::create(['name' => $name, 'email' => $email, 'role' => $role, 'password' => $password]);
$this->info("Benutzer {$email} ({$role->getLabel()}) angelegt.");
if ($role === UserRole::Admin) {
$this->line('Bei der ersten Anmeldung wird die Zwei-Faktor-Anmeldung mit einer Authenticator-App eingerichtet.');
}
return self::SUCCESS;
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Http\Middleware;
use App\Enums\UserRole;
use App\Models\User;
use Closure;
use Filament\Auth\MultiFactor\Http\Middleware\EnsureMultiFactorAuthenticationIsEnabled;
use Filament\Facades\Filament;
use Illuminate\Http\Request;
/**
* Filament evaluates "two-factor required" once per panel; this narrows it to administrators.
* Other roles may set it up voluntarily in their profile.
*/
class RequireTwoFactorForAdmins extends EnsureMultiFactorAuthenticationIsEnabled
{
public function handle(Request $request, Closure $next): mixed
{
$user = Filament::auth()->user();
if (! $user instanceof User || ! $user->hasRole(UserRole::Admin)) {
return $next($request);
}
return parent::handle($request, $next);
}
}
+6 -2
View File
@@ -5,6 +5,10 @@
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Enums\UserRole;
use Database\Factories\UserFactory;
use Filament\Auth\MultiFactor\App\Concerns\InteractsWithAppAuthentication;
use Filament\Auth\MultiFactor\App\Concerns\InteractsWithAppAuthenticationRecovery;
use Filament\Auth\MultiFactor\App\Contracts\HasAppAuthentication;
use Filament\Auth\MultiFactor\App\Contracts\HasAppAuthenticationRecovery;
use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use Illuminate\Database\Eloquent\Attributes\Fillable;
@@ -15,10 +19,10 @@
#[Fillable(['name', 'email', 'role', 'password'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable implements FilamentUser
class User extends Authenticatable implements FilamentUser, HasAppAuthentication, HasAppAuthenticationRecovery
{
/** @use HasFactory<UserFactory> */
use HasFactory, Notifiable;
use HasFactory, InteractsWithAppAuthentication, InteractsWithAppAuthenticationRecovery, Notifiable;
/**
* Accounts are created by administrators only; an account without a role has no access.
@@ -2,6 +2,8 @@
namespace App\Providers\Filament;
use App\Http\Middleware\RequireTwoFactorForAdmins;
use Filament\Auth\MultiFactor\App\AppAuthentication;
use Filament\Http\Middleware\Authenticate;
use Filament\Http\Middleware\AuthenticateSession;
use Filament\Http\Middleware\DisableBladeIconComponents;
@@ -27,6 +29,13 @@ public function panel(Panel $panel): Panel
->id('admin')
->path('admin')
->login()
->profile(isSimple: false)
// Two-factor login with an authenticator app (TOTP) and recovery codes; mandatory for administrators.
->multiFactorAuthentication(
[AppAuthentication::make()->brandName('FeWo Stommer')->recoverable()],
isRequired: true,
)
->multiFactorAuthenticationRequiredMiddlewareName(RequireTwoFactorForAdmins::class)
->brandName('FeWo Stommer · Verwaltung')
->navigationGroups(['Vermietung', 'Webseite', 'System'])
->colors([
+9
View File
@@ -32,9 +32,18 @@ public function definition(): array
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
'role' => UserRole::Admin,
'app_authentication_secret' => 'JBSWY3DPEHPK3PXP',
];
}
/**
* Indicate that the user has not set up two-factor authentication yet.
*/
public function withoutTwoFactor(): static
{
return $this->state(fn (): array => ['app_authentication_secret' => null]);
}
public function role(?UserRole $role): static
{
return $this->state(fn (): array => ['role' => $role]);
@@ -0,0 +1,29 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->text('app_authentication_secret')->nullable()->after('password');
$table->text('app_authentication_recovery_codes')->nullable()->after('app_authentication_secret');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['app_authentication_secret', 'app_authentication_recovery_codes']);
});
}
};
+1 -1
View File
@@ -16,7 +16,7 @@ class DatabaseSeeder extends Seeder
*/
public function run(): void
{
User::factory()->create([
User::factory()->withoutTwoFactor()->create([
'name' => 'Admin',
'email' => 'admin@example.com',
'role' => UserRole::Admin,
+133
View File
@@ -0,0 +1,133 @@
# Betrieb: Umgebungen, Zugänge, Einrichtung
Stand: 22.10.2026. Dieses Dokument beschreibt den **tatsächlichen Stand** der Installationen, damit jede neue Arbeitssitzung (Mensch oder KI) ohne Vorwissen weitermachen kann. Allgemeine Abläufe des Deployments stehen in [DEPLOYMENT.md](DEPLOYMENT.md), das fachliche Konzept in [KONZEPT.md](KONZEPT.md).
> **Geheimnisse stehen nie im Repository und nie im Chat.** Passwörter (Datenbank, E-Mail), `APP_KEY`, Tokens und private SSH-Schlüssel liegen nur in `shared/.env` auf dem Server bzw. im Vaultwarden von Lars. Hier ist nur dokumentiert, *wo* sie liegen.
## 1. Überblick
| | Testbetrieb (staging) | Produktion |
|---|---|---|
| Adresse | **https://stommer.info** | später https://www.fewo-stommer.de (heute noch WordPress) |
| Ordner auf dem Webspace | `test.fewo-stommer.de/` | noch nicht angelegt (Vorschlag: `fewo-production/`) |
| Deploy-Konfiguration (lokal, nicht committet) | `scripts/deploy.staging.env` | `scripts/deploy.production.env` (anlegen aus `deploy.example.env`) |
| Datenbank | MariaDB 11.8, siehe §3 | eigene Datenbank anlegen |
| E-Mail | `MAIL_MAILER=log` – **verschickt nichts** | Strato-SMTP |
| Postfach-Abruf (Portal-Mails) | aus (`FEWO_MAILBOX_HOST` leer) | `imap.strato.de` |
| Suchmaschinen | `noindex` (alles außer `APP_ENV=production`) | indexiert |
| Cronjob | **noch offen** (§6) | einrichten |
Git: `https://gitea.stommer.de/Lars/fewo-stommer.git`, Branch `main`. Gebaut und ausgeliefert wird immer der **letzte Commit**.
## 2. Strato-Paket (Hosting Pro)
- **SSH/SFTP-Server:** `51539426.ssh.w1.strato.hosting` (paketspezifisch, *nicht* `ssh.strato.de` – der lehnt ab). Port 22.
- **SSH-Benutzer:** `stu100093250` (Kundenlogin › Datenbanken und Webspace › SFTP & SSH › Details). Startverzeichnis `/` = Webspace-Wurzel.
- **Absoluter Pfad des Webspace:** `/mnt/web508/e3/26/51539426/htdocs/` (für Cronjobs).
- **PHP-CLI:** `/opt/RZphp84/bin/php-cli` (8.4). Die Web-PHP-Version des Pakets ist eine andere (8.3); die `.htaccess` im Deploy-Ordner setzt per `AddType application/x-httpd-php84 .php` 8.4 **nur für diesen Ordner**.
- **Andere Inhalte im Webspace nicht anfassen:** u. a. `www.fewo-stommer.de/` (bestehendes WordPress), `fewo`, Karate-Wiki, Moodle. Das Deploy-Skript arbeitet ausschließlich unterhalb von `DEPLOY_PATH`.
- **Domains:** SSL-Zertifikate gibt es im Paket nur für Hauptdomains, nicht für Subdomains. Deshalb läuft der Test unter `stommer.info` (Ziel: Ordner `test.fewo-stommer.de`, SSL aktiv, `www.stommer.info` ebenso). Die Subdomain `test.fewo-stommer.de` wird nicht mehr gebraucht.
- **Domain-Ziel = Deploy-Ordner selbst** (Strato kann kein Symlink-Ziel wählen). Die dort vom Skript geschriebene `.htaccess` leitet auf `releases/<aktive Version>/public` und sperrt alles Interne mit 403.
## 3. Datenbank (staging)
- Host `database-5021719836.webspace-host.com`, Port 3306, Datenbank `dbs16257975`, Benutzer `dbu2231025`, `DB_CONNECTION=mariadb`.
- Passwort: nur in `test.fewo-stommer.de/shared/.env` (und Vaultwarden).
## 4. SSH-Zugang einrichten (neuer Rechner, z. B. privater PC)
1. Schlüssel erzeugen: `ssh-keygen -t ed25519 -f ~/.ssh/strato_fewo -C "fewo-deploy <rechner>"`.
2. Öffentlichen Schlüssel beim Server eintragen (fragt einmal das SSH-Passwort des Strato-Benutzers ab):
`ssh-copy-id -i ~/.ssh/strato_fewo.pub stu100093250@51539426.ssh.w1.strato.hosting`
(Windows ohne `ssh-copy-id`: Inhalt von `strato_fewo.pub` per SSH an `~/.ssh/authorized_keys` anhängen.)
3. Test: `ssh -i ~/.ssh/strato_fewo stu100093250@51539426.ssh.w1.strato.hosting "ls"`.
4. Den privaten Schlüssel nur im Vaultwarden sichern, nie committen oder weitergeben.
5. **Aufräumen:** Der Schlüssel des Firmen-Laptops (Kommentar in `~/.ssh/authorized_keys` auf dem Server) wird entfernt, sobald der private PC eingerichtet ist.
Lokale Werkzeuge: PHP 8.4 CLI, Composer, Node/npm, Git, Bash (Windows: Git Bash). Danach `scripts/deploy.example.env` nach `scripts/deploy.staging.env` kopieren und mit den Werten aus §2 füllen (`DEPLOY_PATH=test.fewo-stommer.de`, `DEPLOY_URL=https://stommer.info`, `DEPLOY_SSH_KEY=~/.ssh/strato_fewo`; unter Windows ggf. `COMPOSER_BIN="php /c/…/composer.phar"`).
## 5. Konfiguration auf dem Server (`shared/.env`)
Vorlage: [.env.production.example](../.env.production.example). Bearbeiten nur direkt auf dem Server, damit Passwörter nicht durch Chat oder Repository laufen:
```bash
ssh -t -i ~/.ssh/strato_fewo stu100093250@51539426.ssh.w1.strato.hosting "nano test.fewo-stommer.de/shared/.env"
bash scripts/deploy.sh staging artisan optimize # danach Konfiguration neu einlesen
```
Gesetzte Werte im Testbetrieb (Geheimnisse ausgelassen):
| Schlüssel | Wert | Bemerkung |
|---|---|---|
| `APP_ENV` | `staging` | nicht `production` → `noindex` |
| `APP_DEBUG` | `false` | |
| `APP_URL` | `https://stommer.info` | alle erzeugten Links bauen darauf auf (`URL::forceRootUrl`) |
| `APP_KEY` | gesetzt | **nie ändern** – sonst sind 2FA-Schlüssel und Sitzungen unlesbar |
| `DB_*` | siehe §3 | |
| `SESSION_DRIVER` / `CACHE_STORE` | `database` | |
| `SESSION_SECURE_COOKIE` | `true` | Anmeldung nur über HTTPS |
| `QUEUE_CONNECTION` | `sync` | keine Worker auf Shared Hosting |
| `MAIL_MAILER` | `log` | Testbetrieb verschickt **keine** E-Mails (landen in `shared/storage/logs`) |
| `FEWO_MAILBOX_HOST` | leer | Testbetrieb liest **kein** echtes Postfach |
| `FEWO_BANK_*` | leer | für Verträge/Angebote noch einzutragen |
| `FEWO_HEALTH_TOKEN`, `FEWO_SCHEDULER_TOKEN`, `FEWO_AUTOMATION_SECRET` | gesetzt | für n8n (Überwachung, Scheduler-Ersatz, Webhooks) |
## 6. Erledigt / offen im Testbetrieb
Erledigt (22.10.2026): Ordnerstruktur, `shared/.env`, Migrationen, Grunddaten (`ProductionSeeder`: Wohnung, Saisons 2026, Inhalte, Seiten, Erscheinungsbilder), HTTPS unter stommer.info, Gesundheitscheck mit automatischem Rollback.
Offen:
- **Admin-Benutzer anlegen** (§7) und 2FA einrichten.
- **Cronjob** (Kundenlogin › Cronjobs), jede Minute:
`/opt/RZphp84/bin/php-cli /mnt/web508/e3/26/51539426/htdocs/test.fewo-stommer.de/current/artisan schedule:run`
Falls Strato nicht minütlich erlaubt: n8n ruft jede Minute `https://stommer.info/automation/scheduler?token=<FEWO_SCHEDULER_TOKEN>` auf.
- Fotos importieren, Bankdaten, Vertrags- und AGB-Texte, Rechtstexte prüfen.
- Gitea-Runner für automatisches Deployment (DEPLOYMENT.md §5).
## 7. Zugang zur Verwaltung (`/admin`)
**Benutzer anlegen** – der erste Administrator per Befehl (das Passwort wird verdeckt im eigenen Terminal eingegeben, nie als Argument):
```bash
ssh -t -i ~/.ssh/strato_fewo stu100093250@51539426.ssh.w1.strato.hosting \
"cd test.fewo-stommer.de/current && /opt/RZphp84/bin/php-cli artisan users:create lars@stommer.com --name='Lars Stommer' --role=admin"
```
Weitere Benutzer legt ein Administrator in der Verwaltung an (System › Benutzer). Rollen: `admin` (alles inkl. Benutzer), `rentals` (Vermietung), `content` (Inhalte); ohne Rolle kein Zugang.
**Zwei-Faktor-Anmeldung (2FA):** Filament-eigene Lösung mit Authenticator-App (TOTP, z. B. Bitwarden/Vaultwarden, Google oder Microsoft Authenticator) und Wiederherstellungscodes.
- **Pflicht für Administratoren:** Nach der ersten Anmeldung wird man auf die Einrichtungsseite geleitet (QR-Code scannen, Code bestätigen, Wiederherstellungscodes sichern). Umgesetzt mit `App\Http\Middleware\RequireTwoFactorForAdmins`.
- **Freiwillig für andere Rollen:** im Profil (Avatar oben rechts › Profil).
- Schlüssel und Codes liegen verschlüsselt (mit `APP_KEY`) in `users.app_authentication_secret` / `app_authentication_recovery_codes`.
- **Handy verloren:** Anmeldung mit einem Wiederherstellungscode. Sind auch die weg, setzt ein Administrator mit Serverzugang die 2FA zurück:
```bash
bash scripts/deploy.sh staging artisan tinker --execute='App\Models\User::where("email", "lars@stommer.com")->update(["app_authentication_secret" => null, "app_authentication_recovery_codes" => null]);'
```
Danach bei der nächsten Anmeldung neu einrichten.
Lokal (nur Entwicklung, `php artisan migrate:fresh --seed`): `admin@example.com` / `password`, 2FA wird bei der ersten Anmeldung eingerichtet.
## 8. Bekannte Eigenheiten und Lösungen
| Problem | Ursache | Lösung (umgesetzt) |
|---|---|---|
| Nach dem Umschalten lief die alte Version weiter | Strato-OPcache speichert Skripte unter dem Symlink-Pfad `current/…` | `.htaccess` zeigt auf den konkreten Ordner `releases/<version>/public` und wird bei jedem Umschalten neu geschrieben |
| Links mit `/current/public` (z. B. Sitemap) | Laravel leitet den Basis-Pfad aus dem Skript-Pfad ab | `URL::forceRootUrl(APP_URL)` außerhalb von local/testing (`AppServiceProvider`) |
| HTTP 500 „Composer platform“ | Web-PHP des Pakets ist 8.3 | `AddType application/x-httpd-php84 .php` in der Ordner-`.htaccess` |
| SSH „connection closed“ | falscher Server `ssh.strato.de` | paketspezifischer Server (§2) |
| Domain-Ziel `current/public` nicht wählbar | Strato erlaubt kein Symlink-Ziel | Domain auf den Deploy-Ordner, `.htaccess` leitet weiter |
| Ersteinrichtung mit Factories schlägt fehl | Produktion ohne Dev-Pakete | `ProductionSeeder` |
| Kein SSL für Subdomain | Paket erlaubt SSL nur für Hauptdomains | Testbetrieb auf `stommer.info` |
| Windows: Symlinks, `php` nicht im PATH | Git Bash | Deploy nur gegen Strato testen; `export PATH="<php-ordner>:$PATH"` |
## 9. Nützliche Befehle
```bash
bash scripts/deploy.sh staging deploy # ausliefern (letzter Commit)
bash scripts/deploy.sh staging rollback # vorige Version
bash scripts/deploy.sh staging releases # Versionen auf dem Server
bash scripts/deploy.sh staging artisan about # Zustand der Installation
bash scripts/deploy.sh staging artisan migrate:status
ssh -i ~/.ssh/strato_fewo stu100093250@51539426.ssh.w1.strato.hosting \
"tail -n 50 test.fewo-stommer.de/shared/storage/logs/laravel-$(date +%F).log" # Fehlerprotokoll
```
@@ -0,0 +1,72 @@
<?php
namespace Tests\Feature;
use App\Enums\UserRole;
use App\Filament\Resources\Bookings\BookingResource;
use App\Models\User;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;
class TwoFactorAuthenticationTest extends TestCase
{
use RefreshDatabase;
public function test_admin_without_two_factor_must_set_it_up_first(): void
{
$this->actingAs(User::factory()->withoutTwoFactor()->create());
$setUpUrl = Filament::getPanel('admin')->getSetUpRequiredMultiFactorAuthenticationUrl();
$this->get(BookingResource::getUrl('index'))->assertRedirect($setUpUrl);
$this->get($setUpUrl)->assertOk()->assertSee('Authenticator', false);
}
public function test_admin_with_two_factor_enters_the_admin(): void
{
$this->actingAs(User::factory()->create());
$this->get(BookingResource::getUrl('index'))->assertOk();
}
public function test_other_roles_may_work_without_two_factor(): void
{
$this->actingAs(User::factory()->role(UserRole::Rentals)->withoutTwoFactor()->create());
$this->get(BookingResource::getUrl('index'))->assertOk();
}
public function test_two_factor_secret_is_stored_encrypted(): void
{
$user = User::factory()->create();
$this->assertNotSame('JBSWY3DPEHPK3PXP', $user->getRawOriginal('app_authentication_secret'));
$this->assertSame('JBSWY3DPEHPK3PXP', $user->fresh()->getAppAuthenticationSecret());
}
public function test_command_creates_an_admin_with_interactively_entered_password(): void
{
$this->artisan('users:create', ['email' => 'Lars@Example.com', '--name' => 'Lars', '--role' => 'admin'])
->expectsQuestion('Passwort (mind. 12 Zeichen)', 'ein-sicheres-passwort')
->expectsQuestion('Passwort wiederholen', 'ein-sicheres-passwort')
->assertSuccessful();
$user = User::firstWhere('email', 'lars@example.com');
$this->assertSame(UserRole::Admin, $user->role);
$this->assertTrue(Hash::check('ein-sicheres-passwort', $user->password));
$this->assertNull($user->getAppAuthenticationSecret());
}
public function test_command_rejects_mismatching_passwords(): void
{
$this->artisan('users:create', ['email' => 'lars@example.com', '--name' => 'Lars', '--role' => 'admin'])
->expectsQuestion('Passwort (mind. 12 Zeichen)', 'ein-sicheres-passwort')
->expectsQuestion('Passwort wiederholen', 'etwas-anderes-passwort')
->assertFailed();
$this->assertDatabaseCount('users', 0);
}
}