Compare commits
10
Commits
5b4545b60f
...
a444f28681
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a444f28681 | ||
|
|
9748396478 | ||
|
|
8a519041f3 | ||
|
|
7b16940b96 | ||
|
|
4caab7e657 | ||
|
|
f1bfa27ba3 | ||
|
|
66fe8feea4 | ||
|
|
dc4b804ccf | ||
|
|
4c2500797b | ||
|
|
e9585b395c |
No files matched your search
+31
-2
@@ -1,4 +1,5 @@
|
|||||||
# Host binding: LAN IP of the Docker host and published port
|
# --- Network -------------------------------------------------------------------
|
||||||
|
# LAN IP of the Docker host and published port
|
||||||
BIND_IP=192.168.50.123
|
BIND_IP=192.168.50.123
|
||||||
APP_PORT=8085
|
APP_PORT=8085
|
||||||
|
|
||||||
@@ -6,6 +7,34 @@ APP_PORT=8085
|
|||||||
# 127.0.0.1 effectively disables proxy headers until the NPM source IP is known.
|
# 127.0.0.1 effectively disables proxy headers until the NPM source IP is known.
|
||||||
FORWARDED_ALLOW_IPS=127.0.0.1
|
FORWARDED_ALLOW_IPS=127.0.0.1
|
||||||
|
|
||||||
# Logging and timezone
|
# Public URL(s) of the app; state-changing requests from other origins are rejected
|
||||||
|
ALLOWED_ORIGINS=https://clip.webbildhauer.com
|
||||||
|
|
||||||
|
# --- Sessions and login --------------------------------------------------------
|
||||||
|
# Secure cookies are only sent over HTTPS; set false only for local development
|
||||||
|
COOKIE_SECURE=true
|
||||||
|
SESSION_IDLE_DAYS=30
|
||||||
|
SESSION_MAX_DAYS=90
|
||||||
|
|
||||||
|
LOGIN_MAX_FAILURES_PER_USER=5
|
||||||
|
LOGIN_MAX_FAILURES_PER_IP=20
|
||||||
|
LOGIN_FAILURE_WINDOW_MINUTES=15
|
||||||
|
# Enable only after FORWARDED_ALLOW_IPS is set; otherwise all users share the proxy IP
|
||||||
|
LOGIN_IP_LOCKOUT=false
|
||||||
|
|
||||||
|
# Optional: create the first admin on startup if no users exist. Remove afterwards!
|
||||||
|
# Preferred instead: docker exec -it -u app lan-clipboard lc-admin create-admin
|
||||||
|
#INITIAL_ADMIN_USERNAME=
|
||||||
|
#INITIAL_ADMIN_PASSWORD=
|
||||||
|
|
||||||
|
# --- Limits --------------------------------------------------------------------
|
||||||
|
# Maximum characters per clip and maximum API request size in bytes
|
||||||
|
CLIP_MAX_CHARS=200000
|
||||||
|
MAX_REQUEST_BYTES=1048576
|
||||||
|
|
||||||
|
# Swagger UI under /api/docs; keep disabled on a publicly reachable instance
|
||||||
|
ENABLE_API_DOCS=false
|
||||||
|
|
||||||
|
# --- Misc ----------------------------------------------------------------------
|
||||||
LOG_LEVEL=info
|
LOG_LEVEL=info
|
||||||
TZ=Europe/Berlin
|
TZ=Europe/Berlin
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Selbst gehostetes Web-Clipboard für das private Netz (LAN/VPN). Mehrere Benutzer synchronisieren Texte und Code-Snippets live zwischen ihren Geräten.
|
Selbst gehostetes Web-Clipboard für das private Netz (LAN/VPN). Mehrere Benutzer synchronisieren Texte und Code-Snippets live zwischen ihren Geräten.
|
||||||
|
|
||||||
> **Stand:** Meilenstein 1 – Grundgerüst mit Healthcheck. Benutzer, Clips und Live-Sync folgen.
|
> **Stand:** Meilenstein 3 – Clips (Text und Code mit Syntax-Highlighting), Benutzer, Login, Admin-Verwaltung. Live-Sync folgt.
|
||||||
|
|
||||||
## Aufbau
|
## Aufbau
|
||||||
|
|
||||||
@@ -26,6 +26,25 @@ curl http://192.168.50.123:8085/api/health
|
|||||||
# {"status":"ok","version":"0.1.0","db":"ok"}
|
# {"status":"ok","version":"0.1.0","db":"ok"}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Ersten Administrator anlegen
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker exec -it -u app lan-clipboard lc-admin create-admin
|
||||||
|
```
|
||||||
|
|
||||||
|
Benutzername und Passwort (mindestens 12 Zeichen) werden interaktiv abgefragt. Weitere Befehle:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker exec -it -u app lan-clipboard lc-admin create-user --username anna
|
||||||
|
docker exec -it -u app lan-clipboard lc-admin reset-password anna # beendet alle Sitzungen
|
||||||
|
```
|
||||||
|
|
||||||
|
`-u app` ist wichtig: Als root angelegte SQLite-Hilfsdateien wären für die App nicht beschreibbar, deshalb verweigert `lc-admin` den Start als root.
|
||||||
|
|
||||||
|
Alternativ legt der Container beim Start einen Admin aus `INITIAL_ADMIN_USERNAME`/`INITIAL_ADMIN_PASSWORD` an, solange noch kein Benutzer existiert. Die Werte danach wieder aus `.env` entfernen.
|
||||||
|
|
||||||
|
Die Anmeldung funktioniert nur über HTTPS (`https://clip.webbildhauer.com`), weil das Session-Cookie `Secure` ist.
|
||||||
|
|
||||||
Beim Start legt der Container `data/` an (falls nötig), übergibt es an UID 1000, führt `alembic upgrade head` aus und startet Uvicorn mit **einem Worker** (der WebSocket-Broadcast läuft im Prozess).
|
Beim Start legt der Container `data/` an (falls nötig), übergibt es an UID 1000, führt `alembic upgrade head` aus und startet Uvicorn mit **einem Worker** (der WebSocket-Broadcast läuft im Prozess).
|
||||||
|
|
||||||
### `.env`-Variablen
|
### `.env`-Variablen
|
||||||
@@ -35,16 +54,47 @@ Beim Start legt der Container `data/` an (falls nötig), übergibt es an UID 100
|
|||||||
| `BIND_IP` | – (Pflicht) | Host-IP, an die der Port gebunden wird, z. B. `192.168.50.123` |
|
| `BIND_IP` | – (Pflicht) | Host-IP, an die der Port gebunden wird, z. B. `192.168.50.123` |
|
||||||
| `APP_PORT` | `8085` | Veröffentlichter Host-Port |
|
| `APP_PORT` | `8085` | Veröffentlichter Host-Port |
|
||||||
| `FORWARDED_ALLOW_IPS` | `127.0.0.1` | IP(s) des Reverse Proxy (NPM), dessen `X-Forwarded-*`-Header vertraut wird. Kommagetrennt. |
|
| `FORWARDED_ALLOW_IPS` | `127.0.0.1` | IP(s) des Reverse Proxy (NPM), dessen `X-Forwarded-*`-Header vertraut wird. Kommagetrennt. |
|
||||||
|
| `ALLOWED_ORIGINS` | `https://clip.webbildhauer.com` | Erlaubte Origins für zustandsändernde Requests (und später WebSockets). Kommagetrennt. |
|
||||||
|
| `COOKIE_SECURE` | `true` | Session-Cookie nur über HTTPS. Nur für lokale Entwicklung auf `false` setzen. |
|
||||||
|
| `SESSION_IDLE_DAYS` | `30` | Session läuft nach so vielen Tagen ohne Nutzung ab |
|
||||||
|
| `SESSION_MAX_DAYS` | `90` | Maximale Lebensdauer einer Session |
|
||||||
|
| `LOGIN_MAX_FAILURES_PER_USER` | `5` | Fehlversuche pro Benutzername im Zeitfenster bis zur Sperre |
|
||||||
|
| `LOGIN_MAX_FAILURES_PER_IP` | `20` | Fehlversuche pro IP im Zeitfenster bis zur Sperre |
|
||||||
|
| `LOGIN_FAILURE_WINDOW_MINUTES` | `15` | Zeitfenster und Sperrdauer |
|
||||||
|
| `LOGIN_IP_LOCKOUT` | `false` | IP-Sperre aktivieren – **erst wenn `FORWARDED_ALLOW_IPS` gesetzt ist**, sonst teilen sich alle Benutzer die Proxy-IP |
|
||||||
|
| `CLIP_MAX_CHARS` | `200000` | Maximale Zeichenzahl pro Clip |
|
||||||
|
| `MAX_REQUEST_BYTES` | `1048576` | Maximale Größe eines API-Requests (1 MiB), größere werden mit 413 abgelehnt |
|
||||||
|
| `ENABLE_API_DOCS` | `false` | Swagger UI unter `/api/docs`. Bei öffentlich erreichbarer Instanz aus lassen. |
|
||||||
|
| `INITIAL_ADMIN_USERNAME` / `INITIAL_ADMIN_PASSWORD` | – | Optional: ersten Admin beim Start anlegen (siehe oben) |
|
||||||
| `LOG_LEVEL` | `info` | Log-Level von Uvicorn |
|
| `LOG_LEVEL` | `info` | Log-Level von Uvicorn |
|
||||||
| `TZ` | `Europe/Berlin` | Zeitzone im Container |
|
| `TZ` | `Europe/Berlin` | Zeitzone im Container |
|
||||||
|
|
||||||
|
## Sicherheit
|
||||||
|
|
||||||
|
- Passwörter: Argon2id (argon2-cffi), mindestens 12 Zeichen.
|
||||||
|
- Sessions serverseitig in SQLite; im Cookie `lc_session` (`HttpOnly`, `Secure`, `SameSite=Lax`) steht nur ein Zufallstoken, gespeichert wird sein SHA-256-Hash. Geräte sind unter „Konto“ einsehbar und widerrufbar.
|
||||||
|
- CSRF: Token pro Session im lesbaren Cookie `lc_csrf`, muss bei POST/PUT/PATCH/DELETE als Header `X-CSRF-Token` mitgeschickt werden. Zusätzlich werden Requests mit fremdem `Origin` abgelehnt.
|
||||||
|
- Fehlanmeldungen: Sperre pro Benutzername (und optional pro IP), Antwort HTTP 429. Gleiche Fehlermeldung für unbekannte Benutzer und falsche Passwörter.
|
||||||
|
- Passwortänderung, Passwort-Reset und Deaktivierung beenden die betroffenen Sessions.
|
||||||
|
- Datentrennung: Jede Clip-Abfrage filtert nach dem angemeldeten Benutzer. Fremde Clips liefern 404 wie nicht vorhandene, auch für Admins.
|
||||||
|
- Security-Header: CSP (`default-src 'self'`), `X-Frame-Options: DENY`, `nosniff`, Referrer- und Permissions-Policy; HSTS bei HTTPS (ohne `includeSubDomains`).
|
||||||
|
- Dateiartige Pfade wie `/.env` liefern 404 statt der App-Startseite.
|
||||||
|
- Die Instanz ist öffentlich erreichbar (keine Access List im NPM); Schutz durch Login, Sperre und die Maßnahmen oben.
|
||||||
|
|
||||||
|
## Clips
|
||||||
|
|
||||||
|
- Text oder Code; Code mit Sprache für Syntax-Highlighting (highlight.js, 24 Sprachen, Liste in `backend/app/languages.py` und `frontend/src/utils/highlight.ts` synchron halten).
|
||||||
|
- Angeheftete Clips stehen oben, danach die zuletzt geänderten.
|
||||||
|
- „Kopieren“ nutzt die Clipboard API (braucht HTTPS), „Einfügen“ liest die Zwischenablage (Browser fragt nach Erlaubnis).
|
||||||
|
- Konflikterkennung: Jeder Clip hat eine `version`. Wird er auf einem anderen Gerät geändert, meldet das Speichern einen Konflikt (HTTP 409) statt still zu überschreiben.
|
||||||
|
|
||||||
## Reverse Proxy (Nginx Proxy Manager)
|
## Reverse Proxy (Nginx Proxy Manager)
|
||||||
|
|
||||||
- Proxy Host → `http://192.168.50.123:8085`, **Websockets Support aktivieren** (ab Live-Sync nötig).
|
- Proxy Host → `http://192.168.50.123:8085`, **Websockets Support aktivieren** (ab Live-Sync nötig).
|
||||||
- SSL im NPM terminieren. Die App spricht intern nur HTTP.
|
- SSL im NPM terminieren. Die App spricht intern nur HTTP.
|
||||||
- `FORWARDED_ALLOW_IPS` auf die IP setzen, mit der NPM die App erreicht. Sie steht nach einem Aufruf über NPM im Log:
|
- `FORWARDED_ALLOW_IPS` auf die IP setzen, mit der NPM die App erreicht. Sie steht nach einem Aufruf über NPM im Log:
|
||||||
`docker compose logs app | grep "GET /api/health"` → erste Spalte ist die Absender-IP.
|
`docker compose logs app | grep "GET /api/health"` → erste Spalte ist die Absender-IP.
|
||||||
Danach `docker compose up -d` (die Variable wird beim Start gelesen).
|
Danach `docker compose up -d` (die Variable wird beim Start gelesen) und `LOGIN_IP_LOCKOUT=true` setzen.
|
||||||
|
|
||||||
## Entwicklung
|
## Entwicklung
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
"""clips
|
||||||
|
|
||||||
|
Revision ID: 0003
|
||||||
|
Revises: 0002
|
||||||
|
Create Date: 2026-10-25 10:48:45.833873
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "0003"
|
||||||
|
down_revision: str | None = "0002"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"clips",
|
||||||
|
sa.Column("id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"kind",
|
||||||
|
sa.Enum("text", "code", name="clipkind", native_enum=False, length=16),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("title", sa.String(length=200), nullable=True),
|
||||||
|
sa.Column("content", sa.Text(), nullable=False),
|
||||||
|
sa.Column("language", sa.String(length=32), nullable=True),
|
||||||
|
sa.Column("pinned", sa.Boolean(), nullable=False),
|
||||||
|
sa.Column("version", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
with op.batch_alter_table("clips", schema=None) as batch_op:
|
||||||
|
batch_op.create_index(
|
||||||
|
"ix_clips_user_order", ["user_id", "pinned", "updated_at"], unique=False
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table("clips", schema=None) as batch_op:
|
||||||
|
batch_op.drop_index("ix_clips_user_order")
|
||||||
|
|
||||||
|
op.drop_table("clips")
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
from fastapi import APIRouter, HTTPException, status
|
||||||
|
|
||||||
|
from app.api.deps import AdminUser, DbSession
|
||||||
|
from app.models import User
|
||||||
|
from app.schemas.auth import UserOut
|
||||||
|
from app.schemas.users import UserCreate, UserUpdate
|
||||||
|
from app.services import users as user_service
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/admin", tags=["admin"])
|
||||||
|
|
||||||
|
|
||||||
|
def _get_user_or_404(db: DbSession, user_id: int) -> User:
|
||||||
|
user = db.get(User, user_id)
|
||||||
|
if user is None:
|
||||||
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "Benutzer nicht gefunden.")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/users", response_model=list[UserOut])
|
||||||
|
def list_users(_admin: AdminUser, db: DbSession):
|
||||||
|
return user_service.list_users(db)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/users", response_model=UserOut, status_code=status.HTTP_201_CREATED)
|
||||||
|
def create_user(body: UserCreate, _admin: AdminUser, db: DbSession):
|
||||||
|
return user_service.create_user(db, body.username, body.password, body.role)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/users/{user_id}", response_model=UserOut)
|
||||||
|
def get_user(user_id: int, _admin: AdminUser, db: DbSession):
|
||||||
|
return _get_user_or_404(db, user_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/users/{user_id}", response_model=UserOut)
|
||||||
|
def update_user(user_id: int, body: UserUpdate, admin: AdminUser, db: DbSession):
|
||||||
|
target = _get_user_or_404(db, user_id)
|
||||||
|
return user_service.update_user(
|
||||||
|
db, admin, target, role=body.role, is_active=body.is_active, password=body.password
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
def delete_user(user_id: int, admin: AdminUser, db: DbSession) -> None:
|
||||||
|
user_service.delete_user(db, admin, _get_user_or_404(db, user_id))
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Query, status
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
|
||||||
|
from app.api.deps import CurrentUser, DbSession
|
||||||
|
from app.models import Clip
|
||||||
|
from app.schemas.clips import ClipCreate, ClipList, ClipOut, ClipUpdate
|
||||||
|
from app.services import clips as clip_service
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/clips", tags=["clips"])
|
||||||
|
|
||||||
|
# Fields that may be null on purpose (clearing them); all others are ignored when null
|
||||||
|
_NULLABLE_FIELDS = {"title", "language"}
|
||||||
|
|
||||||
|
|
||||||
|
def _get_own_clip(db: DbSession, user: CurrentUser, clip_id: int) -> Clip:
|
||||||
|
# Foreign and missing clips look the same, so ids of other users are not revealed
|
||||||
|
clip = clip_service.get_clip(db, user.id, clip_id)
|
||||||
|
if clip is None:
|
||||||
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.")
|
||||||
|
return clip
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=ClipList)
|
||||||
|
def list_clips(
|
||||||
|
user: CurrentUser,
|
||||||
|
db: DbSession,
|
||||||
|
limit: Annotated[int, Query(ge=1, le=100)] = 50,
|
||||||
|
offset: Annotated[int, Query(ge=0)] = 0,
|
||||||
|
) -> ClipList:
|
||||||
|
items, total = clip_service.list_clips(db, user.id, limit, offset)
|
||||||
|
return ClipList(items=[ClipOut.model_validate(c) for c in items], total=total)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=ClipOut, status_code=status.HTTP_201_CREATED)
|
||||||
|
def create_clip(body: ClipCreate, user: CurrentUser, db: DbSession):
|
||||||
|
return clip_service.create_clip(db, user.id, **body.model_dump())
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{clip_id}", response_model=ClipOut)
|
||||||
|
def get_clip(clip_id: int, user: CurrentUser, db: DbSession):
|
||||||
|
return _get_own_clip(db, user, clip_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/{clip_id}", response_model=ClipOut)
|
||||||
|
def update_clip(clip_id: int, body: ClipUpdate, user: CurrentUser, db: DbSession):
|
||||||
|
clip = _get_own_clip(db, user, clip_id)
|
||||||
|
changes = {
|
||||||
|
field: getattr(body, field)
|
||||||
|
for field in body.model_fields_set - {"version"}
|
||||||
|
if getattr(body, field) is not None or field in _NULLABLE_FIELDS
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
return clip_service.update_clip(db, user.id, clip, changes, body.version)
|
||||||
|
except clip_service.ClipConflict as exc:
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
|
content={
|
||||||
|
"detail": "Der Clip wurde inzwischen auf einem anderen Gerät geändert.",
|
||||||
|
"current": ClipOut.model_validate(exc.current).model_dump(mode="json"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{clip_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
def delete_clip(clip_id: int, user: CurrentUser, db: DbSession) -> None:
|
||||||
|
if not clip_service.delete_clip(db, user.id, clip_id):
|
||||||
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.")
|
||||||
@@ -5,11 +5,15 @@ from pydantic_settings import BaseSettings, SettingsConfigDict
|
|||||||
|
|
||||||
|
|
||||||
class Settings(BaseSettings):
|
class Settings(BaseSettings):
|
||||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
# Only real environment variables; compose passes .env via env_file. Reading a .env
|
||||||
|
# file here would leak the deployment config into tests run from the project root.
|
||||||
|
model_config = SettingsConfigDict(extra="ignore")
|
||||||
|
|
||||||
data_dir: Path = Path("/data")
|
data_dir: Path = Path("/data")
|
||||||
static_dir: Path = Path("/app/static")
|
static_dir: Path = Path("/app/static")
|
||||||
log_level: str = "info"
|
log_level: str = "info"
|
||||||
|
enable_api_docs: bool = False
|
||||||
|
max_request_bytes: int = 1024 * 1024
|
||||||
|
|
||||||
# Comma-separated list of origins allowed for state-changing requests and WebSockets
|
# Comma-separated list of origins allowed for state-changing requests and WebSockets
|
||||||
allowed_origins: str = "https://clip.webbildhauer.com"
|
allowed_origins: str = "https://clip.webbildhauer.com"
|
||||||
@@ -24,6 +28,8 @@ class Settings(BaseSettings):
|
|||||||
# Only meaningful once the real client IP is known (FORWARDED_ALLOW_IPS set to the proxy)
|
# Only meaningful once the real client IP is known (FORWARDED_ALLOW_IPS set to the proxy)
|
||||||
login_ip_lockout: bool = False
|
login_ip_lockout: bool = False
|
||||||
|
|
||||||
|
clip_max_chars: int = 200_000
|
||||||
|
|
||||||
initial_admin_username: str | None = None
|
initial_admin_username: str | None = None
|
||||||
initial_admin_password: str | None = None
|
initial_admin_password: str | None = None
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""Languages available for code clips; ids match highlight.js language names."""
|
||||||
|
|
||||||
|
LANGUAGES: tuple[str, ...] = (
|
||||||
|
"plaintext",
|
||||||
|
"bash",
|
||||||
|
"powershell",
|
||||||
|
"python",
|
||||||
|
"javascript",
|
||||||
|
"typescript",
|
||||||
|
"json",
|
||||||
|
"yaml",
|
||||||
|
"ini",
|
||||||
|
"xml",
|
||||||
|
"css",
|
||||||
|
"sql",
|
||||||
|
"markdown",
|
||||||
|
"dockerfile",
|
||||||
|
"nginx",
|
||||||
|
"go",
|
||||||
|
"rust",
|
||||||
|
"java",
|
||||||
|
"c",
|
||||||
|
"cpp",
|
||||||
|
"csharp",
|
||||||
|
"php",
|
||||||
|
"ruby",
|
||||||
|
"diff",
|
||||||
|
)
|
||||||
+40
-5
@@ -9,13 +9,17 @@ from fastapi.concurrency import run_in_threadpool
|
|||||||
from fastapi.responses import FileResponse, JSONResponse
|
from fastapi.responses import FileResponse, JSONResponse
|
||||||
|
|
||||||
from app import __version__
|
from app import __version__
|
||||||
from app.api import auth, health
|
from app.api import admin, auth, clips, health
|
||||||
from app.config import get_settings
|
from app.config import get_settings
|
||||||
from app.db import _session_factory
|
from app.db import _session_factory
|
||||||
from app.middleware import OriginCheckMiddleware
|
from app.middleware import (
|
||||||
|
BodySizeLimitMiddleware,
|
||||||
|
OriginCheckMiddleware,
|
||||||
|
SecurityHeadersMiddleware,
|
||||||
|
)
|
||||||
from app.services.auth import delete_old_login_attempts
|
from app.services.auth import delete_old_login_attempts
|
||||||
from app.services.sessions import delete_expired_sessions
|
from app.services.sessions import delete_expired_sessions
|
||||||
from app.services.users import UserError
|
from app.services.users import UserError, bootstrap_initial_admin
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -39,8 +43,30 @@ async def _cleanup_loop() -> None:
|
|||||||
await asyncio.sleep(CLEANUP_INTERVAL_SECONDS)
|
await asyncio.sleep(CLEANUP_INTERVAL_SECONDS)
|
||||||
|
|
||||||
|
|
||||||
|
def _bootstrap_admin() -> None:
|
||||||
|
settings = get_settings()
|
||||||
|
if not (settings.initial_admin_username and settings.initial_admin_password):
|
||||||
|
return
|
||||||
|
with _session_factory()() as db:
|
||||||
|
try:
|
||||||
|
user = bootstrap_initial_admin(
|
||||||
|
db, settings.initial_admin_username, settings.initial_admin_password
|
||||||
|
)
|
||||||
|
except UserError as exc:
|
||||||
|
logger.error("INITIAL_ADMIN_* ignored: %s", exc)
|
||||||
|
return
|
||||||
|
if user is not None:
|
||||||
|
logger.warning(
|
||||||
|
"Initial admin '%s' created from INITIAL_ADMIN_*; remove these from .env now.",
|
||||||
|
user.username,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
logger.info("INITIAL_ADMIN_* ignored: users already exist; remove them from .env.")
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
||||||
|
await run_in_threadpool(_bootstrap_admin)
|
||||||
task = asyncio.create_task(_cleanup_loop())
|
task = asyncio.create_task(_cleanup_loop())
|
||||||
try:
|
try:
|
||||||
yield
|
yield
|
||||||
@@ -60,6 +86,10 @@ def _register_frontend(app: FastAPI, static_dir: Path) -> None:
|
|||||||
candidate = (root / path).resolve()
|
candidate = (root / path).resolve()
|
||||||
if path and candidate.is_relative_to(root) and candidate.is_file():
|
if path and candidate.is_relative_to(root) and candidate.is_file():
|
||||||
return FileResponse(candidate)
|
return FileResponse(candidate)
|
||||||
|
# Paths that look like files (/.env, /wp-login.php, /.git/config) are not app routes
|
||||||
|
segments = path.split("/")
|
||||||
|
if "." in segments[-1] or any(seg.startswith(".") for seg in segments):
|
||||||
|
raise HTTPException(status_code=404)
|
||||||
return FileResponse(index_file, headers={"Cache-Control": "no-cache"})
|
return FileResponse(index_file, headers={"Cache-Control": "no-cache"})
|
||||||
|
|
||||||
|
|
||||||
@@ -68,14 +98,19 @@ def create_app() -> FastAPI:
|
|||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="LAN-Clipboard",
|
title="LAN-Clipboard",
|
||||||
version=__version__,
|
version=__version__,
|
||||||
docs_url="/api/docs",
|
docs_url="/api/docs" if settings.enable_api_docs else None,
|
||||||
openapi_url="/api/openapi.json",
|
openapi_url="/api/openapi.json" if settings.enable_api_docs else None,
|
||||||
redoc_url=None,
|
redoc_url=None,
|
||||||
lifespan=lifespan,
|
lifespan=lifespan,
|
||||||
)
|
)
|
||||||
|
# Last added runs first: security headers wrap every response, including rejections
|
||||||
app.add_middleware(OriginCheckMiddleware, allowed_origins=settings.allowed_origin_list)
|
app.add_middleware(OriginCheckMiddleware, allowed_origins=settings.allowed_origin_list)
|
||||||
|
app.add_middleware(BodySizeLimitMiddleware, max_bytes=settings.max_request_bytes)
|
||||||
|
app.add_middleware(SecurityHeadersMiddleware)
|
||||||
app.include_router(health.router, prefix="/api")
|
app.include_router(health.router, prefix="/api")
|
||||||
app.include_router(auth.router, prefix="/api")
|
app.include_router(auth.router, prefix="/api")
|
||||||
|
app.include_router(admin.router, prefix="/api")
|
||||||
|
app.include_router(clips.router, prefix="/api")
|
||||||
|
|
||||||
@app.exception_handler(UserError)
|
@app.exception_handler(UserError)
|
||||||
def user_error_handler(_request: Request, exc: UserError) -> JSONResponse:
|
def user_error_handler(_request: Request, exc: UserError) -> JSONResponse:
|
||||||
|
|||||||
+101
-1
@@ -1,6 +1,6 @@
|
|||||||
from starlette.datastructures import Headers
|
from starlette.datastructures import Headers
|
||||||
from starlette.responses import JSONResponse
|
from starlette.responses import JSONResponse
|
||||||
from starlette.types import ASGIApp, Receive, Scope, Send
|
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
||||||
|
|
||||||
SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
|
SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
|
||||||
|
|
||||||
@@ -24,3 +24,103 @@ class OriginCheckMiddleware:
|
|||||||
await response(scope, receive, send)
|
await response(scope, receive, send)
|
||||||
return
|
return
|
||||||
await self.app(scope, receive, send)
|
await self.app(scope, receive, send)
|
||||||
|
|
||||||
|
|
||||||
|
CONTENT_SECURITY_POLICY = "; ".join(
|
||||||
|
[
|
||||||
|
"default-src 'self'",
|
||||||
|
"script-src 'self'",
|
||||||
|
"style-src 'self'",
|
||||||
|
"img-src 'self' data:",
|
||||||
|
"connect-src 'self'",
|
||||||
|
"frame-ancestors 'none'",
|
||||||
|
"base-uri 'self'",
|
||||||
|
"form-action 'self'",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
SECURITY_HEADERS = [
|
||||||
|
(b"content-security-policy", CONTENT_SECURITY_POLICY.encode()),
|
||||||
|
(b"x-content-type-options", b"nosniff"),
|
||||||
|
(b"referrer-policy", b"same-origin"),
|
||||||
|
(b"x-frame-options", b"DENY"),
|
||||||
|
(b"permissions-policy", b"camera=(), microphone=(), geolocation=(), payment=()"),
|
||||||
|
]
|
||||||
|
|
||||||
|
# No includeSubDomains: other subdomains of the domain are not under our control
|
||||||
|
HSTS_HEADER = (b"strict-transport-security", b"max-age=31536000")
|
||||||
|
|
||||||
|
|
||||||
|
class SecurityHeadersMiddleware:
|
||||||
|
"""Add security headers to every HTTP response; HSTS only for HTTPS requests."""
|
||||||
|
|
||||||
|
def __init__(self, app: ASGIApp) -> None:
|
||||||
|
self.app = app
|
||||||
|
|
||||||
|
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||||
|
if scope["type"] != "http":
|
||||||
|
await self.app(scope, receive, send)
|
||||||
|
return
|
||||||
|
|
||||||
|
extra = list(SECURITY_HEADERS)
|
||||||
|
if scope.get("scheme") == "https":
|
||||||
|
extra.append(HSTS_HEADER)
|
||||||
|
|
||||||
|
async def send_with_headers(message: Message) -> None:
|
||||||
|
if message["type"] == "http.response.start":
|
||||||
|
existing = {name.lower() for name, _ in message.get("headers", [])}
|
||||||
|
headers = list(message.get("headers", []))
|
||||||
|
headers.extend((n, v) for n, v in extra if n not in existing)
|
||||||
|
message["headers"] = headers
|
||||||
|
await send(message)
|
||||||
|
|
||||||
|
await self.app(scope, receive, send_with_headers)
|
||||||
|
|
||||||
|
|
||||||
|
class BodySizeLimitMiddleware:
|
||||||
|
"""Reject API request bodies above a size limit with 413.
|
||||||
|
|
||||||
|
Checks Content-Length up front and counts streamed bytes for chunked requests.
|
||||||
|
When a stream exceeds the limit, the 413 is sent here and the app sees a disconnect.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, app: ASGIApp, max_bytes: int, path_prefix: str = "/api/") -> None:
|
||||||
|
self.app = app
|
||||||
|
self.max_bytes = max_bytes
|
||||||
|
self.path_prefix = path_prefix
|
||||||
|
|
||||||
|
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||||
|
if scope["type"] != "http" or not scope["path"].startswith(self.path_prefix):
|
||||||
|
await self.app(scope, receive, send)
|
||||||
|
return
|
||||||
|
|
||||||
|
too_large = JSONResponse({"detail": "Anfrage ist zu groß."}, 413)
|
||||||
|
content_length = Headers(scope=scope).get("content-length")
|
||||||
|
if content_length and content_length.isdigit() and int(content_length) > self.max_bytes:
|
||||||
|
await too_large(scope, receive, send)
|
||||||
|
return
|
||||||
|
|
||||||
|
received = 0
|
||||||
|
response_started = False
|
||||||
|
rejected = False
|
||||||
|
|
||||||
|
async def limited_receive() -> Message:
|
||||||
|
nonlocal received, rejected
|
||||||
|
message = await receive()
|
||||||
|
if message["type"] == "http.request":
|
||||||
|
received += len(message.get("body", b""))
|
||||||
|
if received > self.max_bytes and not response_started:
|
||||||
|
rejected = True
|
||||||
|
await too_large(scope, receive, send)
|
||||||
|
return {"type": "http.disconnect"}
|
||||||
|
return message
|
||||||
|
|
||||||
|
async def guarded_send(message: Message) -> None:
|
||||||
|
nonlocal response_started
|
||||||
|
if rejected:
|
||||||
|
return # 413 already sent
|
||||||
|
if message["type"] == "http.response.start":
|
||||||
|
response_started = True
|
||||||
|
await send(message)
|
||||||
|
|
||||||
|
await self.app(scope, limited_receive, guarded_send)
|
||||||
@@ -1,6 +1,17 @@
|
|||||||
from app.models.base import Base, UTCDateTime, utcnow
|
from app.models.base import Base, UTCDateTime, utcnow
|
||||||
|
from app.models.clip import Clip, ClipKind
|
||||||
from app.models.login_attempt import LoginAttempt
|
from app.models.login_attempt import LoginAttempt
|
||||||
from app.models.session import UserSession
|
from app.models.session import UserSession
|
||||||
from app.models.user import Role, User
|
from app.models.user import Role, User
|
||||||
|
|
||||||
__all__ = ["Base", "LoginAttempt", "Role", "UTCDateTime", "User", "UserSession", "utcnow"]
|
__all__ = [
|
||||||
|
"Base",
|
||||||
|
"Clip",
|
||||||
|
"ClipKind",
|
||||||
|
"LoginAttempt",
|
||||||
|
"Role",
|
||||||
|
"UTCDateTime",
|
||||||
|
"User",
|
||||||
|
"UserSession",
|
||||||
|
"utcnow",
|
||||||
|
]
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import enum
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import Enum, ForeignKey, Index, String, Text
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from app.models.base import Base, UTCDateTime, utcnow
|
||||||
|
|
||||||
|
|
||||||
|
class ClipKind(enum.StrEnum):
|
||||||
|
TEXT = "text"
|
||||||
|
CODE = "code"
|
||||||
|
|
||||||
|
|
||||||
|
class Clip(Base):
|
||||||
|
__tablename__ = "clips"
|
||||||
|
__table_args__ = (Index("ix_clips_user_order", "user_id", "pinned", "updated_at"),)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||||
|
kind: Mapped[ClipKind] = mapped_column(
|
||||||
|
Enum(ClipKind, native_enum=False, length=16, values_callable=lambda e: [m.value for m in e])
|
||||||
|
)
|
||||||
|
title: Mapped[str | None] = mapped_column(String(200))
|
||||||
|
content: Mapped[str] = mapped_column(Text)
|
||||||
|
language: Mapped[str | None] = mapped_column(String(32))
|
||||||
|
pinned: Mapped[bool] = mapped_column(default=False)
|
||||||
|
# Incremented on every change; clients send it back to detect concurrent edits
|
||||||
|
version: Mapped[int] = mapped_column(default=1)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
|
from app.models import ClipKind
|
||||||
|
|
||||||
|
# Hard upper bound for request parsing; the configurable limit is enforced in the service
|
||||||
|
_CONTENT_MAX = 1_000_000
|
||||||
|
|
||||||
|
|
||||||
|
class ClipCreate(BaseModel):
|
||||||
|
kind: ClipKind = ClipKind.TEXT
|
||||||
|
title: str | None = Field(default=None, max_length=1000)
|
||||||
|
content: str = Field(max_length=_CONTENT_MAX)
|
||||||
|
language: str | None = Field(default=None, max_length=32)
|
||||||
|
pinned: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class ClipUpdate(BaseModel):
|
||||||
|
"""Partial update; only fields present in the request are changed."""
|
||||||
|
|
||||||
|
kind: ClipKind | None = None
|
||||||
|
title: str | None = Field(default=None, max_length=1000)
|
||||||
|
content: str | None = Field(default=None, max_length=_CONTENT_MAX)
|
||||||
|
language: str | None = Field(default=None, max_length=32)
|
||||||
|
pinned: bool | None = None
|
||||||
|
version: int | None = Field(default=None, description="Expected version for conflict check")
|
||||||
|
|
||||||
|
|
||||||
|
class ClipOut(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: int
|
||||||
|
kind: ClipKind
|
||||||
|
title: str | None
|
||||||
|
content: str
|
||||||
|
language: str | None
|
||||||
|
pinned: bool
|
||||||
|
version: int
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class ClipList(BaseModel):
|
||||||
|
items: list[ClipOut]
|
||||||
|
total: int
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from app.models import Role
|
||||||
|
|
||||||
|
|
||||||
|
class UserCreate(BaseModel):
|
||||||
|
username: str = Field(min_length=1, max_length=64)
|
||||||
|
password: str = Field(min_length=1, max_length=1024)
|
||||||
|
role: Role = Role.USER
|
||||||
|
|
||||||
|
|
||||||
|
class UserUpdate(BaseModel):
|
||||||
|
role: Role | None = None
|
||||||
|
is_active: bool | None = None
|
||||||
|
password: str | None = Field(default=None, min_length=1, max_length=1024)
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import delete, func, select, update
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.config import get_settings
|
||||||
|
from app.languages import LANGUAGES
|
||||||
|
from app.models import Clip, ClipKind, utcnow
|
||||||
|
from app.services.users import UserError
|
||||||
|
|
||||||
|
# Changing only these fields does not count as an edit (no new updated_at)
|
||||||
|
_META_FIELDS = frozenset({"pinned"})
|
||||||
|
|
||||||
|
|
||||||
|
class ClipConflict(Exception):
|
||||||
|
"""The clip was changed elsewhere since the client loaded it."""
|
||||||
|
|
||||||
|
def __init__(self, current: Clip) -> None:
|
||||||
|
super().__init__("clip version conflict")
|
||||||
|
self.current = current
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize(kind: ClipKind, title: str | None, content: str, language: str | None):
|
||||||
|
max_chars = get_settings().clip_max_chars
|
||||||
|
if not content.strip():
|
||||||
|
raise UserError("Der Inhalt darf nicht leer sein.")
|
||||||
|
if len(content) > max_chars:
|
||||||
|
raise UserError(
|
||||||
|
f"Der Inhalt ist zu lang (höchstens {max_chars:,} Zeichen).".replace(",", ".")
|
||||||
|
)
|
||||||
|
title = (title or "").strip() or None
|
||||||
|
if title is not None and len(title) > 200:
|
||||||
|
raise UserError("Der Titel ist zu lang (höchstens 200 Zeichen).")
|
||||||
|
if kind == ClipKind.TEXT:
|
||||||
|
language = None
|
||||||
|
else:
|
||||||
|
language = language or "plaintext"
|
||||||
|
if language not in LANGUAGES:
|
||||||
|
raise UserError("Unbekannte Sprache.")
|
||||||
|
return title, language
|
||||||
|
|
||||||
|
|
||||||
|
def list_clips(db: Session, user_id: int, limit: int, offset: int) -> tuple[list[Clip], int]:
|
||||||
|
items = db.scalars(
|
||||||
|
select(Clip)
|
||||||
|
.where(Clip.user_id == user_id)
|
||||||
|
.order_by(Clip.pinned.desc(), Clip.updated_at.desc(), Clip.id.desc())
|
||||||
|
.limit(limit)
|
||||||
|
.offset(offset)
|
||||||
|
)
|
||||||
|
total = db.scalar(select(func.count()).select_from(Clip).where(Clip.user_id == user_id))
|
||||||
|
return list(items), total or 0
|
||||||
|
|
||||||
|
|
||||||
|
def get_clip(db: Session, user_id: int, clip_id: int) -> Clip | None:
|
||||||
|
return db.scalar(select(Clip).where(Clip.id == clip_id, Clip.user_id == user_id))
|
||||||
|
|
||||||
|
|
||||||
|
def create_clip(
|
||||||
|
db: Session,
|
||||||
|
user_id: int,
|
||||||
|
*,
|
||||||
|
content: str,
|
||||||
|
kind: ClipKind = ClipKind.TEXT,
|
||||||
|
title: str | None = None,
|
||||||
|
language: str | None = None,
|
||||||
|
pinned: bool = False,
|
||||||
|
) -> Clip:
|
||||||
|
title, language = _normalize(kind, title, content, language)
|
||||||
|
clip = Clip(
|
||||||
|
user_id=user_id,
|
||||||
|
kind=kind,
|
||||||
|
title=title,
|
||||||
|
content=content,
|
||||||
|
language=language,
|
||||||
|
pinned=pinned,
|
||||||
|
)
|
||||||
|
db.add(clip)
|
||||||
|
db.commit()
|
||||||
|
return clip
|
||||||
|
|
||||||
|
|
||||||
|
def update_clip(
|
||||||
|
db: Session,
|
||||||
|
user_id: int,
|
||||||
|
clip: Clip,
|
||||||
|
changes: dict[str, Any],
|
||||||
|
expected_version: int | None = None,
|
||||||
|
) -> Clip:
|
||||||
|
"""Apply a partial update. With expected_version, a concurrent change raises ClipConflict."""
|
||||||
|
kind = changes.get("kind", clip.kind)
|
||||||
|
title = changes.get("title", clip.title)
|
||||||
|
content = changes.get("content", clip.content)
|
||||||
|
language = changes.get("language", clip.language)
|
||||||
|
title, language = _normalize(kind, title, content, language)
|
||||||
|
|
||||||
|
values: dict[str, Any] = {
|
||||||
|
"kind": kind,
|
||||||
|
"title": title,
|
||||||
|
"content": content,
|
||||||
|
"language": language,
|
||||||
|
"pinned": changes.get("pinned", clip.pinned),
|
||||||
|
"version": Clip.version + 1,
|
||||||
|
}
|
||||||
|
if set(changes) - _META_FIELDS:
|
||||||
|
values["updated_at"] = utcnow()
|
||||||
|
|
||||||
|
# Conditional UPDATE keeps the version check atomic across concurrent requests
|
||||||
|
stmt = update(Clip).where(Clip.id == clip.id, Clip.user_id == user_id)
|
||||||
|
if expected_version is not None:
|
||||||
|
stmt = stmt.where(Clip.version == expected_version)
|
||||||
|
result = db.execute(stmt.values(**values).execution_options(synchronize_session=False))
|
||||||
|
if result.rowcount == 0:
|
||||||
|
db.rollback()
|
||||||
|
db.refresh(clip)
|
||||||
|
raise ClipConflict(clip)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(clip)
|
||||||
|
return clip
|
||||||
|
|
||||||
|
|
||||||
|
def delete_clip(db: Session, user_id: int, clip_id: int) -> bool:
|
||||||
|
result = db.execute(delete(Clip).where(Clip.id == clip_id, Clip.user_id == user_id))
|
||||||
|
db.commit()
|
||||||
|
return result.rowcount > 0
|
||||||
@@ -68,3 +68,66 @@ def set_password(
|
|||||||
stmt = stmt.where(UserSession.id != keep_session_id)
|
stmt = stmt.where(UserSession.id != keep_session_id)
|
||||||
db.execute(stmt)
|
db.execute(stmt)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def list_users(db: Session) -> list[User]:
|
||||||
|
return list(db.scalars(select(User).order_by(User.username)))
|
||||||
|
|
||||||
|
|
||||||
|
def _ensure_other_active_admin(db: Session, target: User) -> None:
|
||||||
|
others = db.scalar(
|
||||||
|
select(func.count())
|
||||||
|
.select_from(User)
|
||||||
|
.where(User.role == Role.ADMIN, User.is_active.is_(True), User.id != target.id)
|
||||||
|
)
|
||||||
|
if not others:
|
||||||
|
raise UserError("Es muss mindestens ein aktiver Administrator bestehen bleiben.")
|
||||||
|
|
||||||
|
|
||||||
|
def update_user(
|
||||||
|
db: Session,
|
||||||
|
actor: User,
|
||||||
|
target: User,
|
||||||
|
*,
|
||||||
|
role: Role | None = None,
|
||||||
|
is_active: bool | None = None,
|
||||||
|
password: str | None = None,
|
||||||
|
) -> User:
|
||||||
|
"""Admin change of another user; deactivation and password reset end all sessions."""
|
||||||
|
if actor.id == target.id:
|
||||||
|
raise UserError("Den eigenen Account bitte unter „Konto“ ändern.")
|
||||||
|
|
||||||
|
loses_admin = (
|
||||||
|
target.is_admin
|
||||||
|
and target.is_active
|
||||||
|
and ((role is not None and role != Role.ADMIN) or is_active is False)
|
||||||
|
)
|
||||||
|
if loses_admin:
|
||||||
|
_ensure_other_active_admin(db, target)
|
||||||
|
|
||||||
|
if role is not None:
|
||||||
|
target.role = role
|
||||||
|
if is_active is not None:
|
||||||
|
target.is_active = is_active
|
||||||
|
if password is not None:
|
||||||
|
set_password(db, target, password) # commits and revokes sessions
|
||||||
|
if is_active is False:
|
||||||
|
db.execute(delete(UserSession).where(UserSession.user_id == target.id))
|
||||||
|
db.commit()
|
||||||
|
return target
|
||||||
|
|
||||||
|
|
||||||
|
def delete_user(db: Session, actor: User, target: User) -> None:
|
||||||
|
if actor.id == target.id:
|
||||||
|
raise UserError("Der eigene Account kann nicht gelöscht werden.")
|
||||||
|
if target.is_admin and target.is_active:
|
||||||
|
_ensure_other_active_admin(db, target)
|
||||||
|
db.delete(target)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def bootstrap_initial_admin(db: Session, username: str, password: str) -> User | None:
|
||||||
|
"""Create the first admin from configuration; does nothing once any user exists."""
|
||||||
|
if count_users(db) > 0:
|
||||||
|
return None
|
||||||
|
return create_user(db, username, password, Role.ADMIN)
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.models import Role, User, UserSession
|
||||||
|
from app.services.users import UserError, delete_user, update_user
|
||||||
|
from tests.conftest import login
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def admin_client(client, make_user):
|
||||||
|
make_user("boss", Role.ADMIN)
|
||||||
|
login(client, "boss")
|
||||||
|
return client
|
||||||
|
|
||||||
|
|
||||||
|
def test_regular_user_cannot_use_admin_api(client, make_user):
|
||||||
|
make_user("anna")
|
||||||
|
login(client, "anna")
|
||||||
|
|
||||||
|
assert client.get("/api/admin/users").status_code == 403
|
||||||
|
response = client.post(
|
||||||
|
"/api/admin/users", json={"username": "evil", "password": "long enough password"}
|
||||||
|
)
|
||||||
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_admin_api_requires_login(client):
|
||||||
|
assert client.get("/api/admin/users").status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_admin_api_requires_csrf(admin_client):
|
||||||
|
del admin_client.headers["X-CSRF-Token"]
|
||||||
|
response = admin_client.post(
|
||||||
|
"/api/admin/users", json={"username": "anna", "password": "long enough password"}
|
||||||
|
)
|
||||||
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_and_list_users(admin_client):
|
||||||
|
response = admin_client.post(
|
||||||
|
"/api/admin/users", json={"username": "Anna", "password": "long enough password"}
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 201
|
||||||
|
assert response.json()["username"] == "anna"
|
||||||
|
assert response.json()["role"] == "user"
|
||||||
|
names = [u["username"] for u in admin_client.get("/api/admin/users").json()]
|
||||||
|
assert names == ["anna", "boss"]
|
||||||
|
assert "password_hash" not in response.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_user_validation_errors(admin_client):
|
||||||
|
short = admin_client.post("/api/admin/users", json={"username": "anna", "password": "x"})
|
||||||
|
bad_name = admin_client.post(
|
||||||
|
"/api/admin/users", json={"username": "a b", "password": "long enough password"}
|
||||||
|
)
|
||||||
|
duplicate = admin_client.post(
|
||||||
|
"/api/admin/users", json={"username": "BOSS", "password": "long enough password"}
|
||||||
|
)
|
||||||
|
|
||||||
|
assert short.status_code == bad_name.status_code == duplicate.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_deactivate_user_ends_sessions(admin_client, make_user, db):
|
||||||
|
anna = make_user("anna")
|
||||||
|
with TestClient(admin_client.app, base_url="https://testserver") as anna_client:
|
||||||
|
login(anna_client, "anna")
|
||||||
|
|
||||||
|
response = admin_client.patch(f"/api/admin/users/{anna.id}", json={"is_active": False})
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json()["is_active"] is False
|
||||||
|
assert anna_client.get("/api/auth/me").status_code == 401
|
||||||
|
assert db.query(UserSession).filter_by(user_id=anna.id).count() == 0
|
||||||
|
assert login(anna_client, "anna").status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_reset_password_ends_sessions(admin_client, make_user):
|
||||||
|
anna = make_user("anna")
|
||||||
|
with TestClient(admin_client.app, base_url="https://testserver") as anna_client:
|
||||||
|
login(anna_client, "anna")
|
||||||
|
|
||||||
|
admin_client.patch(f"/api/admin/users/{anna.id}", json={"password": "reset by admin!"})
|
||||||
|
|
||||||
|
assert anna_client.get("/api/auth/me").status_code == 401
|
||||||
|
assert login(anna_client, "anna", "reset by admin!").status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_promote_user(admin_client, make_user):
|
||||||
|
anna = make_user("anna")
|
||||||
|
|
||||||
|
response = admin_client.patch(f"/api/admin/users/{anna.id}", json={"role": "admin"})
|
||||||
|
|
||||||
|
assert response.json()["role"] == "admin"
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_user_cascades_sessions(admin_client, make_user, db):
|
||||||
|
anna_id = make_user("anna").id
|
||||||
|
with TestClient(admin_client.app, base_url="https://testserver") as anna_client:
|
||||||
|
login(anna_client, "anna")
|
||||||
|
|
||||||
|
assert admin_client.delete(f"/api/admin/users/{anna_id}").status_code == 204
|
||||||
|
|
||||||
|
db.expire_all()
|
||||||
|
assert db.get(User, anna_id) is None
|
||||||
|
assert db.query(UserSession).filter_by(user_id=anna_id).count() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_admin_cannot_modify_or_delete_self(admin_client, db):
|
||||||
|
boss = db.query(User).filter_by(username="boss").one()
|
||||||
|
|
||||||
|
assert (
|
||||||
|
admin_client.patch(f"/api/admin/users/{boss.id}", json={"role": "user"}).status_code == 400
|
||||||
|
)
|
||||||
|
assert admin_client.delete(f"/api/admin/users/{boss.id}").status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_user_returns_404(admin_client):
|
||||||
|
assert admin_client.get("/api/admin/users/999").status_code == 404
|
||||||
|
assert admin_client.delete("/api/admin/users/999").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_last_active_admin_is_protected(make_user, db):
|
||||||
|
boss = make_user("boss", Role.ADMIN)
|
||||||
|
other = make_user("other", Role.ADMIN)
|
||||||
|
other.is_active = False
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
# An inactive admin acting (e.g. via future tooling) must not remove the last active one
|
||||||
|
with pytest.raises(UserError):
|
||||||
|
update_user(db, other, boss, role=Role.USER)
|
||||||
|
with pytest.raises(UserError):
|
||||||
|
update_user(db, other, boss, is_active=False)
|
||||||
|
with pytest.raises(UserError):
|
||||||
|
delete_user(db, other, boss)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def initial_admin_env(monkeypatch, app_env):
|
||||||
|
from app.config import get_settings
|
||||||
|
|
||||||
|
monkeypatch.setenv("INITIAL_ADMIN_USERNAME", "root-admin")
|
||||||
|
monkeypatch.setenv("INITIAL_ADMIN_PASSWORD", "initial admin password")
|
||||||
|
get_settings.cache_clear()
|
||||||
|
|
||||||
|
|
||||||
|
def test_initial_admin_created_from_env(initial_admin_env, client, db):
|
||||||
|
user = db.query(User).one()
|
||||||
|
assert user.username == "root-admin"
|
||||||
|
assert user.role == Role.ADMIN
|
||||||
|
assert login(client, "root-admin", "initial admin password").status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_initial_admin_ignored_when_users_exist(initial_admin_env, make_user, db):
|
||||||
|
from app.main import _bootstrap_admin
|
||||||
|
|
||||||
|
make_user("anna")
|
||||||
|
_bootstrap_admin()
|
||||||
|
|
||||||
|
assert [u.username for u in db.query(User).all()] == ["anna"]
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.config import get_settings
|
||||||
|
from app.models import Clip, Role, utcnow
|
||||||
|
from tests.conftest import login
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def anna(client, make_user):
|
||||||
|
make_user("anna")
|
||||||
|
login(client, "anna")
|
||||||
|
return client
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def bert(client, make_user):
|
||||||
|
"""Second logged-in user with own client, for data separation tests."""
|
||||||
|
make_user("bert")
|
||||||
|
with TestClient(client.app, base_url="https://testserver") as other:
|
||||||
|
login(other, "bert")
|
||||||
|
yield other
|
||||||
|
|
||||||
|
|
||||||
|
def create(c, **fields):
|
||||||
|
response = c.post("/api/clips", json={"content": "hello", **fields})
|
||||||
|
assert response.status_code == 201, response.text
|
||||||
|
return response.json()
|
||||||
|
|
||||||
|
|
||||||
|
# --- CRUD -----------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_text_clip(anna):
|
||||||
|
clip = create(anna, content="Some text", title=" Note ")
|
||||||
|
|
||||||
|
assert clip["kind"] == "text"
|
||||||
|
assert clip["title"] == "Note"
|
||||||
|
assert clip["language"] is None
|
||||||
|
assert clip["pinned"] is False
|
||||||
|
assert clip["version"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_code_clip_defaults_to_plaintext(anna):
|
||||||
|
assert create(anna, kind="code")["language"] == "plaintext"
|
||||||
|
assert create(anna, kind="code", language="python")["language"] == "python"
|
||||||
|
|
||||||
|
|
||||||
|
def test_text_clip_drops_language(anna):
|
||||||
|
assert create(anna, kind="text", language="python")["language"] is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"fields",
|
||||||
|
[
|
||||||
|
{"content": " "},
|
||||||
|
{"content": "x", "kind": "code", "language": "brainfuck"},
|
||||||
|
{"content": "x", "title": "t" * 201},
|
||||||
|
{"content": "x", "kind": "image"},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_create_validation(anna, fields):
|
||||||
|
assert anna.post("/api/clips", json=fields).status_code in (400, 422)
|
||||||
|
|
||||||
|
|
||||||
|
def test_content_limit_is_configurable(anna, monkeypatch):
|
||||||
|
monkeypatch.setenv("CLIP_MAX_CHARS", "10")
|
||||||
|
get_settings.cache_clear()
|
||||||
|
|
||||||
|
assert anna.post("/api/clips", json={"content": "x" * 10}).status_code == 201
|
||||||
|
response = anna.post("/api/clips", json={"content": "x" * 11})
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert "zu lang" in response.json()["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_orders_pinned_first_then_recent(anna, db):
|
||||||
|
old = create(anna, content="old")
|
||||||
|
pinned = create(anna, content="pinned", pinned=True)
|
||||||
|
new = create(anna, content="new")
|
||||||
|
db.query(Clip).filter_by(id=old["id"]).update({Clip.updated_at: utcnow() - timedelta(days=1)})
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
data = anna.get("/api/clips").json()
|
||||||
|
|
||||||
|
assert [c["id"] for c in data["items"]] == [pinned["id"], new["id"], old["id"]]
|
||||||
|
assert data["total"] == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_pagination(anna):
|
||||||
|
for i in range(5):
|
||||||
|
create(anna, content=f"clip {i}")
|
||||||
|
|
||||||
|
page = anna.get("/api/clips", params={"limit": 2, "offset": 2}).json()
|
||||||
|
|
||||||
|
assert len(page["items"]) == 2
|
||||||
|
assert page["total"] == 5
|
||||||
|
assert anna.get("/api/clips", params={"limit": 101}).status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_update_delete(anna):
|
||||||
|
clip = create(anna)
|
||||||
|
|
||||||
|
assert anna.get(f"/api/clips/{clip['id']}").json()["content"] == "hello"
|
||||||
|
|
||||||
|
updated = anna.patch(
|
||||||
|
f"/api/clips/{clip['id']}",
|
||||||
|
json={"content": "print(1)", "kind": "code", "language": "python"},
|
||||||
|
).json()
|
||||||
|
assert updated["content"] == "print(1)"
|
||||||
|
assert updated["language"] == "python"
|
||||||
|
assert updated["version"] == 2
|
||||||
|
|
||||||
|
assert anna.delete(f"/api/clips/{clip['id']}").status_code == 204
|
||||||
|
assert anna.get(f"/api/clips/{clip['id']}").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_patch_only_changes_given_fields(anna):
|
||||||
|
clip = create(anna, title="Keep", kind="code", language="go")
|
||||||
|
|
||||||
|
updated = anna.patch(f"/api/clips/{clip['id']}", json={"content": "new"}).json()
|
||||||
|
|
||||||
|
assert updated["title"] == "Keep"
|
||||||
|
assert updated["language"] == "go"
|
||||||
|
|
||||||
|
|
||||||
|
def test_patch_can_clear_title(anna):
|
||||||
|
clip = create(anna, title="Remove me")
|
||||||
|
|
||||||
|
assert anna.patch(f"/api/clips/{clip['id']}", json={"title": None}).json()["title"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_pinning_does_not_count_as_edit(anna):
|
||||||
|
clip = create(anna)
|
||||||
|
|
||||||
|
pinned = anna.patch(f"/api/clips/{clip['id']}", json={"pinned": True}).json()
|
||||||
|
|
||||||
|
assert pinned["pinned"] is True
|
||||||
|
assert pinned["updated_at"] == clip["updated_at"]
|
||||||
|
assert pinned["version"] == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_version_conflict(anna):
|
||||||
|
clip = create(anna)
|
||||||
|
anna.patch(f"/api/clips/{clip['id']}", json={"content": "from phone", "version": 1})
|
||||||
|
|
||||||
|
response = anna.patch(f"/api/clips/{clip['id']}", json={"content": "from laptop", "version": 1})
|
||||||
|
|
||||||
|
assert response.status_code == 409
|
||||||
|
assert response.json()["current"]["content"] == "from phone"
|
||||||
|
assert response.json()["current"]["version"] == 2
|
||||||
|
assert anna.get(f"/api/clips/{clip['id']}").json()["content"] == "from phone"
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_without_version_overwrites(anna):
|
||||||
|
clip = create(anna)
|
||||||
|
anna.patch(f"/api/clips/{clip['id']}", json={"content": "first"})
|
||||||
|
|
||||||
|
response = anna.patch(f"/api/clips/{clip['id']}", json={"content": "second"})
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json()["version"] == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_clips_require_login(client):
|
||||||
|
assert client.get("/api/clips").status_code == 401
|
||||||
|
assert client.post("/api/clips", json={"content": "x"}).status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_clip_changes_require_csrf(anna):
|
||||||
|
clip = create(anna)
|
||||||
|
del anna.headers["X-CSRF-Token"]
|
||||||
|
|
||||||
|
assert anna.post("/api/clips", json={"content": "x"}).status_code == 403
|
||||||
|
assert anna.patch(f"/api/clips/{clip['id']}", json={"pinned": True}).status_code == 403
|
||||||
|
assert anna.delete(f"/api/clips/{clip['id']}").status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
# --- Data separation ------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_only_shows_own_clips(anna, bert):
|
||||||
|
create(anna, content="anna's secret")
|
||||||
|
create(bert, content="bert's clip")
|
||||||
|
|
||||||
|
anna_items = anna.get("/api/clips").json()
|
||||||
|
bert_items = bert.get("/api/clips").json()
|
||||||
|
|
||||||
|
assert [c["content"] for c in anna_items["items"]] == ["anna's secret"]
|
||||||
|
assert [c["content"] for c in bert_items["items"]] == ["bert's clip"]
|
||||||
|
assert anna_items["total"] == bert_items["total"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_foreign_clip_is_indistinguishable_from_missing(anna, bert):
|
||||||
|
clip_id = create(anna, content="anna's secret")["id"]
|
||||||
|
|
||||||
|
for response in (
|
||||||
|
bert.get(f"/api/clips/{clip_id}"),
|
||||||
|
bert.patch(f"/api/clips/{clip_id}", json={"content": "hacked"}),
|
||||||
|
bert.delete(f"/api/clips/{clip_id}"),
|
||||||
|
):
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert response.json() == bert.get("/api/clips/999999").json()
|
||||||
|
|
||||||
|
assert anna.get(f"/api/clips/{clip_id}").json()["content"] == "anna's secret"
|
||||||
|
|
||||||
|
|
||||||
|
def test_admin_cannot_read_other_users_clips(client, make_user):
|
||||||
|
make_user("boss", Role.ADMIN)
|
||||||
|
make_user("anna")
|
||||||
|
login(client, "anna")
|
||||||
|
clip_id = create(client, content="private")["id"]
|
||||||
|
client.post("/api/auth/logout")
|
||||||
|
|
||||||
|
login(client, "boss")
|
||||||
|
|
||||||
|
assert client.get(f"/api/clips/{clip_id}").status_code == 404
|
||||||
|
assert client.get("/api/clips").json()["total"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_deleting_user_deletes_their_clips(client, make_user, db):
|
||||||
|
make_user("boss", Role.ADMIN)
|
||||||
|
anna = make_user("anna")
|
||||||
|
anna_id = anna.id
|
||||||
|
with TestClient(client.app, base_url="https://testserver") as anna_client:
|
||||||
|
login(anna_client, "anna")
|
||||||
|
create(anna_client, content="bye")
|
||||||
|
|
||||||
|
login(client, "boss")
|
||||||
|
client.delete(f"/api/admin/users/{anna_id}")
|
||||||
|
|
||||||
|
db.expire_all()
|
||||||
|
assert db.query(Clip).filter_by(user_id=anna_id).count() == 0
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.config import get_settings
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def spa(static_dir):
|
||||||
|
(static_dir / "index.html").write_text("<html>spa</html>")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"path", ["/.env", "/root/.env", "/wp-login.php", "/config.json", "/.git/config"]
|
||||||
|
)
|
||||||
|
def test_file_like_paths_return_404(spa, client, path):
|
||||||
|
response = client.get(path)
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert "spa" not in response.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_app_routes_still_fall_back_to_index(spa, client):
|
||||||
|
assert client.get("/clips/42").status_code == 200
|
||||||
|
assert client.get("/admin/users").status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_security_headers_on_api_and_spa(spa, client):
|
||||||
|
for path in ("/api/health", "/", "/does-not-exist.php"):
|
||||||
|
headers = client.get(path).headers
|
||||||
|
assert "default-src 'self'" in headers["content-security-policy"]
|
||||||
|
assert "frame-ancestors 'none'" in headers["content-security-policy"]
|
||||||
|
assert headers["x-content-type-options"] == "nosniff"
|
||||||
|
assert headers["x-frame-options"] == "DENY"
|
||||||
|
assert headers["referrer-policy"] == "same-origin"
|
||||||
|
|
||||||
|
|
||||||
|
def test_hsts_only_over_https(client, app_env):
|
||||||
|
assert client.get("/api/health").headers["strict-transport-security"] == "max-age=31536000"
|
||||||
|
|
||||||
|
with TestClient(client.app, base_url="http://testserver") as plain:
|
||||||
|
assert "strict-transport-security" not in plain.get("/api/health").headers
|
||||||
|
|
||||||
|
|
||||||
|
def test_security_headers_on_rejected_requests(client):
|
||||||
|
response = client.post("/api/auth/logout", headers={"Origin": "https://evil.example"})
|
||||||
|
assert response.status_code == 403
|
||||||
|
assert "content-security-policy" in response.headers
|
||||||
|
|
||||||
|
|
||||||
|
def test_api_docs_disabled_by_default(client):
|
||||||
|
assert client.get("/api/docs").status_code == 404
|
||||||
|
assert client.get("/api/openapi.json").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_api_docs_can_be_enabled(app_env, monkeypatch):
|
||||||
|
monkeypatch.setenv("ENABLE_API_DOCS", "true")
|
||||||
|
get_settings.cache_clear()
|
||||||
|
from app.main import create_app
|
||||||
|
|
||||||
|
with TestClient(create_app(), base_url="https://testserver") as client:
|
||||||
|
assert client.get("/api/openapi.json").status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_oversized_request_is_rejected(client):
|
||||||
|
body = b'{"username": "' + b"a" * (1024 * 1024) + b'", "password": "x"}'
|
||||||
|
response = client.post(
|
||||||
|
"/api/auth/login", content=body, headers={"Content-Type": "application/json"}
|
||||||
|
)
|
||||||
|
assert response.status_code == 413
|
||||||
|
|
||||||
|
|
||||||
|
def test_oversized_chunked_request_is_rejected(client):
|
||||||
|
def chunks():
|
||||||
|
for _ in range(20):
|
||||||
|
yield b"a" * 100_000
|
||||||
|
|
||||||
|
response = client.post(
|
||||||
|
"/api/auth/login", content=chunks(), headers={"Content-Type": "application/json"}
|
||||||
|
)
|
||||||
|
assert response.status_code == 413
|
||||||
|
|
||||||
|
|
||||||
|
def test_normal_requests_pass_size_limit(client):
|
||||||
|
response = client.post("/api/auth/login", json={"username": "x", "password": "y"})
|
||||||
|
assert response.status_code == 401
|
||||||
+2
-4
@@ -8,10 +8,8 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
ports:
|
ports:
|
||||||
- "${BIND_IP:?BIND_IP must be set in .env}:${APP_PORT:-8085}:8000"
|
- "${BIND_IP:?BIND_IP must be set in .env}:${APP_PORT:-8085}:8000"
|
||||||
environment:
|
# All app settings come from .env (see .env.example)
|
||||||
FORWARDED_ALLOW_IPS: ${FORWARDED_ALLOW_IPS:-127.0.0.1}
|
env_file: .env
|
||||||
LOG_LEVEL: ${LOG_LEVEL:-info}
|
|
||||||
TZ: ${TZ:-Europe/Berlin}
|
|
||||||
volumes:
|
volumes:
|
||||||
- ./data:/data
|
- ./data:/data
|
||||||
security_opt:
|
security_opt:
|
||||||
|
|||||||
Generated
+10
@@ -8,6 +8,7 @@
|
|||||||
"name": "lan-clipboard-frontend",
|
"name": "lan-clipboard-frontend",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"highlight.js": "^11.12.0",
|
||||||
"pinia": "^4.1.0",
|
"pinia": "^4.1.0",
|
||||||
"vue": "^3.5.44",
|
"vue": "^3.5.44",
|
||||||
"vue-router": "^5.4.0"
|
"vue-router": "^5.4.0"
|
||||||
@@ -2030,6 +2031,15 @@
|
|||||||
"node": ">=20"
|
"node": ">=20"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/highlight.js": {
|
||||||
|
"version": "11.12.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.12.0.tgz",
|
||||||
|
"integrity": "sha512-nbfWpyRMcMrPMmDwJB+dhX/eiaPKtc2RB+0QZskqJ3WjRA/FDS0e9hZrx8EC/lbEv8gXy98FcDbNa/dspAaJMg==",
|
||||||
|
"license": "BSD-3-Clause",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/hookable": {
|
"node_modules/hookable": {
|
||||||
"version": "5.5.3",
|
"version": "5.5.3",
|
||||||
"resolved": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz",
|
"resolved": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz",
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
"format:check": "prettier --check src/"
|
"format:check": "prettier --check src/"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"highlight.js": "^11.12.0",
|
||||||
"pinia": "^4.1.0",
|
"pinia": "^4.1.0",
|
||||||
"vue": "^3.5.44",
|
"vue": "^3.5.44",
|
||||||
"vue-router": "^5.4.0"
|
"vue-router": "^5.4.0"
|
||||||
|
|||||||
@@ -1,7 +1,13 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { RouterView } from 'vue-router'
|
import { RouterView } from 'vue-router'
|
||||||
|
|
||||||
|
import AppHeader from '@/components/AppHeader.vue'
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
|
||||||
|
const auth = useAuthStore()
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
<AppHeader v-if="auth.user" />
|
||||||
<RouterView />
|
<RouterView />
|
||||||
</template>
|
</template>
|
||||||
@@ -2,18 +2,63 @@ export class ApiError extends Error {
|
|||||||
constructor(
|
constructor(
|
||||||
public readonly status: number,
|
public readonly status: number,
|
||||||
message: string,
|
message: string,
|
||||||
|
/** Parsed JSON body of the error response, if any */
|
||||||
|
public readonly data: unknown = null,
|
||||||
) {
|
) {
|
||||||
super(message)
|
super(message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function apiGet<T>(path: string): Promise<T> {
|
type UnauthorizedHandler = () => void
|
||||||
const response = await fetch(`/api${path}`, {
|
|
||||||
credentials: 'same-origin',
|
let onUnauthorized: UnauthorizedHandler | null = null
|
||||||
headers: { Accept: 'application/json' },
|
|
||||||
})
|
/** Called on 401 responses (except for the login request itself). */
|
||||||
if (!response.ok) {
|
export function setUnauthorizedHandler(handler: UnauthorizedHandler): void {
|
||||||
throw new ApiError(response.status, `${response.status} ${response.statusText}`)
|
onUnauthorized = handler
|
||||||
|
}
|
||||||
|
|
||||||
|
function readCookie(name: string): string | null {
|
||||||
|
const match = document.cookie.split('; ').find((c) => c.startsWith(`${name}=`))
|
||||||
|
return match ? decodeURIComponent(match.slice(name.length + 1)) : null
|
||||||
|
}
|
||||||
|
|
||||||
|
function errorMessage(response: Response, data: unknown): string {
|
||||||
|
if (data && typeof data === 'object' && 'detail' in data) {
|
||||||
|
const detail = (data as { detail: unknown }).detail
|
||||||
|
if (typeof detail === 'string') return detail
|
||||||
|
if (Array.isArray(detail)) return 'Ungültige Eingabe.'
|
||||||
}
|
}
|
||||||
|
return `${response.status} ${response.statusText}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function apiRequest<T>(method: string, path: string, body?: unknown): Promise<T> {
|
||||||
|
const headers: Record<string, string> = { Accept: 'application/json' }
|
||||||
|
if (body !== undefined) headers['Content-Type'] = 'application/json'
|
||||||
|
if (method !== 'GET') {
|
||||||
|
const csrf = readCookie('lc_csrf')
|
||||||
|
if (csrf) headers['X-CSRF-Token'] = csrf
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(`/api${path}`, {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
credentials: 'same-origin',
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
if (response.status === 401 && path !== '/auth/login') onUnauthorized?.()
|
||||||
|
const data: unknown = await response.json().catch(() => null)
|
||||||
|
throw new ApiError(response.status, errorMessage(response, data), data)
|
||||||
|
}
|
||||||
|
if (response.status === 204) return undefined as T
|
||||||
return (await response.json()) as T
|
return (await response.json()) as T
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const api = {
|
||||||
|
get: <T>(path: string) => apiRequest<T>('GET', path),
|
||||||
|
post: <T>(path: string, body?: unknown) => apiRequest<T>('POST', path, body),
|
||||||
|
patch: <T>(path: string, body?: unknown) => apiRequest<T>('PATCH', path, body),
|
||||||
|
delete: <T>(path: string) => apiRequest<T>('DELETE', path),
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
export type Role = 'admin' | 'user'
|
||||||
|
|
||||||
|
export interface User {
|
||||||
|
id: number
|
||||||
|
username: string
|
||||||
|
role: Role
|
||||||
|
is_active: boolean
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SessionInfo {
|
||||||
|
id: number
|
||||||
|
created_at: string
|
||||||
|
last_seen_at: string
|
||||||
|
expires_at: string
|
||||||
|
ip: string | null
|
||||||
|
user_agent: string | null
|
||||||
|
current: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ClipKind = 'text' | 'code'
|
||||||
|
|
||||||
|
export interface Clip {
|
||||||
|
id: number
|
||||||
|
kind: ClipKind
|
||||||
|
title: string | null
|
||||||
|
content: string
|
||||||
|
language: string | null
|
||||||
|
pinned: boolean
|
||||||
|
version: number
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ClipList {
|
||||||
|
items: Clip[]
|
||||||
|
total: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ClipInput = Partial<Pick<Clip, 'kind' | 'title' | 'content' | 'language' | 'pinned'>>
|
||||||
@@ -36,3 +36,182 @@ body {
|
|||||||
padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom)
|
padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom)
|
||||||
env(safe-area-inset-left);
|
env(safe-area-inset-left);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* --- Shared building blocks ------------------------------------------------ */
|
||||||
|
|
||||||
|
.page {
|
||||||
|
max-width: 48rem;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 1.25rem 1rem 3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page > h1 {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
padding: 1rem 1.25rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card > h2 {
|
||||||
|
font-size: 1.1rem;
|
||||||
|
margin: 0 0 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form label {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.25rem;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
input,
|
||||||
|
select {
|
||||||
|
min-height: 44px;
|
||||||
|
width: 100%;
|
||||||
|
padding: 0 0.75rem;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
/* 16px prevents iOS Safari from zooming into focused inputs */
|
||||||
|
font: inherit;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
input:focus,
|
||||||
|
select:focus {
|
||||||
|
outline: 2px solid var(--accent);
|
||||||
|
outline-offset: 1px;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
min-height: 44px;
|
||||||
|
padding: 0 1rem;
|
||||||
|
border: 1px solid var(--accent);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: transparent;
|
||||||
|
color: var(--accent);
|
||||||
|
font: inherit;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
button.primary {
|
||||||
|
background: var(--accent);
|
||||||
|
color: var(--bg);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
button.danger {
|
||||||
|
border-color: var(--error);
|
||||||
|
color: var(--error);
|
||||||
|
}
|
||||||
|
|
||||||
|
button.small {
|
||||||
|
min-height: 36px;
|
||||||
|
padding: 0 0.75rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ok {
|
||||||
|
color: var(--ok);
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
color: var(--error);
|
||||||
|
}
|
||||||
|
|
||||||
|
.muted {
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.badge {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 0 0.5rem;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 999px;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.badge.accent {
|
||||||
|
border-color: var(--accent);
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea {
|
||||||
|
width: 100%;
|
||||||
|
min-height: 6rem;
|
||||||
|
padding: 0.75rem;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
font: inherit;
|
||||||
|
font-size: 16px;
|
||||||
|
line-height: 1.45;
|
||||||
|
resize: vertical;
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea:focus {
|
||||||
|
outline: 2px solid var(--accent);
|
||||||
|
outline-offset: 1px;
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea.mono,
|
||||||
|
pre,
|
||||||
|
code {
|
||||||
|
font-family: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, Consolas, monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Link that looks like a button */
|
||||||
|
.button-link {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
min-height: 44px;
|
||||||
|
padding: 0 1rem;
|
||||||
|
border: 1px solid var(--accent);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
color: var(--accent);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.button-link.small {
|
||||||
|
min-height: 36px;
|
||||||
|
padding: 0 0.75rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Two-option toggle */
|
||||||
|
.segmented {
|
||||||
|
display: inline-flex;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.segmented button {
|
||||||
|
border: none;
|
||||||
|
border-radius: 0;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.segmented button.active {
|
||||||
|
background: var(--accent);
|
||||||
|
color: var(--bg);
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { RouterLink, useRouter } from 'vue-router'
|
||||||
|
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
|
||||||
|
const auth = useAuthStore()
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
|
async function logout(): Promise<void> {
|
||||||
|
await auth.logout()
|
||||||
|
await router.push({ name: 'login' })
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<header class="header">
|
||||||
|
<RouterLink to="/" class="brand">LAN-Clipboard</RouterLink>
|
||||||
|
<nav class="nav">
|
||||||
|
<RouterLink to="/account">Konto</RouterLink>
|
||||||
|
<RouterLink v-if="auth.isAdmin" to="/admin/users">Benutzer</RouterLink>
|
||||||
|
<button type="button" class="small" @click="logout">Abmelden</button>
|
||||||
|
</nav>
|
||||||
|
</header>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.header {
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
z-index: 10;
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 0.5rem 1rem;
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
background: var(--surface);
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand {
|
||||||
|
color: var(--text);
|
||||||
|
font-weight: 700;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav a {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
min-height: 44px;
|
||||||
|
padding: 0 0.75rem;
|
||||||
|
border-radius: var(--radius);
|
||||||
|
color: var(--muted);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav a.router-link-active {
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { RouterLink } from 'vue-router'
|
||||||
|
|
||||||
|
import type { Clip } from '@/api/types'
|
||||||
|
import CopyButton from '@/components/CopyButton.vue'
|
||||||
|
import { formatDateTime } from '@/utils/format'
|
||||||
|
import { highlight, languageLabel } from '@/utils/highlight'
|
||||||
|
|
||||||
|
const props = defineProps<{ clip: Clip }>()
|
||||||
|
const emit = defineEmits<{ togglePin: []; remove: [] }>()
|
||||||
|
|
||||||
|
const PREVIEW_LINES = 10
|
||||||
|
const PREVIEW_CHARS = 2000
|
||||||
|
|
||||||
|
const expanded = ref(false)
|
||||||
|
|
||||||
|
const lines = computed(() => props.clip.content.split('\n'))
|
||||||
|
const isLong = computed(
|
||||||
|
() => lines.value.length > PREVIEW_LINES || props.clip.content.length > PREVIEW_CHARS,
|
||||||
|
)
|
||||||
|
const visibleText = computed(() =>
|
||||||
|
expanded.value || !isLong.value
|
||||||
|
? props.clip.content
|
||||||
|
: lines.value.slice(0, PREVIEW_LINES).join('\n').slice(0, PREVIEW_CHARS),
|
||||||
|
)
|
||||||
|
// Highlight only what is visible; large clips stay cheap until expanded
|
||||||
|
const html = computed(() =>
|
||||||
|
props.clip.kind === 'code' ? highlight(visibleText.value, props.clip.language) : null,
|
||||||
|
)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<article class="card clip" :class="{ pinned: clip.pinned }">
|
||||||
|
<header class="clip-head">
|
||||||
|
<div class="clip-meta">
|
||||||
|
<strong v-if="clip.title" class="clip-title">{{ clip.title }}</strong>
|
||||||
|
<span v-if="clip.pinned" class="badge accent">angeheftet</span>
|
||||||
|
<span v-if="clip.kind === 'code'" class="badge">{{ languageLabel(clip.language) }}</span>
|
||||||
|
</div>
|
||||||
|
<span class="muted small">{{ formatDateTime(clip.updated_at) }}</span>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<!-- eslint-disable-next-line vue/no-v-html -- highlight.js output is escaped -->
|
||||||
|
<pre v-if="html !== null" class="content code"><code class="hljs" v-html="html"></code></pre>
|
||||||
|
<pre v-else class="content text">{{ visibleText }}</pre>
|
||||||
|
|
||||||
|
<button v-if="isLong" type="button" class="link" @click="expanded = !expanded">
|
||||||
|
{{ expanded ? 'weniger' : `mehr (${lines.length} Zeilen)` }}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<footer class="actions">
|
||||||
|
<CopyButton :text="clip.content" />
|
||||||
|
<RouterLink :to="`/clips/${clip.id}`" class="button-link small">Bearbeiten</RouterLink>
|
||||||
|
<button type="button" class="small" @click="emit('togglePin')">
|
||||||
|
{{ clip.pinned ? 'Lösen' : 'Anheften' }}
|
||||||
|
</button>
|
||||||
|
<button type="button" class="small danger" @click="emit('remove')">Löschen</button>
|
||||||
|
</footer>
|
||||||
|
</article>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.clip.pinned {
|
||||||
|
border-color: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.clip-head {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: baseline;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 0.25rem 1rem;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.clip-meta {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.clip-title {
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
.small {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.content {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0.75rem;
|
||||||
|
border-radius: calc(var(--radius) - 4px);
|
||||||
|
background: var(--bg);
|
||||||
|
overflow-x: auto;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
|
||||||
|
.content.text {
|
||||||
|
white-space: pre-wrap;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
font-family: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
.content code.hljs {
|
||||||
|
padding: 0;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.link {
|
||||||
|
min-height: 32px;
|
||||||
|
padding: 0;
|
||||||
|
border: none;
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.5rem;
|
||||||
|
margin-top: 0.75rem;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
import { copyText } from '@/utils/clipboard'
|
||||||
|
|
||||||
|
const props = defineProps<{ text: string }>()
|
||||||
|
|
||||||
|
const state = ref<'idle' | 'copied' | 'failed'>('idle')
|
||||||
|
let timer: ReturnType<typeof setTimeout> | undefined
|
||||||
|
|
||||||
|
async function copy(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await copyText(props.text)
|
||||||
|
state.value = 'copied'
|
||||||
|
} catch {
|
||||||
|
state.value = 'failed'
|
||||||
|
}
|
||||||
|
clearTimeout(timer)
|
||||||
|
timer = setTimeout(() => (state.value = 'idle'), 1500)
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<button type="button" class="primary small copy" :class="state" @click="copy">
|
||||||
|
{{ state === 'copied' ? 'Kopiert ✓' : state === 'failed' ? 'Fehlgeschlagen' : 'Kopieren' }}
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.copy {
|
||||||
|
min-width: 7.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.copy.copied {
|
||||||
|
background: var(--ok);
|
||||||
|
border-color: var(--ok);
|
||||||
|
}
|
||||||
|
|
||||||
|
.copy.failed {
|
||||||
|
background: var(--error);
|
||||||
|
border-color: var(--error);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref, watch } from 'vue'
|
||||||
|
|
||||||
|
import type { ClipKind } from '@/api/types'
|
||||||
|
import { useClipsStore } from '@/stores/clips'
|
||||||
|
import { readClipboardText } from '@/utils/clipboard'
|
||||||
|
import { detectLanguage, LANGUAGES } from '@/utils/highlight'
|
||||||
|
|
||||||
|
const store = useClipsStore()
|
||||||
|
|
||||||
|
const content = ref('')
|
||||||
|
const kind = ref<ClipKind>('text')
|
||||||
|
const language = ref<string>('plaintext')
|
||||||
|
const languageTouched = ref(false)
|
||||||
|
const busy = ref(false)
|
||||||
|
const error = ref<string | null>(null)
|
||||||
|
|
||||||
|
const canSave = computed(() => content.value.trim().length > 0 && !busy.value)
|
||||||
|
|
||||||
|
// Suggest a language while typing until the user picks one
|
||||||
|
watch([content, kind], () => {
|
||||||
|
if (kind.value !== 'code' || languageTouched.value) return
|
||||||
|
language.value = detectLanguage(content.value) ?? 'plaintext'
|
||||||
|
})
|
||||||
|
|
||||||
|
async function paste(): Promise<void> {
|
||||||
|
error.value = null
|
||||||
|
try {
|
||||||
|
const text = await readClipboardText()
|
||||||
|
content.value = text
|
||||||
|
if (!languageTouched.value && detectLanguage(text)) kind.value = 'code'
|
||||||
|
} catch (e) {
|
||||||
|
error.value = e instanceof Error ? e.message : String(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save(): Promise<void> {
|
||||||
|
if (!canSave.value) return
|
||||||
|
busy.value = true
|
||||||
|
error.value = null
|
||||||
|
try {
|
||||||
|
await store.create({
|
||||||
|
content: content.value,
|
||||||
|
kind: kind.value,
|
||||||
|
language: kind.value === 'code' ? language.value : null,
|
||||||
|
})
|
||||||
|
content.value = ''
|
||||||
|
kind.value = 'text'
|
||||||
|
languageTouched.value = false
|
||||||
|
} catch (e) {
|
||||||
|
error.value = e instanceof Error ? e.message : String(e)
|
||||||
|
} finally {
|
||||||
|
busy.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<form class="card quick-add" @submit.prevent="save">
|
||||||
|
<textarea
|
||||||
|
v-model="content"
|
||||||
|
:class="{ mono: kind === 'code' }"
|
||||||
|
rows="4"
|
||||||
|
placeholder="Text oder Code einfügen …"
|
||||||
|
autocapitalize="off"
|
||||||
|
spellcheck="false"
|
||||||
|
@keydown.enter.ctrl.prevent="save"
|
||||||
|
@keydown.enter.meta.prevent="save"
|
||||||
|
></textarea>
|
||||||
|
<div class="row">
|
||||||
|
<div class="segmented" role="radiogroup" aria-label="Art">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="radio"
|
||||||
|
:aria-checked="kind === 'text'"
|
||||||
|
:class="{ active: kind === 'text' }"
|
||||||
|
@click="kind = 'text'"
|
||||||
|
>
|
||||||
|
Text
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="radio"
|
||||||
|
:aria-checked="kind === 'code'"
|
||||||
|
:class="{ active: kind === 'code' }"
|
||||||
|
@click="kind = 'code'"
|
||||||
|
>
|
||||||
|
Code
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<select
|
||||||
|
v-if="kind === 'code'"
|
||||||
|
v-model="language"
|
||||||
|
aria-label="Sprache"
|
||||||
|
class="language"
|
||||||
|
@change="languageTouched = true"
|
||||||
|
>
|
||||||
|
<option v-for="l in LANGUAGES" :key="l.id" :value="l.id">{{ l.label }}</option>
|
||||||
|
</select>
|
||||||
|
<div class="spacer"></div>
|
||||||
|
<button type="button" @click="paste">Einfügen</button>
|
||||||
|
<button type="submit" class="primary" :disabled="!canSave">Speichern</button>
|
||||||
|
</div>
|
||||||
|
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||||
|
</form>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.quick-add {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.row {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.spacer {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.language {
|
||||||
|
width: auto;
|
||||||
|
min-width: 9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted } from 'vue'
|
||||||
|
|
||||||
|
import { useHealthStore } from '@/stores/health'
|
||||||
|
|
||||||
|
const store = useHealthStore()
|
||||||
|
|
||||||
|
onMounted(store.refresh)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section class="card">
|
||||||
|
<h2>Systemstatus</h2>
|
||||||
|
<p v-if="store.loading" class="muted">Prüfe …</p>
|
||||||
|
<p v-else-if="store.error" class="error">Backend nicht erreichbar: {{ store.error }}</p>
|
||||||
|
<dl v-else-if="store.health">
|
||||||
|
<dt>Status</dt>
|
||||||
|
<dd :class="store.health.status">{{ store.health.status }}</dd>
|
||||||
|
<dt>Datenbank</dt>
|
||||||
|
<dd :class="store.health.db">{{ store.health.db }}</dd>
|
||||||
|
<dt>Version</dt>
|
||||||
|
<dd>{{ store.health.version }}</dd>
|
||||||
|
</dl>
|
||||||
|
<button type="button" :disabled="store.loading" @click="store.refresh">Aktualisieren</button>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
dl {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: max-content 1fr;
|
||||||
|
gap: 0.25rem 1rem;
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
dt {
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
dd {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,14 +1,25 @@
|
|||||||
|
import 'highlight.js/styles/github-dark.css'
|
||||||
import './assets/main.css'
|
import './assets/main.css'
|
||||||
|
|
||||||
import { createPinia } from 'pinia'
|
import { createPinia } from 'pinia'
|
||||||
import { createApp } from 'vue'
|
import { createApp } from 'vue'
|
||||||
|
|
||||||
|
import { setUnauthorizedHandler } from './api/client'
|
||||||
import App from './App.vue'
|
import App from './App.vue'
|
||||||
import router from './router'
|
import router from './router'
|
||||||
|
import { useAuthStore } from './stores/auth'
|
||||||
|
|
||||||
const app = createApp(App)
|
const app = createApp(App)
|
||||||
|
|
||||||
app.use(createPinia())
|
app.use(createPinia())
|
||||||
app.use(router)
|
app.use(router)
|
||||||
|
|
||||||
|
// Session expired or revoked elsewhere: drop local state and go to the login page
|
||||||
|
setUnauthorizedHandler(() => {
|
||||||
|
useAuthStore().clear()
|
||||||
|
if (router.currentRoute.value.name !== 'login') {
|
||||||
|
void router.push({ name: 'login', query: { redirect: router.currentRoute.value.fullPath } })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
app.mount('#app')
|
app.mount('#app')
|
||||||
@@ -1,10 +1,56 @@
|
|||||||
import { createRouter, createWebHistory } from 'vue-router'
|
import { createRouter, createWebHistory } from 'vue-router'
|
||||||
|
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
import HomeView from '@/views/HomeView.vue'
|
import HomeView from '@/views/HomeView.vue'
|
||||||
|
|
||||||
|
declare module 'vue-router' {
|
||||||
|
interface RouteMeta {
|
||||||
|
public?: boolean
|
||||||
|
admin?: boolean
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const router = createRouter({
|
const router = createRouter({
|
||||||
history: createWebHistory(import.meta.env.BASE_URL),
|
history: createWebHistory(import.meta.env.BASE_URL),
|
||||||
routes: [{ path: '/', name: 'home', component: HomeView }],
|
routes: [
|
||||||
|
{ path: '/', name: 'home', component: HomeView },
|
||||||
|
{
|
||||||
|
path: '/login',
|
||||||
|
name: 'login',
|
||||||
|
component: () => import('@/views/LoginView.vue'),
|
||||||
|
meta: { public: true },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/clips/:id(\\d+)',
|
||||||
|
name: 'clip-edit',
|
||||||
|
component: () => import('@/views/ClipEditView.vue'),
|
||||||
|
props: true,
|
||||||
|
},
|
||||||
|
{ path: '/account', name: 'account', component: () => import('@/views/AccountView.vue') },
|
||||||
|
{
|
||||||
|
path: '/admin/users',
|
||||||
|
name: 'admin-users',
|
||||||
|
component: () => import('@/views/AdminUsersView.vue'),
|
||||||
|
meta: { admin: true },
|
||||||
|
},
|
||||||
|
{ path: '/:pathMatch(.*)*', redirect: '/' },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
router.beforeEach(async (to) => {
|
||||||
|
const auth = useAuthStore()
|
||||||
|
await auth.ensureLoaded()
|
||||||
|
|
||||||
|
if (to.meta.public) {
|
||||||
|
return auth.user && to.name === 'login' ? { name: 'home' } : true
|
||||||
|
}
|
||||||
|
if (!auth.user) {
|
||||||
|
return { name: 'login', query: to.fullPath !== '/' ? { redirect: to.fullPath } : {} }
|
||||||
|
}
|
||||||
|
if (to.meta.admin && !auth.isAdmin) {
|
||||||
|
return { name: 'home' }
|
||||||
|
}
|
||||||
|
return true
|
||||||
})
|
})
|
||||||
|
|
||||||
export default router
|
export default router
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
|
||||||
|
import { ApiError, api } from '@/api/client'
|
||||||
|
import type { User } from '@/api/types'
|
||||||
|
|
||||||
|
export const useAuthStore = defineStore('auth', () => {
|
||||||
|
const user = ref<User | null>(null)
|
||||||
|
const loaded = ref(false)
|
||||||
|
|
||||||
|
const isAdmin = computed(() => user.value?.role === 'admin')
|
||||||
|
|
||||||
|
async function fetchMe(): Promise<void> {
|
||||||
|
try {
|
||||||
|
user.value = await api.get<User>('/auth/me')
|
||||||
|
} catch (e) {
|
||||||
|
if (!(e instanceof ApiError) || e.status !== 401) throw e
|
||||||
|
user.value = null
|
||||||
|
} finally {
|
||||||
|
loaded.value = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureLoaded(): Promise<void> {
|
||||||
|
if (!loaded.value) await fetchMe()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function login(username: string, password: string): Promise<void> {
|
||||||
|
user.value = await api.post<User>('/auth/login', { username, password })
|
||||||
|
loaded.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function logout(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await api.post('/auth/logout')
|
||||||
|
} finally {
|
||||||
|
clear()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function clear(): void {
|
||||||
|
user.value = null
|
||||||
|
}
|
||||||
|
|
||||||
|
return { user, loaded, isAdmin, fetchMe, ensureLoaded, login, logout, clear }
|
||||||
|
})
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
import { ApiError, api } from '@/api/client'
|
||||||
|
import type { Clip, ClipInput, ClipList } from '@/api/types'
|
||||||
|
|
||||||
|
const PAGE_SIZE = 50
|
||||||
|
|
||||||
|
export class ClipConflictError extends Error {
|
||||||
|
constructor(public readonly current: Clip) {
|
||||||
|
super('Der Clip wurde inzwischen auf einem anderen Gerät geändert.')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pinned first, then most recently edited – same order as the backend. */
|
||||||
|
function compareClips(a: Clip, b: Clip): number {
|
||||||
|
if (a.pinned !== b.pinned) return a.pinned ? -1 : 1
|
||||||
|
if (a.updated_at !== b.updated_at) return a.updated_at < b.updated_at ? 1 : -1
|
||||||
|
return b.id - a.id
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useClipsStore = defineStore('clips', () => {
|
||||||
|
const items = ref<Clip[]>([])
|
||||||
|
const total = ref(0)
|
||||||
|
const loading = ref(false)
|
||||||
|
const error = ref<string | null>(null)
|
||||||
|
|
||||||
|
/** Insert or replace a clip locally (also the entry point for live sync later). */
|
||||||
|
function upsert(clip: Clip): void {
|
||||||
|
const index = items.value.findIndex((c) => c.id === clip.id)
|
||||||
|
if (index === -1) {
|
||||||
|
items.value.push(clip)
|
||||||
|
total.value += 1
|
||||||
|
} else {
|
||||||
|
items.value[index] = clip
|
||||||
|
}
|
||||||
|
items.value.sort(compareClips)
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeLocal(id: number): void {
|
||||||
|
const before = items.value.length
|
||||||
|
items.value = items.value.filter((c) => c.id !== id)
|
||||||
|
total.value -= before - items.value.length
|
||||||
|
}
|
||||||
|
|
||||||
|
async function load(): Promise<void> {
|
||||||
|
loading.value = true
|
||||||
|
error.value = null
|
||||||
|
try {
|
||||||
|
const page = await api.get<ClipList>(`/clips?limit=${PAGE_SIZE}&offset=0`)
|
||||||
|
items.value = page.items
|
||||||
|
total.value = page.total
|
||||||
|
} catch (e) {
|
||||||
|
error.value = e instanceof Error ? e.message : String(e)
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadMore(): Promise<void> {
|
||||||
|
const page = await api.get<ClipList>(`/clips?limit=${PAGE_SIZE}&offset=${items.value.length}`)
|
||||||
|
for (const clip of page.items) upsert(clip)
|
||||||
|
total.value = page.total
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchOne(id: number): Promise<Clip> {
|
||||||
|
const clip = await api.get<Clip>(`/clips/${id}`)
|
||||||
|
upsert(clip)
|
||||||
|
return clip
|
||||||
|
}
|
||||||
|
|
||||||
|
async function create(input: ClipInput): Promise<Clip> {
|
||||||
|
const clip = await api.post<Clip>('/clips', input)
|
||||||
|
upsert(clip)
|
||||||
|
return clip
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pass the version the edit is based on to detect concurrent changes. */
|
||||||
|
async function update(id: number, changes: ClipInput, version?: number): Promise<Clip> {
|
||||||
|
try {
|
||||||
|
const clip = await api.patch<Clip>(`/clips/${id}`, { ...changes, version })
|
||||||
|
upsert(clip)
|
||||||
|
return clip
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof ApiError && e.status === 409) {
|
||||||
|
const current = (e.data as { current: Clip }).current
|
||||||
|
upsert(current)
|
||||||
|
throw new ClipConflictError(current)
|
||||||
|
}
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(id: number): Promise<void> {
|
||||||
|
await api.delete(`/clips/${id}`)
|
||||||
|
removeLocal(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
items,
|
||||||
|
total,
|
||||||
|
loading,
|
||||||
|
error,
|
||||||
|
upsert,
|
||||||
|
removeLocal,
|
||||||
|
load,
|
||||||
|
loadMore,
|
||||||
|
fetchOne,
|
||||||
|
create,
|
||||||
|
update,
|
||||||
|
remove,
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { defineStore } from 'pinia'
|
import { defineStore } from 'pinia'
|
||||||
import { ref } from 'vue'
|
import { ref } from 'vue'
|
||||||
|
|
||||||
import { apiGet } from '@/api/client'
|
import { api } from '@/api/client'
|
||||||
|
|
||||||
export interface Health {
|
export interface Health {
|
||||||
status: 'ok' | 'error'
|
status: 'ok' | 'error'
|
||||||
@@ -18,7 +18,7 @@ export const useHealthStore = defineStore('health', () => {
|
|||||||
loading.value = true
|
loading.value = true
|
||||||
error.value = null
|
error.value = null
|
||||||
try {
|
try {
|
||||||
health.value = await apiGet<Health>('/health')
|
health.value = await api.get<Health>('/health')
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
health.value = null
|
health.value = null
|
||||||
error.value = e instanceof Error ? e.message : String(e)
|
error.value = e instanceof Error ? e.message : String(e)
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
/** Copy text; needs HTTPS and a user gesture. Falls back to execCommand for old browsers. */
|
||||||
|
export async function copyText(text: string): Promise<void> {
|
||||||
|
if (navigator.clipboard?.writeText) {
|
||||||
|
await navigator.clipboard.writeText(text)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const area = document.createElement('textarea')
|
||||||
|
area.value = text
|
||||||
|
area.setAttribute('readonly', '')
|
||||||
|
area.style.position = 'fixed'
|
||||||
|
area.style.opacity = '0'
|
||||||
|
document.body.appendChild(area)
|
||||||
|
area.select()
|
||||||
|
try {
|
||||||
|
if (!document.execCommand('copy')) throw new Error('Kopieren nicht möglich.')
|
||||||
|
} finally {
|
||||||
|
area.remove()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function readClipboardText(): Promise<string> {
|
||||||
|
if (!navigator.clipboard?.readText) {
|
||||||
|
throw new Error('Dieser Browser erlaubt kein Einfügen per Knopf. Bitte manuell einfügen.')
|
||||||
|
}
|
||||||
|
return navigator.clipboard.readText()
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
const dateTimeFormat = new Intl.DateTimeFormat('de-DE', {
|
||||||
|
dateStyle: 'medium',
|
||||||
|
timeStyle: 'short',
|
||||||
|
})
|
||||||
|
|
||||||
|
export function formatDateTime(iso: string): string {
|
||||||
|
return dateTimeFormat.format(new Date(iso))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Order matters: iPad/iPhone before macOS, Edge/Chrome before Safari
|
||||||
|
const DEVICES: [RegExp, string][] = [
|
||||||
|
[/iPad/, 'iPad'],
|
||||||
|
[/iPhone/, 'iPhone'],
|
||||||
|
[/Android/, 'Android'],
|
||||||
|
[/Windows/, 'Windows'],
|
||||||
|
[/Mac OS X|Macintosh/, 'macOS'],
|
||||||
|
[/Linux/, 'Linux'],
|
||||||
|
]
|
||||||
|
|
||||||
|
const BROWSERS: [RegExp, string][] = [
|
||||||
|
[/Edg\//, 'Edge'],
|
||||||
|
[/Firefox\/|FxiOS/, 'Firefox'],
|
||||||
|
[/Chrome\/|CriOS/, 'Chrome'],
|
||||||
|
[/Safari\//, 'Safari'],
|
||||||
|
]
|
||||||
|
|
||||||
|
function firstMatch(ua: string, table: [RegExp, string][]): string | null {
|
||||||
|
return table.find(([pattern]) => pattern.test(ua))?.[1] ?? null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Short human-readable device description from a User-Agent string. */
|
||||||
|
export function describeUserAgent(ua: string | null): string {
|
||||||
|
if (!ua) return 'Unbekanntes Gerät'
|
||||||
|
const device = firstMatch(ua, DEVICES)
|
||||||
|
const browser = firstMatch(ua, BROWSERS)
|
||||||
|
if (device && browser) return `${browser} auf ${device}`
|
||||||
|
return device ?? browser ?? ua.slice(0, 40)
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import hljs from 'highlight.js/lib/core'
|
||||||
|
import bash from 'highlight.js/lib/languages/bash'
|
||||||
|
import c from 'highlight.js/lib/languages/c'
|
||||||
|
import cpp from 'highlight.js/lib/languages/cpp'
|
||||||
|
import csharp from 'highlight.js/lib/languages/csharp'
|
||||||
|
import css from 'highlight.js/lib/languages/css'
|
||||||
|
import diff from 'highlight.js/lib/languages/diff'
|
||||||
|
import dockerfile from 'highlight.js/lib/languages/dockerfile'
|
||||||
|
import go from 'highlight.js/lib/languages/go'
|
||||||
|
import ini from 'highlight.js/lib/languages/ini'
|
||||||
|
import java from 'highlight.js/lib/languages/java'
|
||||||
|
import javascript from 'highlight.js/lib/languages/javascript'
|
||||||
|
import json from 'highlight.js/lib/languages/json'
|
||||||
|
import markdown from 'highlight.js/lib/languages/markdown'
|
||||||
|
import nginx from 'highlight.js/lib/languages/nginx'
|
||||||
|
import php from 'highlight.js/lib/languages/php'
|
||||||
|
import plaintext from 'highlight.js/lib/languages/plaintext'
|
||||||
|
import powershell from 'highlight.js/lib/languages/powershell'
|
||||||
|
import python from 'highlight.js/lib/languages/python'
|
||||||
|
import ruby from 'highlight.js/lib/languages/ruby'
|
||||||
|
import rust from 'highlight.js/lib/languages/rust'
|
||||||
|
import sql from 'highlight.js/lib/languages/sql'
|
||||||
|
import typescript from 'highlight.js/lib/languages/typescript'
|
||||||
|
import xml from 'highlight.js/lib/languages/xml'
|
||||||
|
import yaml from 'highlight.js/lib/languages/yaml'
|
||||||
|
|
||||||
|
/** Must match backend/app/languages.py */
|
||||||
|
export const LANGUAGES = [
|
||||||
|
{ id: 'plaintext', label: 'Nur Text', grammar: plaintext },
|
||||||
|
{ id: 'bash', label: 'Bash / Shell', grammar: bash },
|
||||||
|
{ id: 'powershell', label: 'PowerShell', grammar: powershell },
|
||||||
|
{ id: 'python', label: 'Python', grammar: python },
|
||||||
|
{ id: 'javascript', label: 'JavaScript', grammar: javascript },
|
||||||
|
{ id: 'typescript', label: 'TypeScript', grammar: typescript },
|
||||||
|
{ id: 'json', label: 'JSON', grammar: json },
|
||||||
|
{ id: 'yaml', label: 'YAML', grammar: yaml },
|
||||||
|
{ id: 'ini', label: 'INI / TOML', grammar: ini },
|
||||||
|
{ id: 'xml', label: 'HTML / XML', grammar: xml },
|
||||||
|
{ id: 'css', label: 'CSS', grammar: css },
|
||||||
|
{ id: 'sql', label: 'SQL', grammar: sql },
|
||||||
|
{ id: 'markdown', label: 'Markdown', grammar: markdown },
|
||||||
|
{ id: 'dockerfile', label: 'Dockerfile', grammar: dockerfile },
|
||||||
|
{ id: 'nginx', label: 'Nginx', grammar: nginx },
|
||||||
|
{ id: 'go', label: 'Go', grammar: go },
|
||||||
|
{ id: 'rust', label: 'Rust', grammar: rust },
|
||||||
|
{ id: 'java', label: 'Java', grammar: java },
|
||||||
|
{ id: 'c', label: 'C', grammar: c },
|
||||||
|
{ id: 'cpp', label: 'C++', grammar: cpp },
|
||||||
|
{ id: 'csharp', label: 'C#', grammar: csharp },
|
||||||
|
{ id: 'php', label: 'PHP', grammar: php },
|
||||||
|
{ id: 'ruby', label: 'Ruby', grammar: ruby },
|
||||||
|
{ id: 'diff', label: 'Diff', grammar: diff },
|
||||||
|
] as const
|
||||||
|
|
||||||
|
export type LanguageId = (typeof LANGUAGES)[number]['id']
|
||||||
|
|
||||||
|
for (const lang of LANGUAGES) hljs.registerLanguage(lang.id, lang.grammar)
|
||||||
|
|
||||||
|
const DETECTABLE = LANGUAGES.map((l) => l.id).filter((id) => id !== 'plaintext')
|
||||||
|
|
||||||
|
export function languageLabel(id: string | null): string {
|
||||||
|
return LANGUAGES.find((l) => l.id === id)?.label ?? id ?? ''
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns escaped HTML, safe for v-html. */
|
||||||
|
export function highlight(code: string, language: string | null): string {
|
||||||
|
const lang = language && hljs.getLanguage(language) ? language : 'plaintext'
|
||||||
|
return hljs.highlight(code, { language: lang, ignoreIllegals: true }).value
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Best guess for a snippet, or null if nothing fits convincingly. */
|
||||||
|
export function detectLanguage(code: string): LanguageId | null {
|
||||||
|
if (code.trim().length < 20) return null
|
||||||
|
const result = hljs.highlightAuto(code.slice(0, 5000), DETECTABLE)
|
||||||
|
return result.relevance >= 5 ? (result.language as LanguageId) : null
|
||||||
|
}
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, ref } from 'vue'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
|
||||||
|
import { api } from '@/api/client'
|
||||||
|
import type { SessionInfo } from '@/api/types'
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
import { describeUserAgent, formatDateTime } from '@/utils/format'
|
||||||
|
|
||||||
|
const auth = useAuthStore()
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
|
// --- Password -----------------------------------------------------------------
|
||||||
|
|
||||||
|
const currentPassword = ref('')
|
||||||
|
const newPassword = ref('')
|
||||||
|
const repeatPassword = ref('')
|
||||||
|
const passwordMessage = ref<{ ok: boolean; text: string } | null>(null)
|
||||||
|
const passwordBusy = ref(false)
|
||||||
|
|
||||||
|
async function changePassword(): Promise<void> {
|
||||||
|
if (newPassword.value !== repeatPassword.value) {
|
||||||
|
passwordMessage.value = { ok: false, text: 'Die neuen Passwörter stimmen nicht überein.' }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
passwordBusy.value = true
|
||||||
|
passwordMessage.value = null
|
||||||
|
try {
|
||||||
|
await api.post('/auth/password', {
|
||||||
|
current_password: currentPassword.value,
|
||||||
|
new_password: newPassword.value,
|
||||||
|
})
|
||||||
|
currentPassword.value = newPassword.value = repeatPassword.value = ''
|
||||||
|
passwordMessage.value = {
|
||||||
|
ok: true,
|
||||||
|
text: 'Passwort geändert. Alle anderen Geräte wurden abgemeldet.',
|
||||||
|
}
|
||||||
|
await loadSessions()
|
||||||
|
} catch (e) {
|
||||||
|
passwordMessage.value = { ok: false, text: e instanceof Error ? e.message : String(e) }
|
||||||
|
} finally {
|
||||||
|
passwordBusy.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Sessions -----------------------------------------------------------------
|
||||||
|
|
||||||
|
const sessions = ref<SessionInfo[]>([])
|
||||||
|
const sessionError = ref<string | null>(null)
|
||||||
|
|
||||||
|
async function loadSessions(): Promise<void> {
|
||||||
|
try {
|
||||||
|
sessions.value = await api.get<SessionInfo[]>('/auth/sessions')
|
||||||
|
sessionError.value = null
|
||||||
|
} catch (e) {
|
||||||
|
sessionError.value = e instanceof Error ? e.message : String(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function revoke(session: SessionInfo): Promise<void> {
|
||||||
|
if (session.current) {
|
||||||
|
await auth.logout()
|
||||||
|
await router.push({ name: 'login' })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
await api.delete(`/auth/sessions/${session.id}`)
|
||||||
|
await loadSessions()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function revokeOthers(): Promise<void> {
|
||||||
|
if (!confirm('Alle anderen Geräte abmelden?')) return
|
||||||
|
await api.delete('/auth/sessions')
|
||||||
|
await loadSessions()
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(loadSessions)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<main class="page">
|
||||||
|
<h1>Konto</h1>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<h2>Angemeldet als</h2>
|
||||||
|
<p>
|
||||||
|
{{ auth.user?.username }}
|
||||||
|
<span class="badge" :class="{ accent: auth.isAdmin }">{{ auth.user?.role }}</span>
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<h2>Passwort ändern</h2>
|
||||||
|
<form class="form" @submit.prevent="changePassword">
|
||||||
|
<!-- Hidden username helps password managers associate the new password -->
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
name="username"
|
||||||
|
autocomplete="username"
|
||||||
|
:value="auth.user?.username"
|
||||||
|
hidden
|
||||||
|
/>
|
||||||
|
<label>
|
||||||
|
Aktuelles Passwort
|
||||||
|
<input
|
||||||
|
v-model="currentPassword"
|
||||||
|
type="password"
|
||||||
|
autocomplete="current-password"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Neues Passwort (mindestens 12 Zeichen)
|
||||||
|
<input
|
||||||
|
v-model="newPassword"
|
||||||
|
type="password"
|
||||||
|
autocomplete="new-password"
|
||||||
|
minlength="12"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Neues Passwort wiederholen
|
||||||
|
<input
|
||||||
|
v-model="repeatPassword"
|
||||||
|
type="password"
|
||||||
|
autocomplete="new-password"
|
||||||
|
minlength="12"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<p v-if="passwordMessage" :class="passwordMessage.ok ? 'ok' : 'error'" role="status">
|
||||||
|
{{ passwordMessage.text }}
|
||||||
|
</p>
|
||||||
|
<button type="submit" class="primary" :disabled="passwordBusy">Passwort ändern</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<h2>Angemeldete Geräte</h2>
|
||||||
|
<p v-if="sessionError" class="error">{{ sessionError }}</p>
|
||||||
|
<ul class="sessions">
|
||||||
|
<li v-for="s in sessions" :key="s.id">
|
||||||
|
<div>
|
||||||
|
<strong>{{ describeUserAgent(s.user_agent) }}</strong>
|
||||||
|
<span v-if="s.current" class="badge accent">dieses Gerät</span>
|
||||||
|
<div class="muted small">
|
||||||
|
{{ s.ip ?? 'IP unbekannt' }} · zuletzt aktiv {{ formatDateTime(s.last_seen_at) }}
|
||||||
|
</div>
|
||||||
|
<div class="muted small">angemeldet seit {{ formatDateTime(s.created_at) }}</div>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="small danger" @click="revoke(s)">
|
||||||
|
{{ s.current ? 'Abmelden' : 'Widerrufen' }}
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<button v-if="sessions.length > 1" type="button" class="danger" @click="revokeOthers">
|
||||||
|
Alle anderen Geräte abmelden
|
||||||
|
</button>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.sessions {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sessions li {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 1rem;
|
||||||
|
padding: 0.75rem 0;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.sessions li:last-child {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.small {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.badge {
|
||||||
|
margin-left: 0.5rem;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, ref } from 'vue'
|
||||||
|
|
||||||
|
import { api } from '@/api/client'
|
||||||
|
import type { Role, User } from '@/api/types'
|
||||||
|
import SystemStatus from '@/components/SystemStatus.vue'
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
import { formatDateTime } from '@/utils/format'
|
||||||
|
|
||||||
|
const auth = useAuthStore()
|
||||||
|
|
||||||
|
const users = ref<User[]>([])
|
||||||
|
const error = ref<string | null>(null)
|
||||||
|
const notice = ref<string | null>(null)
|
||||||
|
|
||||||
|
function showError(e: unknown): void {
|
||||||
|
notice.value = null
|
||||||
|
error.value = e instanceof Error ? e.message : String(e)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function load(): Promise<void> {
|
||||||
|
try {
|
||||||
|
users.value = await api.get<User[]>('/admin/users')
|
||||||
|
} catch (e) {
|
||||||
|
showError(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Create -------------------------------------------------------------------
|
||||||
|
|
||||||
|
const newUsername = ref('')
|
||||||
|
const newPassword = ref('')
|
||||||
|
const newRole = ref<Role>('user')
|
||||||
|
const creating = ref(false)
|
||||||
|
|
||||||
|
async function createUser(): Promise<void> {
|
||||||
|
creating.value = true
|
||||||
|
error.value = null
|
||||||
|
try {
|
||||||
|
const user = await api.post<User>('/admin/users', {
|
||||||
|
username: newUsername.value,
|
||||||
|
password: newPassword.value,
|
||||||
|
role: newRole.value,
|
||||||
|
})
|
||||||
|
notice.value = `Benutzer „${user.username}“ angelegt.`
|
||||||
|
newUsername.value = newPassword.value = ''
|
||||||
|
newRole.value = 'user'
|
||||||
|
await load()
|
||||||
|
} catch (e) {
|
||||||
|
showError(e)
|
||||||
|
} finally {
|
||||||
|
creating.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Update / delete ----------------------------------------------------------
|
||||||
|
|
||||||
|
async function update(user: User, changes: Partial<User> & { password?: string }): Promise<void> {
|
||||||
|
error.value = null
|
||||||
|
try {
|
||||||
|
await api.patch<User>(`/admin/users/${user.id}`, changes)
|
||||||
|
await load()
|
||||||
|
} catch (e) {
|
||||||
|
showError(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function resetPassword(user: User): Promise<void> {
|
||||||
|
const password = prompt(`Neues Passwort für „${user.username}“ (mindestens 12 Zeichen):`)
|
||||||
|
if (!password) return
|
||||||
|
await update(user, { password })
|
||||||
|
if (!error.value) notice.value = `Passwort für „${user.username}“ gesetzt.`
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(user: User): Promise<void> {
|
||||||
|
if (!confirm(`Benutzer „${user.username}“ endgültig löschen?`)) return
|
||||||
|
error.value = null
|
||||||
|
try {
|
||||||
|
await api.delete(`/admin/users/${user.id}`)
|
||||||
|
notice.value = `Benutzer „${user.username}“ gelöscht.`
|
||||||
|
await load()
|
||||||
|
} catch (e) {
|
||||||
|
showError(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(load)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<main class="page">
|
||||||
|
<h1>Benutzer</h1>
|
||||||
|
|
||||||
|
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||||
|
<p v-if="notice" class="ok" role="status">{{ notice }}</p>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<h2>Neuer Benutzer</h2>
|
||||||
|
<form class="form" @submit.prevent="createUser">
|
||||||
|
<label>
|
||||||
|
Benutzername
|
||||||
|
<input
|
||||||
|
v-model="newUsername"
|
||||||
|
autocomplete="off"
|
||||||
|
autocapitalize="none"
|
||||||
|
spellcheck="false"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Passwort (mindestens 12 Zeichen)
|
||||||
|
<input
|
||||||
|
v-model="newPassword"
|
||||||
|
type="password"
|
||||||
|
autocomplete="new-password"
|
||||||
|
minlength="12"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Rolle
|
||||||
|
<select v-model="newRole">
|
||||||
|
<option value="user">Benutzer</option>
|
||||||
|
<option value="admin">Administrator</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<button type="submit" class="primary" :disabled="creating">Anlegen</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<h2>Alle Benutzer</h2>
|
||||||
|
<ul class="users">
|
||||||
|
<li v-for="u in users" :key="u.id" :class="{ inactive: !u.is_active }">
|
||||||
|
<div class="info">
|
||||||
|
<strong>{{ u.username }}</strong>
|
||||||
|
<span class="badge" :class="{ accent: u.role === 'admin' }">{{ u.role }}</span>
|
||||||
|
<span v-if="!u.is_active" class="badge">deaktiviert</span>
|
||||||
|
<div class="muted small">angelegt {{ formatDateTime(u.created_at) }}</div>
|
||||||
|
</div>
|
||||||
|
<div v-if="u.id !== auth.user?.id" class="actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="small"
|
||||||
|
@click="update(u, { role: u.role === 'admin' ? 'user' : 'admin' })"
|
||||||
|
>
|
||||||
|
{{ u.role === 'admin' ? 'Zu Benutzer' : 'Zu Admin' }}
|
||||||
|
</button>
|
||||||
|
<button type="button" class="small" @click="update(u, { is_active: !u.is_active })">
|
||||||
|
{{ u.is_active ? 'Deaktivieren' : 'Aktivieren' }}
|
||||||
|
</button>
|
||||||
|
<button type="button" class="small" @click="resetPassword(u)">Passwort</button>
|
||||||
|
<button type="button" class="small danger" @click="remove(u)">Löschen</button>
|
||||||
|
</div>
|
||||||
|
<span v-else class="muted small">das bist du</span>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<SystemStatus />
|
||||||
|
</main>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.users {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.users li {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 0.5rem 1rem;
|
||||||
|
padding: 0.75rem 0;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.users li:last-child {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.users li.inactive .info {
|
||||||
|
opacity: 0.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.info .badge {
|
||||||
|
margin-left: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.small {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref } from 'vue'
|
||||||
|
import { onBeforeRouteLeave, useRouter } from 'vue-router'
|
||||||
|
|
||||||
|
import { ApiError } from '@/api/client'
|
||||||
|
import type { Clip, ClipKind } from '@/api/types'
|
||||||
|
import CopyButton from '@/components/CopyButton.vue'
|
||||||
|
import { ClipConflictError, useClipsStore } from '@/stores/clips'
|
||||||
|
import { formatDateTime } from '@/utils/format'
|
||||||
|
import { detectLanguage, highlight, LANGUAGES } from '@/utils/highlight'
|
||||||
|
|
||||||
|
const props = defineProps<{ id: string }>()
|
||||||
|
|
||||||
|
const store = useClipsStore()
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
|
const clip = ref<Clip | null>(null)
|
||||||
|
const notFound = ref(false)
|
||||||
|
const error = ref<string | null>(null)
|
||||||
|
const busy = ref(false)
|
||||||
|
const conflict = ref<Clip | null>(null)
|
||||||
|
|
||||||
|
// Form state
|
||||||
|
const title = ref('')
|
||||||
|
const content = ref('')
|
||||||
|
const kind = ref<ClipKind>('text')
|
||||||
|
const language = ref('plaintext')
|
||||||
|
const baseVersion = ref(0)
|
||||||
|
|
||||||
|
function fillForm(source: Clip): void {
|
||||||
|
clip.value = source
|
||||||
|
title.value = source.title ?? ''
|
||||||
|
content.value = source.content
|
||||||
|
kind.value = source.kind
|
||||||
|
language.value = source.language ?? detectLanguage(source.content) ?? 'plaintext'
|
||||||
|
baseVersion.value = source.version
|
||||||
|
}
|
||||||
|
|
||||||
|
const dirty = computed(() => {
|
||||||
|
const c = clip.value
|
||||||
|
if (!c) return false
|
||||||
|
return (
|
||||||
|
title.value !== (c.title ?? '') ||
|
||||||
|
content.value !== c.content ||
|
||||||
|
kind.value !== c.kind ||
|
||||||
|
(kind.value === 'code' && language.value !== c.language)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
const previewHtml = computed(() =>
|
||||||
|
kind.value === 'code' ? highlight(content.value, language.value) : null,
|
||||||
|
)
|
||||||
|
|
||||||
|
async function save(version = baseVersion.value): Promise<void> {
|
||||||
|
if (!clip.value) return
|
||||||
|
busy.value = true
|
||||||
|
error.value = null
|
||||||
|
try {
|
||||||
|
await store.update(
|
||||||
|
clip.value.id,
|
||||||
|
{
|
||||||
|
title: title.value.trim() || null,
|
||||||
|
content: content.value,
|
||||||
|
kind: kind.value,
|
||||||
|
language: kind.value === 'code' ? language.value : null,
|
||||||
|
},
|
||||||
|
version,
|
||||||
|
)
|
||||||
|
conflict.value = null
|
||||||
|
clip.value = null // nothing left to lose; skip the leave guard
|
||||||
|
await router.push('/')
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof ClipConflictError) {
|
||||||
|
conflict.value = e.current
|
||||||
|
} else {
|
||||||
|
error.value = e instanceof Error ? e.message : String(e)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
busy.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function takeTheirs(): void {
|
||||||
|
if (conflict.value) fillForm(conflict.value)
|
||||||
|
conflict.value = null
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(): Promise<void> {
|
||||||
|
if (!clip.value || !confirm('Diesen Clip endgültig löschen?')) return
|
||||||
|
try {
|
||||||
|
await store.remove(clip.value.id)
|
||||||
|
clip.value = null
|
||||||
|
await router.push('/')
|
||||||
|
} catch (e) {
|
||||||
|
error.value = e instanceof Error ? e.message : String(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onBeforeRouteLeave(() => !dirty.value || confirm('Ungespeicherte Änderungen verwerfen?'))
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
try {
|
||||||
|
fillForm(await store.fetchOne(Number(props.id)))
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof ApiError && e.status === 404) notFound.value = true
|
||||||
|
else error.value = e instanceof Error ? e.message : String(e)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<main class="page">
|
||||||
|
<h1>Clip bearbeiten</h1>
|
||||||
|
|
||||||
|
<p v-if="notFound" class="muted">
|
||||||
|
Diesen Clip gibt es nicht (mehr). <RouterLink to="/">Zur Übersicht</RouterLink>
|
||||||
|
</p>
|
||||||
|
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||||
|
|
||||||
|
<section v-if="conflict" class="card conflict" role="alert">
|
||||||
|
<h2>Konflikt</h2>
|
||||||
|
<p>
|
||||||
|
Der Clip wurde am {{ formatDateTime(conflict.updated_at) }} auf einem anderen Gerät
|
||||||
|
geändert. Deine Änderungen sind noch nicht gespeichert.
|
||||||
|
</p>
|
||||||
|
<div class="actions">
|
||||||
|
<button type="button" @click="takeTheirs">Andere Version laden</button>
|
||||||
|
<button type="button" class="danger" :disabled="busy" @click="save(conflict.version)">
|
||||||
|
Meine Version speichern
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<form v-if="clip" class="card form" @submit.prevent="save()">
|
||||||
|
<label>
|
||||||
|
Titel (optional)
|
||||||
|
<input v-model="title" maxlength="200" />
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<div class="segmented" role="radiogroup" aria-label="Art">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="radio"
|
||||||
|
:aria-checked="kind === 'text'"
|
||||||
|
:class="{ active: kind === 'text' }"
|
||||||
|
@click="kind = 'text'"
|
||||||
|
>
|
||||||
|
Text
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="radio"
|
||||||
|
:aria-checked="kind === 'code'"
|
||||||
|
:class="{ active: kind === 'code' }"
|
||||||
|
@click="kind = 'code'"
|
||||||
|
>
|
||||||
|
Code
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<select v-if="kind === 'code'" v-model="language" aria-label="Sprache" class="language">
|
||||||
|
<option v-for="l in LANGUAGES" :key="l.id" :value="l.id">{{ l.label }}</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<textarea
|
||||||
|
v-model="content"
|
||||||
|
:class="{ mono: kind === 'code' }"
|
||||||
|
rows="14"
|
||||||
|
autocapitalize="off"
|
||||||
|
spellcheck="false"
|
||||||
|
@keydown.enter.ctrl.prevent="save()"
|
||||||
|
@keydown.enter.meta.prevent="save()"
|
||||||
|
></textarea>
|
||||||
|
|
||||||
|
<template v-if="previewHtml !== null">
|
||||||
|
<span class="muted small">Vorschau</span>
|
||||||
|
<!-- eslint-disable-next-line vue/no-v-html -- highlight.js output is escaped -->
|
||||||
|
<pre class="preview"><code class="hljs" v-html="previewHtml"></code></pre>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<div class="actions">
|
||||||
|
<button type="submit" class="primary" :disabled="busy || !content.trim()">Speichern</button>
|
||||||
|
<CopyButton :text="content" />
|
||||||
|
<RouterLink to="/" class="button-link">Abbrechen</RouterLink>
|
||||||
|
<div class="spacer"></div>
|
||||||
|
<button type="button" class="danger" @click="remove">Löschen</button>
|
||||||
|
</div>
|
||||||
|
<p class="muted small">
|
||||||
|
Angelegt {{ formatDateTime(clip.created_at) }} · zuletzt geändert
|
||||||
|
{{ formatDateTime(clip.updated_at) }}
|
||||||
|
</p>
|
||||||
|
</form>
|
||||||
|
</main>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.row,
|
||||||
|
.actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.spacer {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.language {
|
||||||
|
width: auto;
|
||||||
|
min-width: 9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.small {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.conflict {
|
||||||
|
border-color: var(--error);
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0.75rem;
|
||||||
|
max-height: 24rem;
|
||||||
|
overflow: auto;
|
||||||
|
border-radius: calc(var(--radius) - 4px);
|
||||||
|
background: var(--bg);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview code.hljs {
|
||||||
|
padding: 0;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,97 +1,69 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted } from 'vue'
|
import { onMounted } from 'vue'
|
||||||
|
|
||||||
import { useHealthStore } from '@/stores/health'
|
import type { Clip } from '@/api/types'
|
||||||
|
import ClipCard from '@/components/ClipCard.vue'
|
||||||
|
import QuickAdd from '@/components/QuickAdd.vue'
|
||||||
|
import { useClipsStore } from '@/stores/clips'
|
||||||
|
|
||||||
const store = useHealthStore()
|
const store = useClipsStore()
|
||||||
|
|
||||||
onMounted(store.refresh)
|
async function togglePin(clip: Clip): Promise<void> {
|
||||||
|
try {
|
||||||
|
await store.update(clip.id, { pinned: !clip.pinned })
|
||||||
|
} catch (e) {
|
||||||
|
store.error = e instanceof Error ? e.message : String(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(clip: Clip): Promise<void> {
|
||||||
|
if (!confirm('Diesen Clip endgültig löschen?')) return
|
||||||
|
try {
|
||||||
|
await store.remove(clip.id)
|
||||||
|
} catch (e) {
|
||||||
|
store.error = e instanceof Error ? e.message : String(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(store.load)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<main class="home">
|
<main class="page">
|
||||||
<h1>LAN-Clipboard</h1>
|
<QuickAdd />
|
||||||
<section class="card">
|
|
||||||
<h2>Systemstatus</h2>
|
<p v-if="store.error" class="error" role="alert">{{ store.error }}</p>
|
||||||
<p v-if="store.loading" class="muted">Prüfe …</p>
|
<p v-if="store.loading && store.items.length === 0" class="muted">Lade …</p>
|
||||||
<p v-else-if="store.error" class="error">Backend nicht erreichbar: {{ store.error }}</p>
|
<p v-else-if="!store.loading && store.items.length === 0" class="muted empty">
|
||||||
<dl v-else-if="store.health">
|
Noch keine Clips. Füge oben Text oder Code ein.
|
||||||
<dt>Status</dt>
|
</p>
|
||||||
<dd :class="store.health.status">{{ store.health.status }}</dd>
|
|
||||||
<dt>Datenbank</dt>
|
<ClipCard
|
||||||
<dd :class="store.health.db">{{ store.health.db }}</dd>
|
v-for="clip in store.items"
|
||||||
<dt>Version</dt>
|
:key="clip.id"
|
||||||
<dd>{{ store.health.version }}</dd>
|
:clip="clip"
|
||||||
</dl>
|
@toggle-pin="togglePin(clip)"
|
||||||
<button type="button" :disabled="store.loading" @click="store.refresh">Aktualisieren</button>
|
@remove="remove(clip)"
|
||||||
</section>
|
/>
|
||||||
|
|
||||||
|
<button
|
||||||
|
v-if="store.items.length < store.total"
|
||||||
|
type="button"
|
||||||
|
class="more"
|
||||||
|
@click="store.loadMore"
|
||||||
|
>
|
||||||
|
Weitere laden ({{ store.total - store.items.length }})
|
||||||
|
</button>
|
||||||
</main>
|
</main>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.home {
|
.empty {
|
||||||
max-width: 40rem;
|
text-align: center;
|
||||||
margin: 0 auto;
|
padding: 2rem 0;
|
||||||
padding: 1.5rem 1rem;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
h1 {
|
.more {
|
||||||
font-size: 1.6rem;
|
width: 100%;
|
||||||
margin: 0 0 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.card {
|
|
||||||
background: var(--surface);
|
|
||||||
border: 1px solid var(--border);
|
|
||||||
border-radius: var(--radius);
|
|
||||||
padding: 1rem 1.25rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
h2 {
|
|
||||||
font-size: 1.1rem;
|
|
||||||
margin: 0 0 0.75rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
dl {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: max-content 1fr;
|
|
||||||
gap: 0.25rem 1rem;
|
|
||||||
margin: 0 0 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
dt {
|
|
||||||
color: var(--muted);
|
|
||||||
}
|
|
||||||
|
|
||||||
dd {
|
|
||||||
margin: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.ok {
|
|
||||||
color: var(--ok);
|
|
||||||
}
|
|
||||||
|
|
||||||
.error {
|
|
||||||
color: var(--error);
|
|
||||||
}
|
|
||||||
|
|
||||||
.muted {
|
|
||||||
color: var(--muted);
|
|
||||||
}
|
|
||||||
|
|
||||||
button {
|
|
||||||
min-height: 44px;
|
|
||||||
padding: 0 1rem;
|
|
||||||
border: 1px solid var(--accent);
|
|
||||||
border-radius: var(--radius);
|
|
||||||
background: transparent;
|
|
||||||
color: var(--accent);
|
|
||||||
font: inherit;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
button:disabled {
|
|
||||||
opacity: 0.5;
|
|
||||||
cursor: default;
|
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref } from 'vue'
|
||||||
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
|
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
|
||||||
|
const auth = useAuthStore()
|
||||||
|
const route = useRoute()
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
|
const username = ref('')
|
||||||
|
const password = ref('')
|
||||||
|
const error = ref<string | null>(null)
|
||||||
|
const busy = ref(false)
|
||||||
|
|
||||||
|
async function submit(): Promise<void> {
|
||||||
|
busy.value = true
|
||||||
|
error.value = null
|
||||||
|
try {
|
||||||
|
await auth.login(username.value, password.value)
|
||||||
|
const redirect = typeof route.query.redirect === 'string' ? route.query.redirect : '/'
|
||||||
|
// Only allow app-internal redirects
|
||||||
|
await router.replace(redirect.startsWith('/') && !redirect.startsWith('//') ? redirect : '/')
|
||||||
|
} catch (e) {
|
||||||
|
error.value = e instanceof Error ? e.message : String(e)
|
||||||
|
password.value = ''
|
||||||
|
} finally {
|
||||||
|
busy.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<main class="login">
|
||||||
|
<h1>LAN-Clipboard</h1>
|
||||||
|
<form class="card form" @submit.prevent="submit">
|
||||||
|
<label>
|
||||||
|
Benutzername
|
||||||
|
<input
|
||||||
|
v-model="username"
|
||||||
|
name="username"
|
||||||
|
autocomplete="username"
|
||||||
|
autocapitalize="none"
|
||||||
|
autocorrect="off"
|
||||||
|
spellcheck="false"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Passwort
|
||||||
|
<input
|
||||||
|
v-model="password"
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
autocomplete="current-password"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||||
|
<button type="submit" class="primary" :disabled="busy">Anmelden</button>
|
||||||
|
</form>
|
||||||
|
</main>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.login {
|
||||||
|
max-width: 24rem;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 15vh 1rem 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
text-align: center;
|
||||||
|
font-size: 1.6rem;
|
||||||
|
margin: 0 0 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
Reference in new issue
Block a user