unmiddlewared

This commit is contained in:
2023-10-04 23:42:39 +03:00
parent 2db81462d0
commit e76f924b2d
10 changed files with 75 additions and 96 deletions

View File

@@ -11,9 +11,7 @@ from settings import AUTH_URL
from orm.author import Author
class AuthUser(BaseModel):
user_id: Optional[int]
username: Optional[str]
INTERNAL_AUTH_SERVER = "v2.discours" in AUTH_URL
class AuthCredentials(BaseModel):
@@ -26,17 +24,14 @@ class AuthCredentials(BaseModel):
class JWTAuthenticate(AuthenticationBackend):
async def authenticate(self, request: HTTPConnection):
logged_in, user_id = await check_auth(request)
return (
AuthCredentials(user_id=user_id, logged_in=logged_in),
AuthUser(user_id=user_id),
)
return AuthCredentials(user_id=user_id, logged_in=logged_in), user_id
async def check_auth(req):
token = req.headers.get("Authorization")
gql = (
{"mutation": "{ getSession { user { id } } }"}
if "v2" in AUTH_URL
if INTERNAL_AUTH_SERVER
else {"query": "{ session { user { id } } }"}
)
headers = {"Authorization": token, "Content-Type": "application/json"}
@@ -84,8 +79,9 @@ def auth_request(f):
if not is_authenticated:
raise HTTPError("please, login first")
else:
author_id = await author_id_by_user_id(user_id)
req["author_id"] = author_id
req["author_id"] = (
user_id if INTERNAL_AUTH_SERVER else await author_id_by_user_id(user_id)
)
return await f(*args, **kwargs)
return decorated_function

54
services/core.py Normal file
View File

@@ -0,0 +1,54 @@
from httpx import AsyncClient
from settings import API_BASE
async def get_author(author_id):
gql = {
"query": "{ getAuthor(author_id: %s) { id slug userpic name lastSeen } }"
% author_id
}
headers = {"Content-Type": "application/json"}
try:
async with AsyncClient() as client:
response = await client.post(API_BASE, headers=headers, data=gql)
if response.status_code != 200:
return False, None
r = response.json()
author = r.get("data", {}).get("getAuthor")
return author
except Exception:
pass
async def get_network(author_id, limit=50, offset=0):
headers = {"Content-Type": "application/json"}
gql = {
"query": "{ authorFollowings(author_id: %s, limit: %s, offset: %s) { id slug userpic name } }"
% (author_id, limit, offset)
}
followings = []
followers = []
try:
async with AsyncClient() as client:
response = await client.post(API_BASE, headers=headers, data=gql)
if response.status_code != 200:
return False, None
r = response.json()
followings = r.get("data", {}).get("authorFollowers", [])
more_amount = limit - len(followings)
if more_amount > 0:
gql = {
"query": "{ authorFollowers(author_id: %s, limit: %s) { id slug userpic name } }"
% (author_id, more_amount)
}
response = await client.post(API_BASE, headers=headers, data=gql)
if response.status_code != 200:
return False, None
r = response.json()
followers = r.get("data", {}).get("authorFollowers", [])
except Exception as e:
pass
return followings + followers