admin user hinzufügen und login auf jeder seite
This commit is contained in:
+45
@@ -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
|
||||
# ============================================================
|
||||
|
||||
Reference in New Issue
Block a user