Switch to cognito user/password authentication. Major code refactor.
Some checks failed
AWS Deploy on Push / build (push) Failing after 48s

This commit is contained in:
2025-05-16 11:05:54 -05:00
parent 8d1997fa5a
commit c221a8cded
17 changed files with 220 additions and 109 deletions

View File

@@ -1,6 +1,9 @@
from fastapi import FastAPI, Depends, HTTPException
from fastapi.responses import RedirectResponse, JSONResponse
from app.cabletv.utils.auth import get_current_user, exchange_code_for_token
import uvicorn
from fastapi import FastAPI, Depends
from fastapi.responses import RedirectResponse
from app.auth.cognito import initiate_auth
from app.auth.dependencies import get_current_user, require_roles
from app.models.auth import CognitoUser, SigninRequest, TokenResponse
app = FastAPI()
@@ -8,35 +11,33 @@ app = FastAPI()
async def root():
return {"message": "IPTV Updater API"}
@app.get("/protected")
async def protected_route(user = Depends(get_current_user)):
if isinstance(user, RedirectResponse):
return user
return {"message": "Protected content", "user": user['Username']}
@app.post("/signin", response_model=TokenResponse, summary="Signin Endpoint")
def signin(credentials: SigninRequest):
"""
Sign-in endpoint to authenticate the user with AWS Cognito using username and password.
On success, returns JWT tokens (access_token, id_token, refresh_token).
"""
auth_result = initiate_auth(credentials.username, credentials.password)
return TokenResponse(
access_token=auth_result["AccessToken"],
id_token=auth_result["IdToken"],
refresh_token=auth_result.get("RefreshToken"),
token_type="Bearer",
)
@app.get("/auth/callback")
async def auth_callback(code: str):
try:
tokens = exchange_code_for_token(code)
# Use id_token instead of access_token
response = JSONResponse(content={
"message": "Authentication successful",
"id_token": tokens["id_token"] # Changed from access_token
})
# Store id_token in cookie
response.set_cookie(
key="token",
value=tokens["id_token"], # Changed from access_token
httponly=True,
secure=True,
samesite="lax"
)
return response
except Exception as e:
raise HTTPException(
status_code=400,
detail=f"Authentication failed: {str(e)}"
)
@app.get("/protected")
async def protected_route(user: CognitoUser = Depends(get_current_user)):
"""
Protected endpoint that requires for all authenticated users.
If the user is authenticates, returns success message.
"""
return {"message": f"Hello {user.username}, you have access to support resources!"}
@app.get("/protected_admin", summary="Protected endpoint for Admin role")
@require_roles("admin")
def protected_admin_endpoint(user: CognitoUser = Depends(get_current_user)):
"""
Protected endpoint that requires the 'admin' role.
If the user has 'admin' role, returns success message.
"""
return {"message": f"Hello {user.username}, you have admin privileges!"}