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>
33 lines
966 B
Python
33 lines
966 B
Python
from datetime import datetime, timedelta, timezone
|
|
|
|
import jwt
|
|
from pwdlib import PasswordHash
|
|
|
|
from app.core.config import get_settings
|
|
|
|
_password_hash = PasswordHash.recommended() # argon2id
|
|
ALGORITHM = "HS256"
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
return _password_hash.hash(password)
|
|
|
|
|
|
def verify_password(plain: str, hashed: str) -> bool:
|
|
return _password_hash.verify(plain, hashed)
|
|
|
|
|
|
def create_access_token(subject: str, expires_delta: timedelta | None = None) -> str:
|
|
settings = get_settings()
|
|
expire = datetime.now(timezone.utc) + (
|
|
expires_delta or timedelta(minutes=settings.access_token_expire_minutes)
|
|
)
|
|
return jwt.encode({"sub": subject, "exp": expire}, settings.secret_key, algorithm=ALGORITHM)
|
|
|
|
|
|
def decode_access_token(token: str) -> dict | None:
|
|
settings = get_settings()
|
|
try:
|
|
return jwt.decode(token, settings.secret_key, algorithms=[ALGORITHM])
|
|
except jwt.PyJWTError:
|
|
return None
|