Password hashing via pwdlib (argon2id), stateless JWT auth (2h expiry) delivered as an Authorization: Bearer token, with an OAuth2PasswordBearer dependency (app/dependencies.py) protecting future routes. Establishes app/routers/ as the convention for feature routes, explicitly registered in main.py (no auto-discovery, unlike app/models/). The first admin user is seeded via an Alembic data migration gated on SUPERUSER_EMAIL/SUPERUSER_PASSWORD env vars (read at migration-run time only, never persisted to .env/git) rather than a script or open endpoint, so a fresh `alembic upgrade head` still succeeds without them. The migration mirrors the users/organization tables locally instead of importing the live SQLModel classes, keeping it a stable schema snapshot; it does import app.core.security.hash_password, a pure utility with no table-shape dependency. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
37 lines
1.2 KiB
Python
37 lines
1.2 KiB
Python
from typing import Annotated
|
|
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
|
|
from app.core.security import decode_access_token
|
|
from app.db import SessionDep
|
|
from app.models.user import User
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/login")
|
|
|
|
|
|
def get_current_user(session: SessionDep, token: Annotated[str, Depends(oauth2_scheme)]) -> User:
|
|
credentials_exception = HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
payload = decode_access_token(token)
|
|
if payload is None or payload.get("sub") is None:
|
|
raise credentials_exception
|
|
user = session.get(User, int(payload["sub"]))
|
|
if user is None or not user.is_active:
|
|
raise credentials_exception
|
|
return user
|
|
|
|
|
|
CurrentUser = Annotated[User, Depends(get_current_user)]
|
|
|
|
|
|
def get_current_active_superuser(current_user: CurrentUser) -> User:
|
|
if not current_user.is_superadmin:
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not enough privileges")
|
|
return current_user
|
|
|
|
|
|
CurrentSuperuser = Annotated[User, Depends(get_current_active_superuser)]
|