File size: 2,325 Bytes
ef1ad9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

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