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

This commit is contained in:
2025-05-15 16:12:49 -05:00
parent 7b7ff78030
commit 38e5a94701

View File

@@ -1,16 +1,16 @@
import os
import boto3
import requests
import jwt
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2AuthorizationCodeBearer
from fastapi.responses import RedirectResponse
from typing import Optional
REGION = "us-east-2"
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"
REDIRECT_URI = "http://localhost:8000/auth/callback"
REDIRECT_URI = f"http://localhost:8000/auth/callback"
oauth2_scheme = OAuth2AuthorizationCodeBearer(
authorizationUrl=f"{DOMAIN}/oauth2/authorize",
@@ -29,6 +29,7 @@ def exchange_code_for_token(code: str):
response = requests.post(token_url, data=data)
if response.status_code == 200:
return response.json()
print(f"Token exchange failed: {response.text}") # Add logging
raise HTTPException(status_code=400, detail="Failed to exchange code for token")
async def get_current_user(token: str = Depends(oauth2_scheme)):
@@ -36,15 +37,25 @@ async def get_current_user(token: str = Depends(oauth2_scheme)):
return RedirectResponse(
f"{DOMAIN}/login?client_id={CLIENT_ID}"
f"&response_type=code"
f"&scope=openid"
f"&scope=openid+email+profile" # Added more scopes
f"&redirect_uri={REDIRECT_URI}"
)
try:
cognito = boto3.client('cognito-idp', region_name=REGION)
response = cognito.get_user(AccessToken=token)
return response
# Decode JWT token instead of using get_user
decoded = jwt.decode(
token,
options={"verify_signature": False} # We trust tokens from Cognito
)
return {
"Username": decoded.get("email") or decoded.get("sub"),
"UserAttributes": [
{"Name": k, "Value": v}
for k, v in decoded.items()
]
}
except Exception as e:
print(f"Token verification failed: {str(e)}") # Add logging
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",