some-fixes-chats

This commit is contained in:
tonyrewin 2022-11-23 12:57:58 +03:00
parent 5ecb0d811b
commit 2cb152bdb1
7 changed files with 36 additions and 16 deletions

View File

@ -28,6 +28,7 @@ class SessionToken:
token is of specified type token is of specified type
""" """
try: try:
print('[auth.authenticate] session token verify')
payload = JWTCodec.decode(token) payload = JWTCodec.decode(token)
except ExpiredSignatureError: except ExpiredSignatureError:
payload = JWTCodec.decode(token, verify_exp=False) payload = JWTCodec.decode(token, verify_exp=False)
@ -58,6 +59,8 @@ class JWTAuthenticate(AuthenticationBackend):
try: try:
payload = await SessionToken.verify(token) payload = await SessionToken.verify(token)
except Exception as exc: except Exception as exc:
print("[auth.authenticate] session token verify error")
print(exc)
return AuthCredentials(scopes=[], error_message=str(exc)), AuthUser( return AuthCredentials(scopes=[], error_message=str(exc)), AuthUser(
user_id=None user_id=None
) )

View File

@ -81,6 +81,7 @@ class Identity:
@staticmethod @staticmethod
async def onetime(token: str) -> User: async def onetime(token: str) -> User:
try: try:
print('[auth.identity] using one time token')
payload = JWTCodec.decode(token) payload = JWTCodec.decode(token)
if not await TokenStorage.exist(f"{payload.user_id}-{token}"): if not await TokenStorage.exist(f"{payload.user_id}-{token}"):
raise InvalidToken("Login token has expired, please login again") raise InvalidToken("Login token has expired, please login again")

View File

@ -36,11 +36,13 @@ class TokenStorage:
@staticmethod @staticmethod
async def revoke(token: str) -> bool: async def revoke(token: str) -> bool:
payload = None
try: try:
print("[auth.tokenstorage] revoke token")
payload = JWTCodec.decode(token) payload = JWTCodec.decode(token)
except: # noqa except: # noqa
pass pass
else: finally:
await redis.execute("DEL", f"{payload.user_id}-{token}") await redis.execute("DEL", f"{payload.user_id}-{token}")
return True return True

View File

@ -1,5 +1,5 @@
from aioredis import from_url from aioredis import from_url
from asyncio import sleep
from settings import REDIS_URL from settings import REDIS_URL
@ -21,7 +21,12 @@ class RedisCache:
self._instance = None self._instance = None
async def execute(self, command, *args, **kwargs): async def execute(self, command, *args, **kwargs):
return await self._instance.execute_command(command, *args, **kwargs) while not self._instance:
await sleep(1)
try:
await self._instance.execute_command(command, *args, **kwargs)
except Exception:
pass
async def lrange(self, key, start, stop): async def lrange(self, key, start, stop):
return await self._instance.lrange(key, start, stop) return await self._instance.lrange(key, start, stop)

View File

@ -42,6 +42,7 @@ async def get_current_user(_, info):
async def confirm_email(_, info, token): async def confirm_email(_, info, token):
"""confirm owning email address""" """confirm owning email address"""
try: try:
print('[resolvers.auth] confirm email by token')
payload = JWTCodec.decode(token) payload = JWTCodec.decode(token)
user_id = payload.user_id user_id = payload.user_id
await TokenStorage.get(f"{user_id}-{token}") await TokenStorage.get(f"{user_id}-{token}")

View File

@ -33,18 +33,24 @@ async def load_messages(chatId: str, limit: int, offset: int):
async def load_chats(_, info, limit: int, offset: int): async def load_chats(_, info, limit: int, offset: int):
""" load :limit chats of current user with :offset """ """ load :limit chats of current user with :offset """
user = info.context["request"].user user = info.context["request"].user
chats = await redis.execute("GET", f"chats_by_user/{user.slug}") if user:
if chats: chats = await redis.execute("GET", f"chats_by_user/{user.slug}")
chats = list(json.loads(chats))[offset:offset + limit] if chats:
if not chats: chats = list(json.loads(chats))[offset:offset + limit]
chats = [] if not chats:
for c in chats: chats = []
c['messages'] = await load_messages(c['id'], limit, offset) for c in chats:
c['unread'] = await get_unread_counter(c['id'], user.slug) c['messages'] = await load_messages(c['id'], limit, offset)
return { c['unread'] = await get_unread_counter(c['id'], user.slug)
"chats": chats, return {
"error": None "chats": chats,
} "error": None
}
else:
return {
"error": "please login",
"chats": []
}
@query.field("loadMessagesBy") @query.field("loadMessagesBy")

View File

@ -35,8 +35,10 @@ class ReactedStorage:
@staticmethod @staticmethod
async def get_shout_stat(slug): async def get_shout_stat(slug):
viewed = await ViewedStorage.get_shout(slug)
print(viewed)
return { return {
"viewed": await ViewedStorage.get_shout(slug), "viewed": viewed,
"reacted": len(await ReactedStorage.get_shout(slug)), "reacted": len(await ReactedStorage.get_shout(slug)),
"commented": len(await ReactedStorage.get_comments(slug)), "commented": len(await ReactedStorage.get_comments(slug)),
"rating": await ReactedStorage.get_rating(slug), "rating": await ReactedStorage.get_rating(slug),