uploader/auth.py

42 lines
1.5 KiB
Python
Raw Normal View History

2023-12-02 05:44:06 +00:00
from functools import wraps
2024-05-06 08:24:54 +00:00
from starlette.responses import JSONResponse
2023-12-02 05:44:06 +00:00
import aiohttp
AUTH_URL = 'https://auth.discours.io'
async def check_auth(req):
token = req.headers.get("Authorization")
2024-05-06 08:24:54 +00:00
headers = {"Authorization": token, "Content-Type": "application/json"}
2023-12-02 05:44:06 +00:00
2024-05-06 08:24:54 +00:00
print(f"[services.auth] checking auth token: {token}")
2023-12-02 05:44:06 +00:00
gql = {
2024-05-06 08:24:54 +00:00
"query": "query GetUserId { session { user { id } } }",
"operationName": "GetUserId",
2023-12-02 05:44:06 +00:00
"variables": None,
}
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30.0)) as session:
async with session.post(AUTH_URL, headers=headers, json=gql) as response:
print(f"[services.auth] {AUTH_URL} response: {response.status}")
if response.status != 200:
return False, None
r = await response.json()
if r:
2024-05-06 08:24:54 +00:00
user_id = r.get("data", {}).get("session", {}).get("user", {}).get("id", None)
2023-12-02 05:44:06 +00:00
is_authenticated = user_id is not None
return is_authenticated, user_id
return False, None
def login_required(f):
@wraps(f)
2024-05-06 08:24:54 +00:00
async def decorated_function(request, *args, **kwargs):
is_authenticated, user_id = await check_auth(request)
2023-12-02 05:44:06 +00:00
if not is_authenticated:
2024-05-06 08:24:54 +00:00
return JSONResponse({'error': 'Unauthorized'}, status_code=401)
2023-12-02 05:44:06 +00:00
2024-05-06 08:24:54 +00:00
# Make user_id available to the route handler, if needed
request.state.user_id = user_id
return await f(request, *args, **kwargs)
2023-12-02 05:44:06 +00:00
return decorated_function