Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b789c1bd44 | ||
|
|
5062aa8068 | ||
|
|
8a042589e7 | ||
|
|
3898b5ad45 | ||
|
|
9d15336144 |
No files matched your search
-116
@@ -1,116 +0,0 @@
|
|||||||
"""
|
|
||||||
Authentication and Authorization for Mitai Jinkendo
|
|
||||||
|
|
||||||
Provides password hashing, session management, and auth dependencies
|
|
||||||
for FastAPI endpoints.
|
|
||||||
"""
|
|
||||||
import hashlib
|
|
||||||
import secrets
|
|
||||||
from typing import Optional
|
|
||||||
from fastapi import Header, Query, HTTPException
|
|
||||||
import bcrypt
|
|
||||||
|
|
||||||
from db import get_db, get_cursor
|
|
||||||
|
|
||||||
|
|
||||||
def hash_pin(pin: str) -> str:
|
|
||||||
"""Hash password with bcrypt. Falls back gracefully from legacy SHA256."""
|
|
||||||
return bcrypt.hashpw(pin.encode(), bcrypt.gensalt()).decode()
|
|
||||||
|
|
||||||
|
|
||||||
def verify_pin(pin: str, stored_hash: str) -> bool:
|
|
||||||
"""Verify password - supports both bcrypt and legacy SHA256."""
|
|
||||||
if not stored_hash:
|
|
||||||
return False
|
|
||||||
# Detect bcrypt hash (starts with $2b$ or $2a$)
|
|
||||||
if stored_hash.startswith('$2'):
|
|
||||||
try:
|
|
||||||
return bcrypt.checkpw(pin.encode(), stored_hash.encode())
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
# Legacy SHA256 support (auto-upgrade to bcrypt on next login)
|
|
||||||
return stored_hash == hashlib.sha256(pin.encode()).hexdigest()
|
|
||||||
|
|
||||||
|
|
||||||
def make_token() -> str:
|
|
||||||
"""Generate a secure random token for sessions."""
|
|
||||||
return secrets.token_urlsafe(32)
|
|
||||||
|
|
||||||
|
|
||||||
def get_session(token: str):
|
|
||||||
"""
|
|
||||||
Get session data for a given token.
|
|
||||||
|
|
||||||
Returns session dict with profile info, or None if invalid/expired.
|
|
||||||
"""
|
|
||||||
if not token:
|
|
||||||
return None
|
|
||||||
with get_db() as conn:
|
|
||||||
cur = get_cursor(conn)
|
|
||||||
cur.execute(
|
|
||||||
"SELECT s.*, p.role, p.name, p.ai_enabled, p.ai_limit_day, p.export_enabled "
|
|
||||||
"FROM sessions s JOIN profiles p ON s.profile_id=p.id "
|
|
||||||
"WHERE s.token=%s AND s.expires_at > CURRENT_TIMESTAMP",
|
|
||||||
(token,)
|
|
||||||
)
|
|
||||||
return cur.fetchone()
|
|
||||||
|
|
||||||
|
|
||||||
def require_auth(x_auth_token: Optional[str] = Header(default=None)):
|
|
||||||
"""
|
|
||||||
FastAPI dependency - requires valid authentication.
|
|
||||||
|
|
||||||
Usage:
|
|
||||||
@app.get("/api/endpoint")
|
|
||||||
def endpoint(session: dict = Depends(require_auth)):
|
|
||||||
profile_id = session['profile_id']
|
|
||||||
...
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
HTTPException 401 if not authenticated
|
|
||||||
"""
|
|
||||||
session = get_session(x_auth_token)
|
|
||||||
if not session:
|
|
||||||
raise HTTPException(401, "Nicht eingeloggt")
|
|
||||||
return session
|
|
||||||
|
|
||||||
|
|
||||||
def require_auth_flexible(x_auth_token: Optional[str] = Header(default=None), token: Optional[str] = Query(default=None)):
|
|
||||||
"""
|
|
||||||
FastAPI dependency - auth via header OR query parameter.
|
|
||||||
|
|
||||||
Used for endpoints accessed by <img> tags that can't send headers.
|
|
||||||
|
|
||||||
Usage:
|
|
||||||
@app.get("/api/photos/{id}")
|
|
||||||
def get_photo(id: str, session: dict = Depends(require_auth_flexible)):
|
|
||||||
...
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
HTTPException 401 if not authenticated
|
|
||||||
"""
|
|
||||||
session = get_session(x_auth_token or token)
|
|
||||||
if not session:
|
|
||||||
raise HTTPException(401, "Nicht eingeloggt")
|
|
||||||
return session
|
|
||||||
|
|
||||||
|
|
||||||
def require_admin(x_auth_token: Optional[str] = Header(default=None)):
|
|
||||||
"""
|
|
||||||
FastAPI dependency - requires admin authentication.
|
|
||||||
|
|
||||||
Usage:
|
|
||||||
@app.put("/api/admin/endpoint")
|
|
||||||
def admin_endpoint(session: dict = Depends(require_admin)):
|
|
||||||
...
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
HTTPException 401 if not authenticated
|
|
||||||
HTTPException 403 if not admin
|
|
||||||
"""
|
|
||||||
session = get_session(x_auth_token)
|
|
||||||
if not session:
|
|
||||||
raise HTTPException(401, "Nicht eingeloggt")
|
|
||||||
if session['role'] != 'admin':
|
|
||||||
raise HTTPException(403, "Nur für Admins")
|
|
||||||
return session
|
|
||||||
@@ -148,48 +148,3 @@ def execute_write(conn, query: str, params: tuple = ()) -> None:
|
|||||||
"""
|
"""
|
||||||
with get_cursor(conn) as cur:
|
with get_cursor(conn) as cur:
|
||||||
cur.execute(query, params)
|
cur.execute(query, params)
|
||||||
|
|
||||||
|
|
||||||
def init_db():
|
|
||||||
"""
|
|
||||||
Initialize database with required data.
|
|
||||||
|
|
||||||
Ensures critical data exists (e.g., pipeline master prompt).
|
|
||||||
Safe to call multiple times - checks before inserting.
|
|
||||||
Called automatically on app startup.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
with get_db() as conn:
|
|
||||||
cur = get_cursor(conn)
|
|
||||||
|
|
||||||
# Check if table exists first
|
|
||||||
cur.execute("""
|
|
||||||
SELECT EXISTS (
|
|
||||||
SELECT FROM information_schema.tables
|
|
||||||
WHERE table_schema = 'public'
|
|
||||||
AND table_name = 'ai_prompts'
|
|
||||||
) as table_exists
|
|
||||||
""")
|
|
||||||
if not cur.fetchone()['table_exists']:
|
|
||||||
print("⚠️ ai_prompts table doesn't exist yet - skipping pipeline prompt creation")
|
|
||||||
return
|
|
||||||
|
|
||||||
# Ensure "pipeline" master prompt exists
|
|
||||||
cur.execute("SELECT COUNT(*) as count FROM ai_prompts WHERE slug='pipeline'")
|
|
||||||
if cur.fetchone()['count'] == 0:
|
|
||||||
cur.execute("""
|
|
||||||
INSERT INTO ai_prompts (slug, name, description, template, active, sort_order)
|
|
||||||
VALUES (
|
|
||||||
'pipeline',
|
|
||||||
'Mehrstufige Gesamtanalyse',
|
|
||||||
'Master-Schalter für die gesamte Pipeline. Deaktiviere diese Analyse, um die Pipeline komplett zu verstecken.',
|
|
||||||
'PIPELINE_MASTER',
|
|
||||||
true,
|
|
||||||
-10
|
|
||||||
)
|
|
||||||
""")
|
|
||||||
conn.commit()
|
|
||||||
print("✓ Pipeline master prompt created")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"⚠️ Could not create pipeline prompt: {e}")
|
|
||||||
# Don't fail startup - prompt can be created manually
|
|
||||||
+88
-3
@@ -15,8 +15,7 @@ from slowapi.util import get_remote_address
|
|||||||
from slowapi.errors import RateLimitExceeded
|
from slowapi.errors import RateLimitExceeded
|
||||||
from starlette.requests import Request
|
from starlette.requests import Request
|
||||||
|
|
||||||
from db import get_db, get_cursor, r2d, init_db
|
from db import get_db, get_cursor, r2d
|
||||||
from auth import hash_pin, verify_pin, make_token, get_session, require_auth, require_auth_flexible, require_admin
|
|
||||||
|
|
||||||
DATA_DIR = Path(os.getenv("DATA_DIR", "./data"))
|
DATA_DIR = Path(os.getenv("DATA_DIR", "./data"))
|
||||||
PHOTOS_DIR = Path(os.getenv("PHOTOS_DIR", "./photos"))
|
PHOTOS_DIR = Path(os.getenv("PHOTOS_DIR", "./photos"))
|
||||||
@@ -50,6 +49,46 @@ async def startup_event():
|
|||||||
print(f"⚠️ init_db() failed (non-fatal): {e}")
|
print(f"⚠️ init_db() failed (non-fatal): {e}")
|
||||||
# Don't crash on startup - pipeline prompt can be created manually
|
# Don't crash on startup - pipeline prompt can be created manually
|
||||||
|
|
||||||
|
def init_db():
|
||||||
|
"""Initialize database - Schema is loaded by startup.sh"""
|
||||||
|
# Schema loading and migration handled by startup.sh
|
||||||
|
# This function kept for backwards compatibility
|
||||||
|
|
||||||
|
# Ensure "pipeline" master prompt exists
|
||||||
|
try:
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
# Check if table exists first
|
||||||
|
cur.execute("""
|
||||||
|
SELECT EXISTS (
|
||||||
|
SELECT FROM information_schema.tables
|
||||||
|
WHERE table_schema = 'public'
|
||||||
|
AND table_name = 'ai_prompts'
|
||||||
|
) as table_exists
|
||||||
|
""")
|
||||||
|
if not cur.fetchone()['table_exists']:
|
||||||
|
print("⚠️ ai_prompts table doesn't exist yet - skipping pipeline prompt creation")
|
||||||
|
return
|
||||||
|
|
||||||
|
cur.execute("SELECT COUNT(*) as count FROM ai_prompts WHERE slug='pipeline'")
|
||||||
|
if cur.fetchone()['count'] == 0:
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO ai_prompts (slug, name, description, template, active, sort_order)
|
||||||
|
VALUES (
|
||||||
|
'pipeline',
|
||||||
|
'Mehrstufige Gesamtanalyse',
|
||||||
|
'Master-Schalter für die gesamte Pipeline. Deaktiviere diese Analyse, um die Pipeline komplett zu verstecken.',
|
||||||
|
'PIPELINE_MASTER',
|
||||||
|
true,
|
||||||
|
-10
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
print("✓ Pipeline master prompt created")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"⚠️ Could not create pipeline prompt: {e}")
|
||||||
|
# Don't fail startup - prompt can be created manually
|
||||||
|
|
||||||
# ── Helper: get profile_id from header ───────────────────────────────────────
|
# ── Helper: get profile_id from header ───────────────────────────────────────
|
||||||
def get_pid(x_profile_id: Optional[str] = Header(default=None)) -> str:
|
def get_pid(x_profile_id: Optional[str] = Header(default=None)) -> str:
|
||||||
"""Get profile_id - from header for legacy endpoints."""
|
"""Get profile_id - from header for legacy endpoints."""
|
||||||
@@ -115,9 +154,55 @@ class NutritionDay(BaseModel):
|
|||||||
fat_g: Optional[float]=None; carbs_g: Optional[float]=None
|
fat_g: Optional[float]=None; carbs_g: Optional[float]=None
|
||||||
|
|
||||||
# ── Profiles ──────────────────────────────────────────────────────────────────
|
# ── Profiles ──────────────────────────────────────────────────────────────────
|
||||||
|
import hashlib, secrets
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
|
||||||
# Auth functions moved to auth.py
|
def hash_pin(pin: str) -> str:
|
||||||
|
"""Hash password with bcrypt. Falls back gracefully from legacy SHA256."""
|
||||||
|
return bcrypt.hashpw(pin.encode(), bcrypt.gensalt()).decode()
|
||||||
|
|
||||||
|
def verify_pin(pin: str, stored_hash: str) -> bool:
|
||||||
|
"""Verify password - supports both bcrypt and legacy SHA256."""
|
||||||
|
if not stored_hash:
|
||||||
|
return False
|
||||||
|
# Detect bcrypt hash (starts with $2b$ or $2a$)
|
||||||
|
if stored_hash.startswith('$2'):
|
||||||
|
return bcrypt.checkpw(pin.encode(), stored_hash.encode())
|
||||||
|
# Legacy SHA256 fallback - auto-upgrade on successful login
|
||||||
|
import hashlib
|
||||||
|
return hashlib.sha256(pin.encode()).hexdigest() == stored_hash
|
||||||
|
|
||||||
|
def make_token() -> str:
|
||||||
|
return secrets.token_urlsafe(32)
|
||||||
|
|
||||||
|
def get_session(token: str):
|
||||||
|
if not token: return None
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"SELECT s.*, p.role, p.name, p.ai_enabled, p.ai_limit_day, p.export_enabled "
|
||||||
|
"FROM sessions s JOIN profiles p ON s.profile_id=p.id "
|
||||||
|
"WHERE s.token=%s AND s.expires_at > CURRENT_TIMESTAMP", (token,)
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
return r2d(row)
|
||||||
|
|
||||||
|
def require_auth(x_auth_token: Optional[str]=Header(default=None)):
|
||||||
|
session = get_session(x_auth_token)
|
||||||
|
if not session: raise HTTPException(401, "Nicht eingeloggt")
|
||||||
|
return session
|
||||||
|
|
||||||
|
def require_auth_flexible(x_auth_token: Optional[str]=Header(default=None), token: Optional[str]=Query(default=None)):
|
||||||
|
"""Auth via header OR query parameter (for <img> tags)."""
|
||||||
|
session = get_session(x_auth_token or token)
|
||||||
|
if not session: raise HTTPException(401, "Nicht eingeloggt")
|
||||||
|
return session
|
||||||
|
|
||||||
|
def require_admin(x_auth_token: Optional[str]=Header(default=None)):
|
||||||
|
session = get_session(x_auth_token)
|
||||||
|
if not session: raise HTTPException(401, "Nicht eingeloggt")
|
||||||
|
if session['role'] != 'admin': raise HTTPException(403, "Nur für Admins")
|
||||||
|
return session
|
||||||
|
|
||||||
@app.get("/api/profiles")
|
@app.get("/api/profiles")
|
||||||
def list_profiles(session=Depends(require_auth)):
|
def list_profiles(session=Depends(require_auth)):
|
||||||
|
|||||||
@@ -69,12 +69,6 @@ BOOLEAN_COLUMNS = {
|
|||||||
'ai_prompts': ['active'],
|
'ai_prompts': ['active'],
|
||||||
}
|
}
|
||||||
|
|
||||||
# Column whitelist for tables that have schema differences
|
|
||||||
# Only these columns will be migrated (filters out legacy columns)
|
|
||||||
COLUMN_WHITELIST = {
|
|
||||||
'ai_insights': ['id', 'profile_id', 'scope', 'content', 'created'],
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
# ================================================================
|
# ================================================================
|
||||||
# CONVERSION HELPERS
|
# CONVERSION HELPERS
|
||||||
@@ -179,17 +173,8 @@ def migrate_table(pg_conn, table: str) -> Dict[str, int]:
|
|||||||
# Convert rows
|
# Convert rows
|
||||||
converted_rows = [convert_row(row, table) for row in sqlite_rows]
|
converted_rows = [convert_row(row, table) for row in sqlite_rows]
|
||||||
|
|
||||||
# Get column names - filter if whitelist exists for this table
|
# Get column names
|
||||||
if table in COLUMN_WHITELIST:
|
columns = list(converted_rows[0].keys())
|
||||||
allowed_columns = COLUMN_WHITELIST[table]
|
|
||||||
# Filter rows to only include allowed columns
|
|
||||||
converted_rows = [
|
|
||||||
{k: v for k, v in row.items() if k in allowed_columns}
|
|
||||||
for row in converted_rows
|
|
||||||
]
|
|
||||||
columns = allowed_columns
|
|
||||||
else:
|
|
||||||
columns = list(converted_rows[0].keys())
|
|
||||||
cols_str = ', '.join(columns)
|
cols_str = ', '.join(columns)
|
||||||
placeholders = ', '.join(['%s'] * len(columns))
|
placeholders = ', '.join(['%s'] * len(columns))
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user