admin user hinzufügen und login auf jeder seite

This commit is contained in:
kai
2026-08-25 12:07:12 +02:00
parent b3ad6d13a8
commit 2733818cad
2 changed files with 48 additions and 0 deletions
+45
View File
@@ -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
# ============================================================
+3
View File
@@ -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: