feat: implement user profile management and oauth/traefik integration

User Profile (US-004):
- Add authenticated profile endpoints (GET/PUT /users/me)
- Add avatar upload with file validation (PNG/JPEG, max 2MB)
- Create frontend profile page with edit form and avatar upload
- Update app shell to link to profile page

OAuth/Traefik Integration:
- Externalize all Authentik URLs to environment variables
- Add domain configuration (API_DOMAIN, WEB_DOMAIN, AUTHENTIK_DOMAIN)
- Create docker-compose.traefik.yml for reverse proxy deployment
- Update OAuth redirect/callback URLs to use configured domains
- Add VITE_APP_URL for frontend public URL configuration

Quality gates: pytest (50 passed), ruff, mypy, npm test (12 passed), typecheck, lint, build
This commit is contained in:
Fusion
2026-05-17 23:17:10 +02:00
parent 56f440db1b
commit 577b052c05
32 changed files with 1153 additions and 16 deletions
+2 -1
View File
@@ -1,3 +1,4 @@
from src.api.auth import router as auth_router
from src.api.users import router as users_router
__all__ = ["auth_router"]
__all__ = ["auth_router", "users_router"]
+2 -2
View File
@@ -32,7 +32,7 @@ async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
@router.get("/login")
async def login() -> RedirectResponse:
settings = Settings()
redirect_uri = "http://localhost:8000/auth/callback"
redirect_uri = f"{settings.api_base_url}/auth/callback"
state = token_urlsafe(24)
location = build_login_redirect_url(
settings=settings,
@@ -57,7 +57,7 @@ async def callback(
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid state")
settings = Settings()
redirect_uri = "http://localhost:8000/auth/callback"
redirect_uri = f"{settings.api_base_url}/auth/callback"
async with httpx.AsyncClient() as client:
token_payload = await exchange_code_for_tokens(
settings=settings,
+132
View File
@@ -0,0 +1,132 @@
import uuid
from pathlib import Path
from typing import Annotated
from fastapi import APIRouter, Cookie, Depends, HTTPException, UploadFile, status
from pydantic import BaseModel, ConfigDict
from sqlalchemy.ext.asyncio import AsyncSession
from src.auth.jwt_service import decode_access_token
from src.config import Settings
from src.database import SessionLocal
from src.models.user import User
router = APIRouter(prefix="/users", tags=["users"])
UPLOAD_DIR = Path("uploads/avatars")
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
ALLOWED_CONTENT_TYPES = {"image/png", "image/jpeg", "image/jpg"}
MAX_AVATAR_SIZE = 2 * 1024 * 1024 # 2MB
async def get_db_session():
async with SessionLocal() as session:
yield session
async def get_current_user_id(
access_token: Annotated[str | None, Cookie()] = None,
) -> uuid.UUID:
if not access_token:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="missing access token")
try:
claims = decode_access_token(settings=Settings(), token=access_token)
return uuid.UUID(str(claims["sub"]))
except Exception:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid access token")
async def _get_user(session: AsyncSession, user_id: uuid.UUID) -> User:
user = await session.get(User, user_id)
if user is None:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="user not found")
return user
class UserProfileResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
email: str
name: str
avatar_url: str | None
class UserProfileUpdate(BaseModel):
name: str | None = None
email: str | None = None
@router.get("/me", response_model=UserProfileResponse)
async def get_profile(
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> User:
return await _get_user(session, user_id)
@router.put("/me", response_model=UserProfileResponse)
async def update_profile(
data: UserProfileUpdate,
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> User:
user = await _get_user(session, user_id)
if data.name is not None:
if len(data.name.strip()) == 0:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="name cannot be empty")
user.name = data.name.strip()
if data.email is not None:
if "@" not in data.email:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="invalid email")
user.email = data.email.strip()
await session.commit()
await session.refresh(user)
return user
@router.post("/me/avatar", response_model=UserProfileResponse)
async def upload_avatar(
file: UploadFile,
user_id: uuid.UUID = Depends(get_current_user_id),
session: AsyncSession = Depends(get_db_session),
) -> User:
user = await _get_user(session, user_id)
if file.content_type not in ALLOWED_CONTENT_TYPES:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"invalid file type: {file.content_type}. only png and jpg allowed",
)
content = await file.read()
if len(content) > MAX_AVATAR_SIZE:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="file too large. max size is 2mb",
)
# Delete old avatar if exists
if user.avatar_url:
old_path = UPLOAD_DIR / Path(user.avatar_url).name
if old_path.exists():
old_path.unlink()
# Save new avatar with UUID filename
filename_part = file.filename or "avatar.png"
ext = filename_part.split(".")[-1].lower() if "." in filename_part else "png"
if ext not in {"png", "jpg", "jpeg"}:
ext = "png"
filename = f"{uuid.uuid4()}.{ext}"
file_path = UPLOAD_DIR / filename
file_path.write_bytes(content)
user.avatar_url = f"/uploads/avatars/{filename}"
await session.commit()
await session.refresh(user)
return user
+4 -4
View File
@@ -23,7 +23,7 @@ def build_login_redirect_url(
"nonce": nonce,
}
)
return f"{settings.authentik_authorize_url}?{query}"
return f"{settings.resolved_authentik_authorize_url}?{query}"
async def exchange_code_for_tokens(
@@ -34,7 +34,7 @@ async def exchange_code_for_tokens(
client: httpx.AsyncClient,
) -> dict[str, str]:
response = await client.post(
settings.authentik_token_url,
settings.resolved_authentik_token_url,
data={
"grant_type": "authorization_code",
"code": code,
@@ -52,7 +52,7 @@ async def exchange_code_for_tokens(
async def fetch_jwks(*, settings: Settings, client: httpx.AsyncClient) -> dict[str, list[dict[str, str]]]:
response = await client.get(settings.authentik_jwks_url)
response = await client.get(settings.resolved_authentik_jwks_url)
response.raise_for_status()
payload = response.json()
return {"keys": payload["keys"]}
@@ -72,6 +72,6 @@ def verify_provider_access_token(
jwk_key,
algorithms=[jwk_key.get("alg", "HS256")],
audience=settings.authentik_audience,
issuer=settings.authentik_issuer,
issuer=settings.resolved_authentik_issuer,
)
return dict(claims)
+59 -4
View File
@@ -22,12 +22,22 @@ class Settings(BaseSettings):
postgres_port: int = 5432
postgres_db: str = "headquarter"
# Domain configuration
api_domain: str = "localhost"
web_domain: str = "localhost"
authentik_domain: str = "authentik.local"
# Public URLs (constructed from domains if not explicitly set)
api_public_url: str | None = None
web_public_url: str | None = None
# Authentik configuration - no hardcoded URLs
authentik_client_id: str = "headquarter-web"
authentik_client_secret: str = "change-me"
authentik_authorize_url: str = "https://authentik.local/application/o/authorize/"
authentik_token_url: str = "https://authentik.local/application/o/token/"
authentik_jwks_url: str = "https://authentik.local/application/o/headquarter-web/jwks/"
authentik_issuer: str = "https://authentik.local/application/o/headquarter-web/"
authentik_authorize_url: str | None = None
authentik_token_url: str | None = None
authentik_jwks_url: str | None = None
authentik_issuer: str | None = None
authentik_audience: str = "headquarter-web"
jwt_secret: str = "change-me-jwt-secret"
@@ -50,6 +60,51 @@ class Settings(BaseSettings):
database=self.postgres_db,
)
@property
def api_base_url(self) -> str:
if self.api_public_url:
return self.api_public_url
protocol = "https" if self.app_env == "production" else "http"
port = "" if self.app_env == "production" else ":8000"
return f"{protocol}://{self.api_domain}{port}"
@property
def web_base_url(self) -> str:
if self.web_public_url:
return self.web_public_url
protocol = "https" if self.app_env == "production" else "http"
port = "" if self.app_env == "production" else ":3000"
return f"{protocol}://{self.web_domain}{port}"
@property
def authentik_base_url(self) -> str:
protocol = "https" if self.app_env == "production" else "http"
return f"{protocol}://{self.authentik_domain}"
@property
def resolved_authentik_authorize_url(self) -> str:
if self.authentik_authorize_url:
return self.authentik_authorize_url
return f"{self.authentik_base_url}/application/o/authorize/"
@property
def resolved_authentik_token_url(self) -> str:
if self.authentik_token_url:
return self.authentik_token_url
return f"{self.authentik_base_url}/application/o/token/"
@property
def resolved_authentik_jwks_url(self) -> str:
if self.authentik_jwks_url:
return self.authentik_jwks_url
return f"{self.authentik_base_url}/application/o/{self.authentik_client_id}/jwks/"
@property
def resolved_authentik_issuer(self) -> str:
if self.authentik_issuer:
return self.authentik_issuer
return f"{self.authentik_base_url}/application/o/{self.authentik_client_id}/"
@property
def cookie_secure(self) -> bool:
return self.app_env == "production"
+4
View File
@@ -1,8 +1,12 @@
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from src.api.auth import router as auth_router
from src.api.projects import router as projects_router
from src.api.users import router as users_router
app = FastAPI(title="Headquarter API")
app.include_router(auth_router)
app.include_router(projects_router)
app.include_router(users_router)
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")