Skip to content

Commit

Permalink
[Fix] fix validation of token and retrieve user info in game consumer…
Browse files Browse the repository at this point in the history
… file
  • Loading branch information
ael-mouz committed May 2, 2024
1 parent f524509 commit 19bc81d
Showing 1 changed file with 48 additions and 21 deletions.
69 changes: 48 additions & 21 deletions app/back-end/game/consumers.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,62 @@
# from rest_framework_simplejwt.exceptions import InvalidToken, TokenError
# from rest_framework_simplejwt.tokens import UntypedToken
# from urllib.parse import parse_qs
import sys
import json
from django.contrib.auth.models import AnonymousUser
from django.conf import settings
from channels.db import database_sync_to_async
from rest_framework_simplejwt.tokens import UntypedToken
from urllib.parse import parse_qs
from jwt import decode
from channels.generic.websocket import AsyncWebsocketConsumer
import json
import sys

from django.contrib.auth import get_user_model

User = get_user_model()


@database_sync_to_async
def get_user(user_id):
try:
user = User.objects.get(id=user_id)
return user
except User.DoesNotExist:
return AnonymousUser()


async def validate_token(token):
try:
UntypedToken(token)
decode_data = decode(token, settings.SECRET_KEY, algorithms=["HS256"])
return decode_data["user_id"]
except Exception as e:
print(f"Token is invalid: {e}", file=sys.stderr)
return None


class GameConsumer(AsyncWebsocketConsumer):
async def connect(self):
# query_string = parse_qs(self.scope['query_string'].decode())
# token = query_string.get('token')
# if not token:
# await self.close()
# else:
# try:
# UntypedToken(token[0])
# except (InvalidToken, TokenError) as e:
# await self.close()
# else:
await self.accept()
query_string = parse_qs(self.scope["query_string"].decode())
token = query_string.get("token")
if not token:
await self.close()
else:
user_id = await validate_token(token[0])
if user_id is None:
await self.close()
else:
self.scope["user"] = await get_user(user_id=user_id)
print("-" * 50, file=sys.stderr)
print(f"User: {self.scope['user']}", file=sys.stderr)
await self.accept()

async def disconnect(self, close_code):
pass

async def receive(self, text_data):
print(f"Received message: {text_data}", file = sys.stderr)
print(f"Received message: {text_data}", file=sys.stderr)
try:
text_data_json = json.loads(text_data)
message = text_data_json['message']
message = text_data_json["message"]
except json.JSONDecodeError:
message = text_data

await self.send(text_data=json.dumps({
'message': message
}))
await self.send(text_data=json.dumps({"message": message}))

0 comments on commit 19bc81d

Please sign in to comment.