auth-update
Some checks failed
deploy / deploy (push) Failing after 1m5s

This commit is contained in:
Untone 2024-04-18 14:28:10 +03:00
parent f2726633cd
commit fe069696d3
3 changed files with 76 additions and 69 deletions

View File

@ -3,9 +3,8 @@ from importlib import import_module
from os.path import exists from os.path import exists
from ariadne import load_schema_from_path, make_executable_schema from ariadne import load_schema_from_path, make_executable_schema
from starlette.applications import Starlette
from ariadne.asgi import GraphQL from ariadne.asgi import GraphQL
from starlette.applications import Starlette
from starlette.routing import Route from starlette.routing import Route
from services.logger import root_logger as logger from services.logger import root_logger as logger
@ -26,6 +25,7 @@ async def start():
f.write(str(os.getpid())) f.write(str(os.getpid()))
logger.info(f"process started in {MODE} mode") logger.info(f"process started in {MODE} mode")
# main starlette app object with ariadne mounted in root # main starlette app object with ariadne mounted in root
app = Starlette( app = Starlette(
on_startup=[ on_startup=[

View File

@ -1,11 +1,7 @@
from resolvers.chats import create_chat, delete_chat, update_chat from resolvers.chats import create_chat, delete_chat, update_chat
from resolvers.load import load_chats, load_messages_by from resolvers.load import load_chats, load_messages_by
from resolvers.messages import ( from resolvers.messages import (create_message, delete_message, mark_as_read,
create_message, update_message)
delete_message,
mark_as_read,
update_message,
)
from resolvers.search import search_messages, search_recipients from resolvers.search import search_messages, search_recipients
__all__ = [ __all__ = [

View File

@ -1,83 +1,94 @@
import logging
from functools import wraps from functools import wraps
from aiohttp import ClientSession import httpx
from starlette.exceptions import HTTPException from starlette.exceptions import HTTPException
from services.core import get_author_by_user from services.core import get_author_by_user
from services.logger import root_logger as logger from services.logger import root_logger as logger
from settings import AUTH_URL from settings import AUTH_URL
logger.setLevel(logging.DEBUG)
async def request_data(gql, headers=None):
if headers is None:
headers = {"Content-Type": "application/json"}
try:
async with httpx.AsyncClient() as client:
response = await client.post(AUTH_URL, json=gql, headers=headers)
if response.status_code == 200:
data = response.json()
errors = data.get("errors")
if errors:
logger.error(f"HTTP Errors: {errors}")
else:
return data
except Exception as e:
# Handling and logging exceptions during authentication check
logger.error(f"request_data error: {e}")
return None
async def check_auth(req): async def check_auth(req):
logger.debug("checking auth...") token = req.headers.get("Authorization")
user_id = "" user_id = ""
try: user_roles = []
token = req.headers.get("Authorization") if token:
if token: # Logging the authentication token
# Logging the authentication token logger.debug(f"{token}")
query_name = "validate_jwt_token" query_name = "validate_jwt_token"
operation = "ValidateToken" operation = "ValidateToken"
headers = { variables = {"params": {"token_type": "access_token", "token": token}}
"Content-Type": "application/json",
}
variables = { gql = {
"params": { "query": f"query {operation}($params: ValidateJWTTokenInput!) {{"
"token_type": "access_token", + f"{query_name}(params: $params) {{ is_valid claims }} "
"token": token, + "}",
} "variables": variables,
} "operationName": operation,
}
gql = { data = await request_data(gql)
"query": f"query {operation}($params: ValidateJWTTokenInput!) {{ {query_name}(params: $params) {{ is_valid claims }} }}", if data:
"variables": variables, logger.debug(data)
"operationName": operation, user_data = data.get("data", {}).get(query_name, {}).get("claims", {})
} user_id = user_data.get("sub", "")
# Asynchronous HTTP request to the authentication server user_roles = user_data.get("allowed_roles", [])
async with ClientSession() as session: return user_id, user_roles
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:
logger.error(f"{errors}")
else:
user_id = (
data.get("data", {})
.get(query_name, {})
.get("claims", {})
.get("sub")
)
logger.info(f"got user_id: {user_id}")
return user_id
except Exception as e:
# Handling and logging exceptions during authentication check
logger.error(e)
if not user_id:
raise HTTPException(status_code=401, detail="Unauthorized")
def login_required(f): def login_required(f):
@wraps(f) @wraps(f)
async def decorated_function(*args, **kwargs): async def decorated_function(*args, **kwargs):
info = args[1] info = args[1]
context = info.context req = info.context.get("request")
req = context.get("request") authorized = await check_auth(req)
user_id = await check_auth(req) if authorized:
if user_id: logger.info(authorized)
context["user_id"] = user_id.strip() user_id, user_roles = authorized
author = get_author_by_user(user_id) if user_id and user_roles:
if author and "id" in author: logger.info(f" got {user_id} roles: {user_roles}")
context["author_id"] = author["id"] info.context["user_id"] = user_id.strip()
else:
logger.debug(author)
HTTPException(status_code=401, detail="Unauthorized")
return await f(*args, **kwargs) return await f(*args, **kwargs)
return decorated_function return decorated_function
def auth_request(f):
@wraps(f)
async def decorated_function(*args, **kwargs):
req = args[0]
authorized = await check_auth(req)
if authorized:
user_id, user_roles = authorized
if user_id and user_roles:
logger.info(f" got {user_id} roles: {user_roles}")
req["user_id"] = user_id.strip()
author = get_author_by_user(user_id)
if author and "id" in author:
req["author_id"] = author["id"]
else:
logger.debug(author)
HTTPException(status_code=404, detail="Cannot find author profile")
return await f(*args, **kwargs)
else:
raise HTTPException(status_code=401, detail="Unauthorized")
return decorated_function