Added cognito authentication - Fix 1
All checks were successful
AWS Deploy on Push / build (push) Successful in 1m28s
All checks were successful
AWS Deploy on Push / build (push) Successful in 1m28s
This commit is contained in:
47
app/main.py
47
app/main.py
@@ -1,46 +1,21 @@
|
||||
import os
|
||||
import json
|
||||
import boto3
|
||||
from jose import jwt
|
||||
from fastapi import FastAPI, Depends, HTTPException
|
||||
from fastapi.security import OAuth2AuthorizationCodeBearer
|
||||
from fastapi.responses import RedirectResponse
|
||||
from app.cabletv.utils.auth import get_current_user, DOMAIN, CLIENT_ID
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
# Get Cognito info from environment (set by userdata.sh)
|
||||
REGION = "us-east-2"
|
||||
USER_POOL_ID = os.getenv("COGNITO_USER_POOL_ID")
|
||||
CLIENT_ID = os.getenv("COGNITO_CLIENT_ID")
|
||||
|
||||
# OAuth2 scheme for authorization code flow
|
||||
oauth2_scheme = OAuth2AuthorizationCodeBearer(
|
||||
authorizationUrl=f"https://cognito-idp.{REGION}.amazonaws.com/{USER_POOL_ID}/oauth2/authorize",
|
||||
tokenUrl=f"https://cognito-idp.{REGION}.amazonaws.com/{USER_POOL_ID}/oauth2/token"
|
||||
)
|
||||
|
||||
async def get_current_user(token: str = Depends(oauth2_scheme)):
|
||||
try:
|
||||
# Verify the JWT token with Cognito
|
||||
cognito_idp = boto3.client('cognito-idp', region_name=REGION)
|
||||
response = cognito_idp.get_user(
|
||||
AccessToken=token
|
||||
)
|
||||
return response
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Invalid authentication credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {"message": "IPTV Updater API"}
|
||||
|
||||
@app.get("/health")
|
||||
async def health():
|
||||
return {"status": "healthy"}
|
||||
|
||||
@app.get("/protected")
|
||||
async def protected_route(user = Depends(get_current_user)):
|
||||
return {"message": "This is a protected route", "user": user['Username']}
|
||||
if isinstance(user, RedirectResponse):
|
||||
return user
|
||||
return {"message": "Protected content", "user": user['Username']}
|
||||
|
||||
@app.get("/auth/callback")
|
||||
async def auth_callback(code: str):
|
||||
# Here you would exchange the code for tokens
|
||||
# For now, just redirect to protected route
|
||||
return {"auth_code": code}
|
||||
Reference in New Issue
Block a user