server-start

This commit is contained in:
2023-10-03 18:29:56 +03:00
parent 53e0a7c3e4
commit 9e69f506db
8 changed files with 372 additions and 41 deletions

View File

@@ -1,19 +1,38 @@
from typing import Optional
from pydantic import BaseModel
from functools import wraps
from gql.transport import aiohttp
import aiohttp
import json
from starlette.authentication import AuthenticationBackend
from starlette.requests import HTTPConnection
from graphql.error import GraphQLError
from httpx import AsyncClient
from services.db import local_session
from settings import AUTH_URL
from orm.author import Author
from graphql.error import GraphQLError
class BaseHttpException(GraphQLError):
code = 500
message = "500 Server error"
class AuthUser(BaseModel):
user_id: Optional[int]
username: Optional[str]
class Unauthorized(BaseHttpException):
class AuthCredentials(BaseModel):
user_id: Optional[int] = None
scopes: Optional[dict] = {}
logged_in: bool = False
error_message: str = ""
class JWTAuthenticate(AuthenticationBackend):
async def authenticate(self, request: HTTPConnection):
scopes = {} # TODO: integrate await user.get_permission
logged_in, user_id = await check_auth(request)
return (
AuthCredentials(user_id=user_id, scopes=scopes, logged_in=logged_in),
AuthUser(user_id=user_id, username=""),
)
class Unauthorized(GraphQLError):
code = 401
message = "401 Unauthorized"
@@ -26,16 +45,14 @@ async def check_auth(req):
else {"query": "{ session { user { id } } }"}
)
headers = {"Authorization": token, "Content-Type": "application/json"}
async with aiohttp.ClientSession(headers=headers) as session:
async with session.post(AUTH_URL, data=json.dumps(gql)) as response:
if response.status != 200:
return False, None
r = await response.json()
user_id = (
r.get("data", {}).get("session", {}).get("user", {}).get("id", None)
)
is_authenticated = user_id is not None
return is_authenticated, user_id
async with AsyncClient() as client:
response = await client.post(AUTH_URL, headers=headers, data=gql)
if response.status_code != 200:
return False, None
r = response.json()
user_id = r.get("data", {}).get("session", {}).get("user", {}).get("id", None)
is_authenticated = user_id is not None
return is_authenticated, user_id
def author_id_by_user_id(user_id):