From 2733818cad28be23f26f2c647974ba85c0b55eb8 Mon Sep 17 00:00:00 2001 From: kai Date: Tue, 25 Aug 2026 12:07:12 +0200 Subject: [PATCH] =?UTF-8?q?admin=20user=20hinzuf=C3=BCgen=20und=20login=20?= =?UTF-8?q?auf=20jeder=20seite?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/main.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ compose.yml | 3 +++ 2 files changed, 48 insertions(+) diff --git a/app/main.py b/app/main.py index c318d64..6b08365 100644 --- a/app/main.py +++ b/app/main.py @@ -41,6 +41,9 @@ SESSION_COOKIE = "pingu_session" SESSION_DAYS = 30 ALLOWED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"} MAX_IMAGE_BYTES = 10 * 1024 * 1024 +INITIAL_ADMIN_USERNAME = os.environ.get("INITIAL_ADMIN_USERNAME") +INITIAL_ADMIN_PASSWORD = os.environ.get("INITIAL_ADMIN_PASSWORD") +INITIAL_ADMIN_EMAIL = os.environ.get("INITIAL_ADMIN_EMAIL") def get_db_connection(): @@ -111,6 +114,37 @@ def ensure_schema(): with connection.cursor() as cursor: for statement in statements: cursor.execute(statement) + + if INITIAL_ADMIN_USERNAME and INITIAL_ADMIN_PASSWORD: + cursor.execute( + "SELECT id FROM users WHERE username = %s", + (INITIAL_ADMIN_USERNAME,), + ) + existing_user = cursor.fetchone() + + if not existing_user: + cursor.execute( + """ + INSERT INTO users ( + username, + email, + password_hash, + display_name, + is_admin + ) + VALUES (%s, %s, %s, %s, TRUE) + """, + ( + INITIAL_ADMIN_USERNAME, + INITIAL_ADMIN_EMAIL + or f"{INITIAL_ADMIN_USERNAME}@local.invalid", + bcrypt.hashpw( + INITIAL_ADMIN_PASSWORD.encode("utf-8"), + bcrypt.gensalt(), + ).decode("utf-8"), + INITIAL_ADMIN_USERNAME, + ), + ) connection.commit() @@ -123,6 +157,17 @@ async def lifespan(_app: FastAPI): app = FastAPI(title="Pingu Concerts", lifespan=lifespan) +@app.middleware("http") +async def require_login(request: Request, call_next): + if request.url.path == "/login" or request.url.path.startswith("/static/"): + return await call_next(request) + + if get_current_user(request): + return await call_next(request) + + return login_redirect("/") + + # ============================================================ # Templates # ============================================================ diff --git a/compose.yml b/compose.yml index f6a5119..250fd1f 100644 --- a/compose.yml +++ b/compose.yml @@ -19,6 +19,9 @@ services: - "8080:8000" environment: DATABASE_URL: postgresql://concerts:change-me-later@db:5432/concerts + INITIAL_ADMIN_USERNAME: kai + INITIAL_ADMIN_PASSWORD: test123 + INITIAL_ADMIN_EMAIL: kai@local.invalid volumes: - concert_uploads:/app/static/uploads depends_on: