author-id-fix
All checks were successful
deploy / deploy (push) Successful in 1m13s

This commit is contained in:
2023-11-28 12:05:39 +03:00
parent 15139249f1
commit c53b7a4c6c
7 changed files with 64 additions and 40 deletions

View File

@@ -1,5 +1,7 @@
from functools import wraps
from httpx import AsyncClient, HTTPError
from httpx import AsyncClient
from services.core import get_author
from settings import AUTH_URL
@@ -42,23 +44,13 @@ def login_required(f):
raise Exception("You are not logged in")
else:
# Добавляем author_id в контекст
context["author_id"] = user_id
author = await get_author(user_id)
if author:
context["author_id"] = author.id
elif user_id:
context["user_id"] = user_id
# Если пользователь аутентифицирован, выполняем резолвер
return await f(*args, **kwargs)
return decorated_function
def auth_request(f):
@wraps(f)
async def decorated_function(*args, **kwargs):
req = args[0]
is_authenticated, user_id = await check_auth(req)
if not is_authenticated:
raise HTTPError("please, login first")
else:
req["author_id"] = user_id
return await f(*args, **kwargs)
return decorated_function

View File

@@ -1,11 +1,30 @@
from httpx import AsyncClient
from settings import API_BASE
from typing import List
from typing import List, Any
from models.member import ChatMember
headers = {"Content-Type": "application/json"}
async def _request_endpoint(query_name, body) -> Any:
async with AsyncClient() as client:
try:
response = await client.post(API_BASE, headers=headers, json=body)
print(f"[services.core] {query_name}: [{response.status_code}] {len(response.text)} bytes")
if response.status_code != 200:
return []
r = response.json()
if r:
return r.get("data", {}).get(query_name, {})
else:
raise Exception("json response error")
except Exception:
import traceback
traceback.print_exc()
async def get_all_authors() -> List[ChatMember]:
query_name = "authorsAll"
query_type = "query"
@@ -18,20 +37,7 @@ async def get_all_authors() -> List[ChatMember]:
"variables": None,
}
async with AsyncClient() as client:
try:
response = await client.post(API_BASE, headers=headers, json=gql)
print(f"[services.core] {query_name}: [{response.status_code}] {len(response.text)} bytes")
if response.status_code != 200:
return []
r = response.json()
if r:
return r.get("data", {}).get(query_name, [])
except Exception:
import traceback
traceback.print_exc()
return []
return _request_endpoint(query_name, gql)
async def get_my_followed() -> List[ChatMember]:
@@ -60,3 +66,25 @@ async def get_my_followed() -> List[ChatMember]:
traceback.print_exc()
return []
async def get_author(author_id: int = None, slug: str = "", user: str = ""):
query_name = "get_author(author_id: $author_id, slug: $slug, user: $user)"
query_type = "query"
operation = "GetAuthor($author_id: Int, $slug: String, $user: String)"
query_fields = "id slug pic name"
vars = {}
if author_id:
vars["author_id"] = author_id
elif slug:
vars["slug"] = slug
elif user:
vars["user"] = user
gql = {
"query": query_type + " " + operation + " { " + query_name + " { " + query_fields + "} " + " }",
"operationName": operation,
"variables": None if vars == {} else vars,
}
return await _request_endpoint(query_name, gql)

View File

@@ -14,7 +14,7 @@ async def notify_message(message: Message, action="create"):
print(f"Failed to publish to channel {channel_name}: {e}")
async def notify_chat(chat: ChatUpdate, member_id, action="create"):
async def notify_chat(chat: ChatUpdate, member_id: int, action="create"):
channel_name = f"chat:{member_id}"
data = {"payload": chat, "action": action}
try: