cached-auth
This commit is contained in:
parent
987eb8c078
commit
c41fe8b6c9
|
@ -63,13 +63,15 @@ def followed_communities(follower_id):
|
||||||
def community_follow(follower_id, slug):
|
def community_follow(follower_id, slug):
|
||||||
try:
|
try:
|
||||||
with local_session() as session:
|
with local_session() as session:
|
||||||
community = session.query(Community).where(Community.slug == slug).one()
|
community = session.query(Community).where(Community.slug == slug).first()
|
||||||
cf = CommunityAuthor(author=follower_id, community=community.id)
|
if isinstance(community, Community):
|
||||||
session.add(cf)
|
cf = CommunityAuthor(author=follower_id, community=community.id)
|
||||||
session.commit()
|
session.add(cf)
|
||||||
return True
|
session.commit()
|
||||||
|
return True
|
||||||
except Exception:
|
except Exception:
|
||||||
return False
|
pass
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
# for mutation.field("unfollow")
|
# for mutation.field("unfollow")
|
||||||
|
|
|
@ -142,7 +142,7 @@ async def set_published(session, shout_id, approver_id):
|
||||||
s = session.query(Shout).where(Shout.id == shout_id).first()
|
s = session.query(Shout).where(Shout.id == shout_id).first()
|
||||||
s.published_at = int(time.time())
|
s.published_at = int(time.time())
|
||||||
s.published_by = approver_id
|
s.published_by = approver_id
|
||||||
s.visibility = ShoutVisibility.PUBLIC.value
|
Shout.update(s, {"visibility": ShoutVisibility.PUBLIC.value})
|
||||||
author = session.query(Author).filter(Author.id == s.created_by).first()
|
author = session.query(Author).filter(Author.id == s.created_by).first()
|
||||||
if author:
|
if author:
|
||||||
await add_user_role(str(author.user))
|
await add_user_role(str(author.user))
|
||||||
|
@ -152,7 +152,7 @@ async def set_published(session, shout_id, approver_id):
|
||||||
|
|
||||||
def set_hidden(session, shout_id):
|
def set_hidden(session, shout_id):
|
||||||
s = session.query(Shout).where(Shout.id == shout_id).first()
|
s = session.query(Shout).where(Shout.id == shout_id).first()
|
||||||
s.visibility = ShoutVisibility.COMMUNITY.value
|
Shout.update(s, {"visibility": ShoutVisibility.COMMUNITY.value})
|
||||||
session.add(s)
|
session.add(s)
|
||||||
session.commit()
|
session.commit()
|
||||||
|
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
from functools import wraps
|
from cachetools import TTLCache, cached
|
||||||
import logging
|
import logging
|
||||||
|
import time
|
||||||
from aiohttp import ClientSession
|
|
||||||
from starlette.exceptions import HTTPException
|
from starlette.exceptions import HTTPException
|
||||||
|
|
||||||
|
from aiohttp import ClientSession
|
||||||
from settings import AUTH_URL, AUTH_SECRET
|
from settings import AUTH_URL, AUTH_SECRET
|
||||||
|
|
||||||
|
|
||||||
|
@ -11,10 +11,11 @@ logging.basicConfig()
|
||||||
logger = logging.getLogger("\t[services.auth]\t")
|
logger = logging.getLogger("\t[services.auth]\t")
|
||||||
logger.setLevel(logging.DEBUG)
|
logger.setLevel(logging.DEBUG)
|
||||||
|
|
||||||
|
# Define a TTLCache with a time-to-live of 100 seconds
|
||||||
|
token_cache = TTLCache(maxsize=99999, ttl=1799)
|
||||||
|
|
||||||
async def request_data(gql, headers = { "Content-Type": "application/json" }):
|
async def request_data(gql, headers={"Content-Type": "application/json"}):
|
||||||
try:
|
try:
|
||||||
# Asynchronous HTTP request to the authentication server
|
|
||||||
async with 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:
|
||||||
if response.status == 200:
|
if response.status == 200:
|
||||||
|
@ -25,40 +26,46 @@ async def request_data(gql, headers = { "Content-Type": "application/json" }):
|
||||||
else:
|
else:
|
||||||
return data
|
return data
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Handling and logging exceptions during authentication check
|
|
||||||
logger.error(f"[services.auth] request_data error: {e}")
|
logger.error(f"[services.auth] request_data error: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
@cached(cache=token_cache)
|
||||||
|
async def user_id_from_token(token):
|
||||||
|
logger.error(f"[services.auth] checking auth token: {token}")
|
||||||
|
query_name = "validate_jwt_token"
|
||||||
|
operation = "ValidateToken"
|
||||||
|
variables = {
|
||||||
|
"params": {
|
||||||
|
"token_type": "access_token",
|
||||||
|
"token": token,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
gql = {
|
||||||
|
"query": f"query {operation}($params: ValidateJWTTokenInput!) {{ {query_name}(params: $params) {{ is_valid claims }} }}",
|
||||||
|
"variables": variables,
|
||||||
|
"operationName": operation,
|
||||||
|
}
|
||||||
|
data = await request_data(gql)
|
||||||
|
if data:
|
||||||
|
expires_in = data.get("data", {}).get(query_name, {}).get("claims", {}).get("expires_in")
|
||||||
|
user_id = data.get("data", {}).get(query_name, {}).get("claims", {}).get("sub")
|
||||||
|
if expires_in is not None and user_id is not None:
|
||||||
|
if expires_in < 100:
|
||||||
|
# Token will expire soon, remove it from cache
|
||||||
|
token_cache.pop(token, None)
|
||||||
|
else:
|
||||||
|
expires_at = time.time() + expires_in
|
||||||
|
return user_id, expires_at
|
||||||
|
|
||||||
async def check_auth(req) -> str | None:
|
async def check_auth(req) -> str | None:
|
||||||
token = req.headers.get("Authorization")
|
token = req.headers.get("Authorization")
|
||||||
user_id = ""
|
cached_result = await user_id_from_token(token)
|
||||||
if token:
|
if cached_result:
|
||||||
# Logging the authentication token
|
user_id, expires_at = cached_result
|
||||||
logger.error(f"[services.auth] checking auth token: {token}")
|
if expires_at > time.time():
|
||||||
query_name = "validate_jwt_token"
|
|
||||||
operation = "ValidateToken"
|
|
||||||
variables = {
|
|
||||||
"params": {
|
|
||||||
"token_type": "access_token",
|
|
||||||
"token": token,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
gql = {
|
|
||||||
"query": f"query {operation}($params: ValidateJWTTokenInput!) {{ {query_name}(params: $params) {{ is_valid claims }} }}",
|
|
||||||
"variables": variables,
|
|
||||||
"operationName": operation,
|
|
||||||
}
|
|
||||||
data = await request_data(gql)
|
|
||||||
if data:
|
|
||||||
user_id = data.get("data", {}).get(query_name, {}).get("claims", {}).get("sub")
|
|
||||||
return user_id
|
return user_id
|
||||||
|
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||||
if not user_id:
|
|
||||||
raise HTTPException(status_code=401, detail="Unauthorized")
|
|
||||||
|
|
||||||
|
|
||||||
async def add_user_role(user_id):
|
async def add_user_role(user_id):
|
||||||
logger.info(f"[services.auth] add author role for user_id: {user_id}")
|
logger.info(f"[services.auth] add author role for user_id: {user_id}")
|
||||||
|
@ -77,7 +84,6 @@ async def add_user_role(user_id):
|
||||||
return user_id
|
return user_id
|
||||||
|
|
||||||
def login_required(f):
|
def login_required(f):
|
||||||
@wraps(f)
|
|
||||||
async def decorated_function(*args, **kwargs):
|
async def decorated_function(*args, **kwargs):
|
||||||
info = args[1]
|
info = args[1]
|
||||||
context = info.context
|
context = info.context
|
||||||
|
@ -89,9 +95,7 @@ def login_required(f):
|
||||||
|
|
||||||
return decorated_function
|
return decorated_function
|
||||||
|
|
||||||
|
|
||||||
def auth_request(f):
|
def auth_request(f):
|
||||||
@wraps(f)
|
|
||||||
async def decorated_function(*args, **kwargs):
|
async def decorated_function(*args, **kwargs):
|
||||||
req = args[0]
|
req = args[0]
|
||||||
user_id = await check_auth(req)
|
user_id = await check_auth(req)
|
||||||
|
|
Loading…
Reference in New Issue
Block a user