Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ Poetry-managed.
in the change that fixes it.
* **Style**: no emojis or em-dashes in code or docs; do not guess APIs,
versions, flags or package names, verify in code or docs.
* **Typing**: `X | None`, never `Optional[X]`; generic classes use PEP 695
(`class Envelope[T](BaseModel)`); route dependencies are `Annotated`, via
the `SessionDep` and `CurrentUserDep` aliases in `dependencies.py`.

## Project Structure
```
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versions follo
`RequestBodyLimitMiddleware` answers 413 before any route runs (#13).

### Changed
- Annotations use the current syntax: `X | None` instead of `Optional[X]`,
`SuccessResponse` is a PEP 695 generic (`class SuccessResponse[T]`), and
every route dependency is `Annotated`, through the `SessionDep` and
`CurrentUserDep` aliases in `dependencies.py`. No behaviour change; the
OpenAPI document differs only in the envelope example's id, now a UUID (#15).
- `JWT_SECRET_KEY` minimum follows the algorithm: 32 bytes for HS256, 48 for
HS384, 64 for HS512 (RFC 7518 section 3.2), checked at startup by the tested
`config.minimum_secret_bytes()`; `decode_access_token` also passes PyJWT's
Expand Down
7 changes: 3 additions & 4 deletions src/basic_api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import logging
import uuid
from datetime import timedelta
from typing import Optional

import bcrypt
from fastapi import HTTPException, status
Expand Down Expand Up @@ -136,7 +135,7 @@ async def get_password_hash_async(password: str) -> str:
_DUMMY_PASSWORD_HASH: str = get_password_hash("_constant_time_sentinel_")


def access_token_lifetime(requested: Optional[timedelta] = None) -> timedelta:
def access_token_lifetime(requested: timedelta | None = None) -> timedelta:
"""
The lifetime a login token actually gets.

Expand All @@ -160,7 +159,7 @@ def access_token_lifetime(requested: Optional[timedelta] = None) -> timedelta:
return min(requested, maximum)


def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
"""
Create a signed JWT with the given claims plus `iat` and `exp`.

Expand Down Expand Up @@ -265,7 +264,7 @@ async def authenticate_user(
return user


async def get_user_by_id(session: AsyncSession, user_id: uuid.UUID) -> Optional[User]:
async def get_user_by_id(session: AsyncSession, user_id: uuid.UUID) -> User | None:
"""
Load a user by primary key.

Expand Down
12 changes: 10 additions & 2 deletions src/basic_api/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,15 @@
# tokenUrl is where clients obtain tokens; Swagger's Authorize dialog uses it.
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

# Dependency aliases: one token per dependency in a route signature, the style
# FastAPI's documentation recommends. CurrentUserDep is defined below
# get_current_user.
SessionDep = Annotated[AsyncSession, Depends(get_session)]


async def get_current_user(
token: Annotated[str, Depends(oauth2_scheme)],
session: AsyncSession = Depends(get_session),
session: SessionDep,
) -> User:
"""
The user the bearer token belongs to, loaded from the database.
Expand All @@ -42,7 +47,7 @@ async def get_current_user(

Example:
@router.get("/mine")
async def mine(current_user: Annotated[User, Depends(get_current_user)]):
async def mine(current_user: CurrentUserDep):
return {"username": current_user.username}
"""
payload = decode_access_token(token)
Expand Down Expand Up @@ -71,3 +76,6 @@ async def mine(current_user: Annotated[User, Depends(get_current_user)]):
detail="This account is currently disabled",
)
return user


CurrentUserDep = Annotated[User, Depends(get_current_user)]
28 changes: 14 additions & 14 deletions src/basic_api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,14 @@

from contextlib import asynccontextmanager
from datetime import timedelta
from typing import Annotated, Optional
from typing import Annotated

from fastapi import Depends, FastAPI, Query, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.security import OAuth2PasswordRequestForm
from slowapi.errors import RateLimitExceeded
from starlette.middleware.body_limit import RequestBodyLimitMiddleware
from sqlmodel.ext.asyncio.session import AsyncSession

from .auth import access_token_lifetime, authenticate_user, create_access_token
from .config import (
Expand All @@ -41,8 +40,8 @@
MAX_REQUEST_BODY_BYTES,
ROOT_PATH,
)
from .database import engine, get_session, init_db, ping
from .dependencies import get_current_user
from .database import engine, init_db, ping
from .dependencies import CurrentUserDep, SessionDep
from .exceptions import IdentifierTakenError, PasswordVerificationError
from .limiter import RATE_LIMIT_LOGIN, limiter, rate_limit_exceeded_handler
from .routers import auth, users
Expand All @@ -53,7 +52,6 @@
HealthResponse,
TokenResponse,
)
from .schemas.user import User
from .security import verify_api_key

SERVICE_NAME = "basic-api"
Expand Down Expand Up @@ -167,15 +165,17 @@ async def health_check():
async def login(
request: Request,
form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
expires_delta: Optional[timedelta] = Query(
default=None,
description=(
"Requested token lifetime, in seconds or as an ISO 8601 duration "
"(e.g. P1D). Capped at JWT_MAX_ACCESS_TOKEN_EXPIRE_MINUTES; omitted, "
"zero or negative gets JWT_ACCESS_TOKEN_EXPIRE_MINUTES."
session: SessionDep,
expires_delta: Annotated[
timedelta | None,
Query(
description=(
"Requested token lifetime, in seconds or as an ISO 8601 duration "
"(e.g. P1D). Capped at JWT_MAX_ACCESS_TOKEN_EXPIRE_MINUTES; "
"omitted, zero or negative gets JWT_ACCESS_TOKEN_EXPIRE_MINUTES."
),
),
),
session: AsyncSession = Depends(get_session),
] = None,
):
"""
OAuth2 password flow. Public: no API key needed, which also lets Swagger's
Expand Down Expand Up @@ -224,7 +224,7 @@ async def login(
responses=error_responses(401, 403),
)
async def protected_example(
current_user: Annotated[User, Depends(get_current_user)],
current_user: CurrentUserDep,
api_key: Annotated[str, Depends(verify_api_key)],
):
"""
Expand Down
13 changes: 4 additions & 9 deletions src/basic_api/routers/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,11 @@
Thin /auth/* routes around the OAuth2 + JWT flow for frontend convenience.
"""

from typing import Annotated
from fastapi import APIRouter

from fastapi import APIRouter, Depends

from ..dependencies import get_current_user
from ..dependencies import CurrentUserDep
from ..schemas import SuccessResponse, UserResponseSchema
from ..schemas.errors import error_responses
from ..schemas.user import User

router = APIRouter(prefix="/auth", tags=["Authentication"])

Expand All @@ -21,9 +18,7 @@
response_model=SuccessResponse[UserResponseSchema],
responses=error_responses(403),
)
async def get_current_user_info(
current_user: Annotated[User, Depends(get_current_user)],
):
async def get_current_user_info(current_user: CurrentUserDep):
"""
The authenticated user, as stored.

Expand Down Expand Up @@ -54,7 +49,7 @@ async def get_current_user_info(
response_model=SuccessResponse[None],
responses=error_responses(403),
)
async def logout(current_user: Annotated[User, Depends(get_current_user)]):
async def logout(current_user: CurrentUserDep):
"""
Confirm a logout. Tokens are stateless, so the client deletes its copy;
nothing is invalidated server-side (see docs/known_issues.md).
Expand Down
28 changes: 11 additions & 17 deletions src/basic_api/routers/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,16 @@
"""

import logging
from typing import Annotated

from fastapi import APIRouter, Body, Depends, HTTPException, Request
from sqlmodel.ext.asyncio.session import AsyncSession
from fastapi import APIRouter, HTTPException, Request

from ..database import get_session
from ..dependencies import get_current_user
from ..dependencies import CurrentUserDep, SessionDep
from ..exceptions import AppError
from ..limiter import RATE_LIMIT_REGISTER, limiter
from ..schemas import SuccessResponse
from ..schemas.errors import error_responses
from ..schemas.user import (
PasswordChangeSchema,
User,
UserCreateSchema,
UserDeleteSchema,
UserResponseSchema,
Expand All @@ -41,8 +37,8 @@
@limiter.limit(RATE_LIMIT_REGISTER)
async def create_user(
request: Request,
user_create: UserCreateSchema = Body(...),
session: AsyncSession = Depends(get_session),
user_create: UserCreateSchema,
session: SessionDep,
):
"""
Register a user. Rate-limited per client IP (RATE_LIMIT_REGISTER).
Expand Down Expand Up @@ -86,9 +82,7 @@ async def create_user(
response_model=SuccessResponse[UserResponseSchema],
responses=error_responses(403),
)
async def read_current_user(
current_user: Annotated[User, Depends(get_current_user)],
):
async def read_current_user(current_user: CurrentUserDep):
"""
The authenticated user's profile.

Expand All @@ -115,8 +109,8 @@ async def read_current_user(
)
async def update_current_user(
user_update: UserUpdateSchema,
current_user: Annotated[User, Depends(get_current_user)],
session: AsyncSession = Depends(get_session),
current_user: CurrentUserDep,
session: SessionDep,
):
"""
Update the authenticated user's profile.
Expand Down Expand Up @@ -164,8 +158,8 @@ async def update_current_user(
)
async def change_password(
password_change: PasswordChangeSchema,
current_user: Annotated[User, Depends(get_current_user)],
session: AsyncSession = Depends(get_session),
current_user: CurrentUserDep,
session: SessionDep,
):
"""
Change the authenticated user's password.
Expand Down Expand Up @@ -213,8 +207,8 @@ async def change_password(
)
async def delete_current_user(
body: UserDeleteSchema,
current_user: Annotated[User, Depends(get_current_user)],
session: AsyncSession = Depends(get_session),
current_user: CurrentUserDep,
session: SessionDep,
):
"""
Permanently delete the authenticated user's account.
Expand Down
19 changes: 12 additions & 7 deletions src/basic_api/schemas/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,30 @@
string for an HTTPException and a list of validation errors for a 422.
"""

from typing import Generic, Optional, TypeVar

from pydantic import BaseModel, ConfigDict, Field

T = TypeVar("T")

class SuccessResponse[T](BaseModel):
"""
Generic success response wrapper.

class SuccessResponse(BaseModel, Generic[T]):
"""Generic success response wrapper."""
`T` is the type of `data`; `SuccessResponse[UserResponseSchema]` as a
response_model names it in the OpenAPI document. PEP 695 syntax (3.12+): the
type parameter is declared in the class header, with no TypeVar or Generic.
"""

success: bool = Field(default=True, description="Always true")
data: T = Field(..., description="Response data")
message: Optional[str] = Field(default=None, description="Optional message")
message: str | None = Field(default=None, description="Optional message")

model_config = ConfigDict(
json_schema_extra={
"example": {
"success": True,
"data": {"id": 123, "username": "example"},
"data": {
"id": "0199c7a0-5f3e-7cc4-9a7b-4f1e2d3c5b6a",
"username": "example",
},
"message": "Operation completed successfully",
}
}
Expand Down
19 changes: 9 additions & 10 deletions src/basic_api/schemas/user.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import uuid
from datetime import datetime
from typing import Optional

from pydantic import (
AwareDatetime,
Expand All @@ -25,7 +24,7 @@
_HTTP_URL = TypeAdapter(HttpUrl)


def validate_http_url(value: Optional[str]) -> Optional[str]:
def validate_http_url(value: str | None) -> str | None:
"""
An http(s) URL as a string, or null.

Expand Down Expand Up @@ -59,21 +58,21 @@ class UserBase(SQLModel):
max_length=USERNAME_MAX_LENGTH,
description="Unique username",
)
email: Optional[EmailStr] = Field(
email: EmailStr | None = Field(
default=None,
index=True,
unique=True,
max_length=EMAIL_MAX_LENGTH,
description="Email address; also accepted as the login identifier",
)
phone_number: Optional[str] = Field(
phone_number: str | None = Field(
default=None,
index=True,
unique=True,
max_length=PHONE_NUMBER_MAX_LENGTH,
description="Phone number; also accepted as the login identifier",
)
profile_picture_url: Optional[str] = Field(
profile_picture_url: str | None = Field(
default=None,
max_length=URL_MAX_LENGTH,
description="http(s) URL of the profile picture",
Expand All @@ -95,7 +94,7 @@ class User(UserBase, table=True):
id: uuid.UUID = Field(default_factory=uuid.uuid7, primary_key=True)
hashed_password: str = Field(description="bcrypt hash of the SHA-256 pre-hash")
created_at: datetime = Field(default_factory=utc_now)
updated_at: Optional[datetime] = Field(
updated_at: datetime | None = Field(
default=None, sa_column_kwargs={"onupdate": utc_now}
)

Expand All @@ -114,13 +113,13 @@ class UserCreateSchema(UserBase):
# not be able to flip (a self-disabled account could never re-enable itself),
# and the password has its own route with its own confirmation.
class UserUpdateSchema(SQLModel):
email: Optional[EmailStr] = Field(
email: EmailStr | None = Field(
default=None, max_length=EMAIL_MAX_LENGTH, description="Email address"
)
phone_number: Optional[str] = Field(
phone_number: str | None = Field(
default=None, max_length=PHONE_NUMBER_MAX_LENGTH, description="Phone number"
)
profile_picture_url: Optional[HttpUrl] = Field(
profile_picture_url: HttpUrl | None = Field(
default=None, description="http(s) URL of the profile picture"
)

Expand All @@ -144,4 +143,4 @@ class UserResponseSchema(UserBase):
# AwareDatetime states the contract SQLModel's UTCDateTime fulfils: the values
# carry a zone, and serialise with it.
created_at: AwareDatetime
updated_at: Optional[AwareDatetime] = None
updated_at: AwareDatetime | None = None
Loading
Loading