mirror of
https://github.com/d3vyce/fastapi-toolsets.git
synced 2026-04-16 06:36:26 +02:00
25 lines
750 B
Python
25 lines
750 B
Python
"""OAuth 2.0 / OIDC helper utilities."""
|
|
|
|
import base64
|
|
|
|
|
|
def encode_oauth_state(url: str) -> str:
|
|
"""Base64url-encode a URL to embed as an OAuth ``state`` parameter."""
|
|
return base64.urlsafe_b64encode(url.encode()).decode()
|
|
|
|
|
|
def decode_oauth_state(state: str | None, *, fallback: str) -> str:
|
|
"""Decode a base64url OAuth ``state`` parameter.
|
|
|
|
Handles missing padding (some providers strip ``=``).
|
|
Returns *fallback* if *state* is absent, the literal string ``"null"``,
|
|
or cannot be decoded.
|
|
"""
|
|
if not state or state == "null":
|
|
return fallback
|
|
try:
|
|
padded = state + "=" * (4 - len(state) % 4)
|
|
return base64.urlsafe_b64decode(padded).decode()
|
|
except Exception:
|
|
return fallback
|