Bases: BaseHTTPMiddleware, LoggingMixin
Authentication middleware using cookie-based sessions.
Source code in audex/lib/server/auth.py
| def __init__(self, app: ASGIApp, doctor_repo: DoctorRepository):
super().__init__(app)
self.doctor_repo = doctor_repo
|
Functions
dispatch async
dispatch(request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response
Process request with authentication check.
Source code in audex/lib/server/auth.py
| async def dispatch(
self, request: Request, call_next: t.Callable[[Request], t.Awaitable[Response]]
) -> Response:
"""Process request with authentication check."""
# Check if route is public
if self._is_public_route(request.url.path):
return await call_next(request)
# Get session from cookie
session_data = self._get_session_from_cookie(request)
if not session_data:
# Not authenticated, redirect to login
if request.url.path.startswith("/api/"):
return Response(
content=json.dumps({"error": "Unauthorized"}),
status_code=401,
media_type="application/json",
)
return RedirectResponse(url="/login", status_code=303)
# Verify doctor still exists and is active
doctor = await self.doctor_repo.read(session_data["doctor_id"])
if not doctor or not doctor.is_active:
# Session invalid, clear cookie
response = RedirectResponse(url="/login", status_code=303)
response.delete_cookie(self.COOKIE_NAME)
return response
# Attach session data to request state
request.state.doctor_session = session_data
return await call_next(request)
|
create_session_cookie staticmethod
Create encoded session cookie value.
Source code in audex/lib/server/auth.py
| @staticmethod
def create_session_cookie(session_data: DoctorSessionData) -> str:
"""Create encoded session cookie value."""
json_str = json.dumps(session_data)
return base64.b64encode(json_str.encode("utf-8")).decode("utf-8")
|