connectors-upgrade
All checks were successful
deploy / deploy (push) Successful in 1m7s

This commit is contained in:
Untone 2023-12-18 10:30:14 +03:00
parent 7fa6fcf2d7
commit 315fe9fa49
2 changed files with 25 additions and 50 deletions

View File

@ -1,19 +1,20 @@
import aiohttp from functools import wraps
from aiohttp.web import HTTPUnauthorized from aiohttp import ClientSession
from starlette.exceptions import HTTPException
from strawberry.extensions import Extension from strawberry.extensions import Extension
from orm.author import Author
from services.db import local_session
from settings import AUTH_URL from settings import AUTH_URL
from services.db import local_session
from orm.author import Author
async def check_auth(req) -> str | None:
async def check_auth(req):
token = req.headers.get("Authorization") token = req.headers.get("Authorization")
user_id = ""
if token: if token:
# Logging the authentication token # Logging the authentication token
print(f"[services.auth] checking auth token: {token}") print(f"[services.auth] checking auth token: {token}")
query_name = "validate_jwt_token" query_name = "validate_jwt_token"
opeation = "ValidateToken" operation = "ValidateToken"
headers = { headers = {
"Content-Type": "application/json", "Content-Type": "application/json",
} }
@ -26,57 +27,39 @@ async def check_auth(req):
} }
gql = { gql = {
"query": f"query {opeation}($params: ValidateJWTTokenInput!) {{ {query_name}(params: $params) {{ is_valid claims }} }}", "query": f"query {operation}($params: ValidateJWTTokenInput!) {{ {query_name}(params: $params) {{ is_valid claims }} }}",
"variables": variables, "variables": variables,
"operationName": opeation, "operationName": operation,
} }
# print(f"[services.auth] Graphql: {gql}")
try: try:
# Asynchronous HTTP request to the authentication server # Asynchronous HTTP request to the authentication server
async with aiohttp.ClientSession() as session: async with ClientSession() as session:
async with session.post(AUTH_URL, json=gql, headers=headers) as response: async with session.post(AUTH_URL, json=gql, headers=headers) as response:
# Logging the GraphQL response
response_text = await response.text()
print(f"[services.auth] GraphQL Response: {response_text}")
if response.status == 200: if response.status == 200:
# Parsing JSON response
data = await response.json() data = await response.json()
errors = data.get("errors") errors = data.get("errors")
if errors: if errors:
print(f"[services.auth] errors: {errors}") print(f"[services.auth] errors: {errors}")
else: else:
user_id = data.get("data", {}).get(query_name, {}).get("claims", {}).get("sub") user_id = data.get("data", {}).get(query_name, {}).get("claims", {}).get("sub")
return user_id
if user_id:
# Logging the retrieved user ID
print(f"[services.auth] User ID retrieved: {user_id}")
return True, user_id
else:
# Logging when no user ID is found in the response
print("[services.auth] No user ID found in the response")
else:
# Logging when the request to the authentication server fails
print(f"[services.auth] Request failed with status: {response.status}")
except Exception as e: except Exception as e:
# Handling and logging exceptions during authentication check # Handling and logging exceptions during authentication check
print(f"[services.auth] {e}") print(f"[services.auth] {e}")
raise HTTPUnauthorized(text="Please, login first")
return False, None if not user_id:
raise HTTPException(status_code=401,detail="Unauthorized")
class LoginRequiredMiddleware(Extension): class LoginRequiredMiddleware(Extension):
async def on_request_start(self): async def on_request_start(self):
context = self.execution_context.context context = self.execution_context.context
req = context.get("request") req = context.get("request")
is_authenticated, user_id = await check_auth(req) user_id = await check_auth(req)
if is_authenticated: if user_id:
context["user_id"] = user_id
with local_session() as session: with local_session() as session:
author = session.query(Author).filter(Author.user == user_id).first() author = session.query(Author).filter(Author.user == user_id).first()
if author: if author:
context["author_id"] = author.id context["author_id"] = author.id
if user_id:
context["user_id"] = user_id
context["user_id"] = user_id or None context["user_id"] = user_id or None

View File

@ -5,34 +5,26 @@ import aiohttp
from settings import API_BASE from settings import API_BASE
headers = {"Content-Type": "application/json"} headers = {"Content-Type": "application/json"}
api_base = API_BASE or "https://core.discours.io"
async def _request_endpoint(query_name, body): async def _request_endpoint(query_name, body) -> Any:
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
try: async with session.post(API_BASE, headers=headers, json=body) as response:
async with session.post(API_BASE, headers=headers, json=body) as response: print(f"[services.core] {query_name} response: <{response.status}> {await response.text()}")
print(f"[services.core] {query_name}: [{response.status}] {len(await response.text())} bytes") if response.status == 200:
if response.status != 200:
return []
r = await response.json() r = await response.json()
if r: if r:
return r.get("data", {}).get(query_name, {}) return r.get("data", {}).get(query_name, {})
else: return []
raise Exception("json response error")
except Exception:
import traceback
traceback.print_exc()
async def get_followed_shouts(author_id: int): async def get_followed_shouts(author_id: int):
query_name = "load_shouts_followed" query_name = "load_shouts_followed"
query_type = "query"
operation = "GetFollowedShouts" operation = "GetFollowedShouts"
query_fields = "id slug title"
query = f"""{query_type} {operation}($author_id: Int!, limit: Int, offset: Int) {{ query = f"""query {operation}($author_id: Int!, limit: Int, offset: Int) {{
{query_name}(author_id: $author_id, limit: $limit, offset: $offset) {{ {query_fields} }} {query_name}(author_id: $author_id, limit: $limit, offset: $offset) {{ id slug title }}
}}""" }}"""
body = { body = {