ans123's picture
Initial upload from Colab
ef1ad9e verified
from starlette.status import HTTP_401_UNAUTHORIZED
from fastapi import status, HTTPException, Depends, Request
from app.config.env import env
import jwt
import httpx
SECRET_KEY = env.AUTH0_JWT_SECRET_KEY
ALGORITHM = "HS256"
def get_token_from_header(request: Request):
auth_header = request.headers.get("Authorization")
if auth_header is None or not auth_header.startswith("Bearer "):
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
detail="Invalid token",
headers={"WWW-Authenticate": "Bearer"},
)
token = auth_header[len("Bearer "):]
return token
def decode_access_token(token: str):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
return payload
except jwt.PyJWTError:
return None
def get_current_user(request: Request):
token = get_token_from_header(request)
payload = decode_access_token(token)
if payload is None:
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
detail="Invalid token",
headers={"WWW-Authenticate": "Bearer"},
)
username: str = payload.get("sub")
if username is None:
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
detail="Invalid token payload",
headers={"WWW-Authenticate": "Bearer"},
)
return payload
def get_access_token(client_id, client_secret, domain):
url = f"https://{domain[0]}/oauth/token"
payload = {
"grant_type": "client_credentials",
"client_id": client_id[0],
"client_secret": client_secret[0],
"audience": f"https://{domain[0]}/api/v2/"
}
headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
try:
response = httpx.post(url, data=payload, headers=headers)
response.raise_for_status() # Raise an error for bad status codes
return response.json().get("access_token")
except httpx.RequestError as e:
print(f"An error occurred while requesting {e.request.url!r}.")
raise
except httpx.HTTPStatusError as e:
print(f"Error response {e.response.status_code} while requesting {e.request.url!r}.")
raise