Files
einundzwanzig-verein/resources/views/livewire/association/project-support/form/create.blade.php
vk d1b9dad35e [P2 Security] Laravel Authorization Policies für ProjectProposal, Vote, Election (vibe-kanban 85007440)
## Security Audit: Fehlende zentralisierte Autorisierung

### Problem
Die Anwendung hat **keine Laravel Policy-Klassen**. Autorisierungslogik ist verstreut in:

- **Blade Templates:** Inline `@if`-Checks gegen `config('einundzwanzig.config.current_board')`
- **Livewire Trait:** `app/Livewire/Traits/WithNostrAuth.php` setzt `$isAllowed` und `$canEdit` Booleans
- **Component-Mount-Methoden:** z.B. in `project-support/form/create.blade.php` (Zeile 41-47)

Die Board-Member-Autorisierung funktioniert über einen Vergleich mit hartkodierten npubs in `config/einundzwanzig/config.php`:
```php
'current_board' => [
    'npub1pt0kw36...', 'npub1gvqkjc...', // etc.
]
```

**Probleme:**
- Keine zentrale Stelle für Berechtigungsprüfungen
- Autorisierung kann leicht vergessen werden wenn neue Endpoints hinzukommen
- Board-Member-Check wird an vielen Stellen dupliziert
- Livewire-Actions können ggf. direkt aufgerufen werden ohne UI-seitige Prüfung

### Lösung

**1. Laravel Policies erstellen:**

```bash
php artisan make:policy ProjectProposalPolicy --model=ProjectProposal --no-interaction
php artisan make:policy VotePolicy --model=Vote --no-interaction
php artisan make:policy ElectionPolicy --model=Election --no-interaction
```

**2. Policy-Methoden implementieren:**

Für `ProjectProposalPolicy`:
- `viewAny()` – Jeder darf die Liste sehen
- `view()` – Jeder darf ein Proposal sehen
- `create()` – Nur authentifizierte User mit `association_status > 1` und bezahlter Mitgliedschaft im aktuellen Jahr
- `update()` – Nur der Ersteller ODER Board-Members
- `delete()` – Nur Board-Members
- `accept()` – Nur Board-Members (custom method für `accepted`-Flag)

Für `VotePolicy`:
- `create()` – Authentifizierte User, die noch nicht für dieses Proposal abgestimmt haben
- `update()` / `delete()` – Nur der eigene Vote

Für `ElectionPolicy`:
- `viewAny()` / `view()` – Jeder
- `create()` / `update()` / `delete()` – Nur Board-Members
- `vote()` – Authentifizierte Mitglieder mit gültigem Status

**3. Auth-Checks in der Nostr-Auth-Architektur:**

Die App nutzt eine Custom NostrAuth (`app/Support/NostrAuth.php`, `app/Auth/NostrUser.php`). Die Policies müssen mit `NostrUser` funktionieren. Prüfe ob `NostrUser` das `Authenticatable` Interface korrekt implementiert, damit `$this->authorize()` und `Gate::allows()` in Livewire-Components funktionieren.

**4. Policies in Livewire-Components nutzen:**

Ersetze die inline-Checks in den Components durch Policy-Aufrufe:
```php
// Vorher (verstreut in Blade/Component):
if (in_array($this->currentPleb->npub, config('einundzwanzig.config.current_board'), true)) { ... }

// Nachher (zentralisiert):
$this->authorize('update', $projectProposal);
```

### Betroffene Dateien
- **Neue Dateien:** `app/Policies/ProjectProposalPolicy.php`, `app/Policies/VotePolicy.php`, `app/Policies/ElectionPolicy.php`
- **Anpassen:** `app/Livewire/Traits/WithNostrAuth.php` – Board-Check in Policy auslagern
- **Anpassen:** Livewire-Components in `app/Livewire/Association/ProjectSupport/` – `$this->authorize()` nutzen
- **Anpassen:** Livewire-Components in `app/Livewire/Association/Election/` – `$this->authorize()` nutzen
- **Prüfen:** `app/Auth/NostrUser.php` – Kompatibilität mit Policy-System
- **Prüfen:** `config/einundzwanzig/config.php` – Board-Member-Liste wird weiterhin als Datenquelle genutzt

### Vorgehen
1. `search-docs` nutzen: `queries: ['policies', 'authorization', 'gates']` und `packages: ['laravel/framework']`
2. Prüfe wie `NostrUser` mit Laravel's Authorization-System zusammenspielt
3. Policies mit `php artisan make:policy` erstellen
4. Policy-Methoden implementieren (Board-Check-Logik zentralisieren)
5. Livewire-Components auf Policy-Aufrufe umstellen
6. Blade-Templates: `@can` / `@cannot` Directives nutzen statt inline `@if`
7. Pest Feature-Tests für jede Policy-Methode schreiben
8. `vendor/bin/pint --dirty` und `php artisan test --compact`

### Akzeptanzkriterien
- 3 Policy-Klassen existieren und sind registriert
- Board-Member-Check ist an EINER Stelle definiert (in Policy oder Helper)
- Livewire-Components nutzen `$this->authorize()` statt inline-Checks
- Blade-Templates nutzen `@can` / `@cannot` Directives
- Pest-Tests decken alle Policy-Methoden ab (allow & deny)
- Bestehende Funktionalität bleibt erhalten
2026-02-11 23:49:53 +01:00

219 lines
9.8 KiB
PHP

<?php
use App\Models\ProjectProposal;
use App\Support\NostrAuth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\RateLimiter;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithFileUploads;
new
#[Layout('layouts.app')]
#[Title('Projektförderung anlegen')]
class extends Component
{
use WithFileUploads;
public array $form = [
'name' => '',
'description' => '',
'support_in_sats' => '',
'website' => '',
'accepted' => false,
'sats_paid' => 0,
];
public $file = null;
#[Locked]
public bool $isAllowed = false;
#[Locked]
public bool $isAdmin = false;
public function mount(): void
{
$nostrUser = NostrAuth::user();
if ($nostrUser && Gate::forUser($nostrUser)->allows('create', ProjectProposal::class)) {
$this->isAllowed = true;
}
if ($nostrUser) {
$pleb = $nostrUser->getPleb();
if ($pleb && in_array($pleb->npub, config('einundzwanzig.config.current_board'), true)) {
$this->isAdmin = true;
}
}
}
public function removeFile(): void
{
if ($this->file) {
$this->file->delete();
$this->file = null;
}
}
public function save(): void
{
Gate::forUser(NostrAuth::user())->authorize('create', ProjectProposal::class);
$executed = RateLimiter::attempt(
'project-proposal-create:'.request()->ip(),
5,
function () {},
);
if (! $executed) {
abort(429, 'Too many requests.');
}
$this->validate([
'form.name' => 'required|string|max:255',
'form.description' => 'required|string',
'form.support_in_sats' => 'required|integer|min:0',
'form.website' => 'required|url|max:255',
'file' => 'nullable|file|mimes:jpeg,png,jpg,gif,webp|mimetypes:image/jpeg,image/png,image/gif,image/webp|max:10240',
]);
$projectProposal = new ProjectProposal;
$projectProposal->name = $this->form['name'];
$projectProposal->description = $this->form['description'];
$projectProposal->support_in_sats = (int) $this->form['support_in_sats'];
$projectProposal->website = $this->form['website'];
$projectProposal->accepted = $this->isAdmin ? $this->form['accepted'] : false;
$projectProposal->sats_paid = $this->isAdmin ? $this->form['sats_paid'] : 0;
$projectProposal->einundzwanzig_pleb_id = \App\Models\EinundzwanzigPleb::query()->where('pubkey', NostrAuth::pubkey())->first()->id;
$projectProposal->save();
if ($this->file) {
$projectProposal->addMedia($this->file)->toMediaCollection('main');
}
$this->redirectRoute('association.projectSupport');
}
};
?>
<div>
@if($isAllowed)
<div class="px-4 sm:px-6 lg:px-8 py-8 w-full max-w-9xl mx-auto">
<div
class="flex flex-col md:flex-row items-center mb-6 space-y-4 md:space-y-0 md:space-x-4">
<div class="flex items-center justify-between w-full">
<h1 class="text-2xl md:text-3xl text-zinc-800 dark:text-zinc-100 font-bold">
Projektförderungs-Antrag anlegen
</h1>
<flux:button :href="route('association.projectSupport')" variant="ghost" icon="arrow-left">
Zurück
</flux:button>
</div>
</div>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<!-- Form card -->
<div class="lg:col-span-2">
<flux:card>
<flux:fieldset>
<flux:legend>Formular</flux:legend>
<div class="space-y-4">
<flux:field>
<flux:label>Name</flux:label>
<flux:input wire:model="form.name" placeholder="Projektname" />
<flux:error name="form.name" />
</flux:field>
<flux:field>
<flux:label>Website</flux:label>
<flux:input wire:model="form.website" type="url" placeholder="https://example.com" />
<flux:error name="form.website" />
</flux:field>
<flux:field>
<flux:label>Unterstützung (Sats)</flux:label>
<flux:input wire:model="form.support_in_sats" type="number" placeholder="100000" />
<flux:error name="form.support_in_sats" />
</flux:field>
<flux:field>
<flux:label>Bild</flux:label>
<flux:file-upload wire:model="file" label="Bild hochladen">
<flux:file-upload.dropzone
heading="Bild hier ablegen oder zum Durchsuchen klicken"
text="JPG, PNG, GIF, WebP bis zu 10MB"
/>
</flux:file-upload>
<flux:error name="file" />
@if($file)
<div class="mt-4 flex flex-col gap-2">
<flux:file-item
:heading="$file->getClientOriginalName()"
:image="$file->temporaryUrl()"
:size="$file->getSize()"
>
<x-slot name="actions">
<flux:file-item.remove wire:click="removeFile" />
</x-slot>
</flux:file-item>
</div>
@endif
</flux:field>
<flux:editor wire:model="form.description" label="Beschreibung" description="Projektbeschreibung..." />
<flux:error name="form.description" />
@if($isAdmin)
<flux:separator />
<flux:heading level="3" class="text-sm font-semibold uppercase tracking-wide text-zinc-500 dark:text-zinc-400">Admin Felder</flux:heading>
<div class="space-y-3 mt-3">
<flux:field>
<flux:label>Akzeptiert</flux:label>
<flux:switch wire:model="form.accepted" />
</flux:field>
<flux:field>
<flux:label>Sats bezahlt</flux:label>
<flux:input type="number" wire:model="form.sats_paid" />
</flux:field>
</div>
@endif
<flux:button wire:click="save" wire:loading.attr="disabled" variant="primary" class="w-full mt-4">
Speichern
</flux:button>
</div>
</flux:fieldset>
</flux:card>
</div>
<!-- Information card -->
<div>
<flux:card>
<flux:heading level="2">Information</flux:heading>
<p class="text-sm text-zinc-800 dark:text-zinc-100 mt-4">
Fülle das Formular aus, um eine neue Projektförderung anzulegen.
</p>
</flux:card>
</div>
</div>
</div>
@else
<div class="px-4 sm:px-6 lg:px-8 py-8 w-full max-w-9xl mx-auto">
<flux:callout variant="warning" icon="exclamation-circle">
<flux:heading>Projektförderung kann nicht angelegt werden</flux:heading>
<p>Um eine Projektförderung anzulegen, benötigst du:</p>
<ul class="list-disc ml-5 mt-2 space-y-1">
<li>Einen Vereinsstatus von mindestens 2 (Aktives Mitglied)</li>
<li>Eine bezahlte Mitgliedschaft für das aktuelle Jahr ({{ date('Y') }})</li>
</ul>
<p class="mt-3">
@if(!NostrAuth::check())
Bitte melde dich zunächst mit Nostr an.
@else
Bitte kontaktiere den Vorstand, wenn du denkst, dass du berechtigt sein solltest.
@endif
</p>
</flux:callout>
</div>
@endif
</div>