Added cognito authentication - Fix 9
All checks were successful
AWS Deploy on Push / build (push) Successful in 1m8s

This commit is contained in:
2025-05-15 17:08:01 -05:00
parent 30ccf86c86
commit 5c17e4b1e9
2 changed files with 21 additions and 45 deletions

View File

@@ -4,7 +4,6 @@ import requests
import jwt
from fastapi import Depends, HTTPException, status, Request
from fastapi.security import OAuth2AuthorizationCodeBearer
from fastapi.security.utils import get_authorization_scheme_param
from fastapi.responses import RedirectResponse
REGION = "us-east-2"
@@ -12,40 +11,13 @@ USER_POOL_ID = os.getenv("COGNITO_USER_POOL_ID")
CLIENT_ID = os.getenv("COGNITO_CLIENT_ID")
DOMAIN = f"https://iptv-updater.auth.{REGION}.amazoncognito.com"
class BrowserAwareOAuth2(OAuth2AuthorizationCodeBearer):
async def __call__(self, request: Request) -> str:
# Check if this is a browser request
is_browser = "text/html" in request.headers.get("accept", "")
# Try to get token from cookie first, then header
authorization = request.cookies.get("token")
if not authorization:
authorization = request.headers.get("Authorization")
scheme, param = get_authorization_scheme_param(authorization)
if not authorization or scheme.lower() != "bearer":
if is_browser:
redirect_uri = str(request.base_url) + "auth/callback"
# Return redirect for browser requests
return RedirectResponse(
f"{DOMAIN}/login?client_id={CLIENT_ID}"
f"&response_type=code"
f"&scope=openid+email+profile"
f"&redirect_uri={redirect_uri}",
status_code=302
)
# Return 401 for API requests
raise HTTPException(
status_code=401,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
return param
# Remove the hardcoded REDIRECT_URI, we'll make it dynamic based on the request
class DynamicOAuth2(OAuth2AuthorizationCodeBearer):
async def __call__(self, request: Request):
self.redirect_uri = str(request.base_url) + "auth/callback"
return await super().__call__(request)
# Update the oauth2_scheme to use our custom class
oauth2_scheme = BrowserAwareOAuth2(
oauth2_scheme = DynamicOAuth2(
authorizationUrl=f"{DOMAIN}/oauth2/authorize",
tokenUrl=f"{DOMAIN}/oauth2/token"
)