Skip to content

Commit c91567e

Browse files
Further changes to prepare for splitting access token parsing (#926)
* Refactor Authenticator route creation * Type hint Authenticator routes * Refactor auth router construction * Remove get_authenticators * Add changelog entry
1 parent 19d4d59 commit c91567e

File tree

5 files changed

+455
-502
lines changed

5 files changed

+455
-502
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ Write the date in place of the "Unreleased" in the case a new version is release
2323
TILED_SERVER_SECRET_KEYS is now TILED_SECRET_KEYS and these fields now require passing a json
2424
list e.g. ``TILED_SECRET_KEYS='["one", "two"]'``
2525
- More type hinting
26+
- Refactor authentication router construction
2627

2728
## 0.1.0-b20 (2025-03-07)
2829

tiled/server/app.py

Lines changed: 12 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,13 @@
1010
from contextlib import asynccontextmanager
1111
from functools import cache, partial
1212
from pathlib import Path
13-
from typing import Optional
13+
from typing import Optional, Union
1414

1515
import anyio
1616
import packaging.version
1717
import yaml
1818
from asgi_correlation_id import CorrelationIdMiddleware, correlation_id
19-
from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request, Response
19+
from fastapi import Depends, FastAPI, HTTPException, Request, Response
2020
from fastapi.exception_handlers import http_exception_handler
2121
from fastapi.middleware.cors import CORSMiddleware
2222
from fastapi.openapi.utils import get_openapi
@@ -52,13 +52,7 @@
5252
from .dependencies import get_root_tree
5353
from .router import get_router
5454
from .settings import Settings, get_settings
55-
from .utils import (
56-
API_KEY_COOKIE_NAME,
57-
CSRF_COOKIE_NAME,
58-
get_authenticators,
59-
get_root_url,
60-
record_timing,
61-
)
55+
from .utils import API_KEY_COOKIE_NAME, CSRF_COOKIE_NAME, get_root_url, record_timing
6256

6357
SAFE_METHODS = {"GET", "HEAD", "OPTIONS", "TRACE"}
6458
SENSITIVE_COOKIES = {
@@ -134,7 +128,7 @@ def build_app(
134128
Dict of other server configuration.
135129
"""
136130
authentication = authentication or {}
137-
authenticators = {
131+
authenticators: dict[str, Union[ExternalAuthenticator, InternalAuthenticator]] = {
138132
spec["provider"]: spec["authenticator"]
139133
for spec in authentication.get("providers", [])
140134
}
@@ -354,6 +348,7 @@ async def unhandled_exception_handler(
354348
serialization_registry,
355349
deserialization_registry,
356350
validation_registry,
351+
authenticators,
357352
)
358353
app.include_router(router, prefix="/api/v1")
359354

@@ -368,13 +363,9 @@ async def unhandled_exception_handler(
368363
# Delay this imports to avoid delaying startup with the SQL and cryptography
369364
# imports if they are not needed.
370365
from .authentication import (
371-
base_authentication_router,
372-
build_auth_code_route,
373-
build_device_code_authorize_route,
374-
build_device_code_token_route,
375-
build_device_code_user_code_form_route,
376-
build_device_code_user_code_submit_route,
377-
build_handle_credentials_route,
366+
add_external_routes,
367+
add_internal_routes,
368+
authentication_router,
378369
oauth2_scheme,
379370
)
380371

@@ -385,41 +376,17 @@ async def unhandled_exception_handler(
385376
)
386377
# Authenticators provide Router(s) for their particular flow.
387378
# Collect them in the authentication_router.
388-
authentication_router = APIRouter()
379+
authentication_router = authentication_router()
389380
# This adds the universal routes like /session/refresh and /session/revoke.
390381
# Below we will add routes specific to our authentication providers.
391-
authentication_router.include_router(base_authentication_router)
382+
392383
for spec in authentication["providers"]:
393384
provider = spec["provider"]
394385
authenticator = spec["authenticator"]
395386
if isinstance(authenticator, InternalAuthenticator):
396-
authentication_router.post(f"/provider/{provider}/token")(
397-
build_handle_credentials_route(authenticator, provider)
398-
)
387+
add_internal_routes(authentication_router, provider, authenticator)
399388
elif isinstance(authenticator, ExternalAuthenticator):
400-
# Client starts here to create a PendingSession.
401-
authentication_router.post(f"/provider/{provider}/authorize")(
402-
build_device_code_authorize_route(authenticator, provider)
403-
)
404-
# External OAuth redirects here with code, presenting form for user code.
405-
authentication_router.get(f"/provider/{provider}/device_code")(
406-
build_device_code_user_code_form_route(authenticator, provider)
407-
)
408-
# User code and auth code are submitted here.
409-
authentication_router.post(f"/provider/{provider}/device_code")(
410-
build_device_code_user_code_submit_route(authenticator, provider)
411-
)
412-
# Client polls here for token.
413-
authentication_router.post(f"/provider/{provider}/token")(
414-
build_device_code_token_route(authenticator, provider)
415-
)
416-
# Normal code flow end point for web UIs
417-
authentication_router.get(f"/provider/{provider}/code")(
418-
build_auth_code_route(authenticator, provider)
419-
)
420-
# authentication_router.post(f"/provider/{provider}/code")(
421-
# build_auth_code_route(authenticator, provider)
422-
# )
389+
add_external_routes(authentication_router, provider, authenticator)
423390
else:
424391
raise ValueError(f"unknown authenticator type {type(authenticator)}")
425392
for custom_router in getattr(authenticator, "include_routers", []):
@@ -432,10 +399,6 @@ async def unhandled_exception_handler(
432399
else:
433400
app.state.authenticated = False
434401

435-
@cache
436-
def override_get_authenticators():
437-
return authenticators
438-
439402
@cache
440403
def override_get_root_tree():
441404
return tree
@@ -761,7 +724,6 @@ async def set_cookies(request: Request, call_next):
761724
return response
762725

763726
app.openapi = partial(custom_openapi, app)
764-
app.dependency_overrides[get_authenticators] = override_get_authenticators
765727
app.dependency_overrides[get_root_tree] = override_get_root_tree
766728
app.dependency_overrides[get_settings] = override_get_settings
767729

0 commit comments

Comments
 (0)