52 lines
1.7 KiB
Python
52 lines
1.7 KiB
Python
|
from functools import wraps
|
||
|
import aiohttp
|
||
|
from aiohttp import web
|
||
|
|
||
|
AUTH_URL = 'https://auth.discours.io'
|
||
|
|
||
|
|
||
|
async def check_auth(req):
|
||
|
token = req.headers.get("Authorization")
|
||
|
headers = {"Authorization": token, "Content-Type": "application/json"} # "Bearer " + removed
|
||
|
print(f"[services.auth] checking auth token: {token}")
|
||
|
|
||
|
query_name = "session"
|
||
|
query_type = "query"
|
||
|
operation = "GetUserId"
|
||
|
|
||
|
gql = {
|
||
|
"query": query_type + " " + operation + " { " + query_name + " { user { id } } }",
|
||
|
"operationName": operation,
|
||
|
"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:
|
||
|
user_id = r.get("data", {}).get(query_name, {}).get("user", {}).get("id", None)
|
||
|
is_authenticated = user_id is not None
|
||
|
return is_authenticated, user_id
|
||
|
return False, None
|
||
|
|
||
|
|
||
|
def login_required(f):
|
||
|
@wraps(f)
|
||
|
async def decorated_function(*args, **kwargs):
|
||
|
info = args[1]
|
||
|
context = info.context
|
||
|
req = context.get("request")
|
||
|
is_authenticated, user_id = await check_auth(req)
|
||
|
if not is_authenticated:
|
||
|
raise web.HTTPUnauthorized(text="You are not logged in") # Return HTTP 401 Unauthorized
|
||
|
else:
|
||
|
context["user_id"] = user_id
|
||
|
|
||
|
# If the user is authenticated, execute the resolver
|
||
|
return await f(*args, **kwargs)
|
||
|
|
||
|
return decorated_function
|