notifier/services/auth.py
Untone 25b6a6f50a
All checks were successful
deploy / deploy (push) Successful in 1m5s
tolerate-auth-for-schema-inspect
2023-12-18 10:47:50 +03:00

63 lines
2.3 KiB
Python

from functools import wraps
from aiohttp import ClientSession
from starlette.exceptions import HTTPException
from strawberry.extensions import Extension
from settings import AUTH_URL
from services.db import local_session
from orm.author import Author
async def check_auth(req) -> str | None:
token = req.headers.get("Authorization")
user_id = ""
if token:
# Logging the authentication token
print(f"[services.auth] checking auth token: {token}")
query_name = "validate_jwt_token"
operation = "ValidateToken"
headers = {
"Content-Type": "application/json",
}
variables = {
"params": {
"token_type": "access_token",
"token": token,
}
}
gql = {
"query": f"query {operation}($params: ValidateJWTTokenInput!) {{ {query_name}(params: $params) {{ is_valid claims }} }}",
"variables": variables,
"operationName": operation,
}
try:
# Asynchronous HTTP request to the authentication server
async with ClientSession() as session:
async with session.post(AUTH_URL, json=gql, headers=headers) as response:
if response.status == 200:
data = await response.json()
errors = data.get("errors")
if errors:
print(f"[services.auth] errors: {errors}")
else:
user_id = data.get("data", {}).get(query_name, {}).get("claims", {}).get("sub")
return user_id
except Exception as e:
# Handling and logging exceptions during authentication check
print(f"[services.auth] {e}")
class LoginRequiredMiddleware(Extension):
async def on_request_start(self):
context = self.execution_context.context
req = context.get("request")
user_id = await check_auth(req)
if user_id:
context["user_id"] = user_id
with local_session() as session:
author = session.query(Author).filter(Author.user == user_id).first()
if author:
context["author_id"] = author.id
context["user_id"] = user_id or None