diff --git a/app/back-end/dashboards/consumers.py b/app/back-end/dashboards/consumers.py index b925adb5..1a7c4162 100644 --- a/app/back-end/dashboards/consumers.py +++ b/app/back-end/dashboards/consumers.py @@ -1,23 +1,48 @@ -# dashboards/consumers.py import sys from channels.generic.websocket import AsyncWebsocketConsumer import json +from django.contrib.auth.models import AnonymousUser +from rest_framework_simplejwt.tokens import AccessToken class UserStatusConsumer(AsyncWebsocketConsumer): - async def connect(self,): - self.accept() + async def connect(self): + # Get the user and authentication data from the scope + user = self.scope["user"] + auth_headers = self.scope.get("headers", []) + auth_header = None + for header in auth_headers: + if header[0].decode() == "authorization": + auth_header = header[1].decode() + break + + if user.is_authenticated: + # User is authenticated + print(f"Authenticated user: {user.username}", file=sys.stderr) + self.accept() + elif auth_header: + # Try to authenticate the user with the provided token + try: + token = auth_header.split(" ")[1] + access_token = AccessToken(token) + user = access_token.payload["user_id"] + print(f"Authenticated user: {user}", file=sys.stderr) + self.accept() + except Exception as e: + print(f"Authentication error: {e}", file=sys.stderr) + self.close() + else: + # Anonymous user + print("Anonymous user", file=sys.stderr) + 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'] except json.JSONDecodeError: message = text_data - - await self.send(text_data=json.dumps({ - 'message': message - })) + await self.send(text_data=json.dumps({'message': message})) diff --git a/app/back-end/dashboards/urls.py b/app/back-end/dashboards/urls.py index 6fd4a2bc..02fb2b61 100644 --- a/app/back-end/dashboards/urls.py +++ b/app/back-end/dashboards/urls.py @@ -3,12 +3,12 @@ ProfileView, ProfileIdView, FriendsView, - RemoveFriendshipView) + ) urlpatterns = [ path('dashboard', MainDashboardView.as_view(), name='dashboard'), path('profile', ProfileView.as_view(), name='profile'), path('profile/', ProfileIdView.as_view(), name='profile_with_id'), path('friends', FriendsView.as_view(), name='friends'), - path('friends-remove', RemoveFriendshipView.as_view(), name="friends-remove") + # path('friends-remove', RemoveFriendshipView.as_view(), name="friends-remove") ] diff --git a/app/back-end/dashboards/views.py b/app/back-end/dashboards/views.py index d3c4ad3e..d9159d97 100644 --- a/app/back-end/dashboards/views.py +++ b/app/back-end/dashboards/views.py @@ -52,23 +52,45 @@ def get(self, request): serializer = FriendsSerializer(instance=user) return Response(serializer.data) -class RemoveFriendshipView(APIView): - authentication_classes = [JWTAuthentication] - permission_classes = [IsAuthenticated] +# class RemoveFriendshipView(APIView): +# authentication_classes = [JWTAuthentication] +# permission_classes = [IsAuthenticated] - def post(self, request): - user_from = request.user - username = request.data.get('username') +# def post(self, request): +# user_from = request.user +# username = request.data.get('username') - try: - user_remove = User.objects.get(username=username) - except User.DoesNotExist: - return Response({'error': 'User does not exist'}, status=status.HTTP_400_BAD_REQUEST) +# try: +# user_remove = User.objects.get(username=username) +# except User.DoesNotExist: +# return Response({'error': 'User does not exist'}, status=status.HTTP_400_BAD_REQUEST) - try: - friendship = Friendship.objects.get(Q(user_from=user_from, user_to=user_remove)| - Q(user_from=user_remove, user_to=user_from)) - friendship.delete() - return Response({'success': 'Friendship removed'}, status=status.HTTP_200_OK) - except Friendship.DoesNotExist: - return Response({'error': 'Friendship does not exist'}, status=status.HTTP_400_BAD_REQUEST) +# try: +# friendship = Friendship.objects.get(Q(user_from=user_from, user_to=user_remove)| +# Q(user_from=user_remove, user_to=user_from)) +# friendship.delete() +# return Response({'success': 'Friendship removed'}, status=status.HTTP_200_OK) +# except Friendship.DoesNotExist: +# return Response({'error': 'Friendship does not exist'}, status=status.HTTP_400_BAD_REQUEST) + + +# class AddFriendshipView(APIView): +# authentication_classes = [JWTAuthentication] +# permission_classes = [IsAuthenticated] + +# def post(self, request): +# user_from = request.user +# username = request.data.get('username') + +# try: +# user_remove = User.objects.get(username=username) +# except User.DoesNotExist: +# return Response({'error': 'User does not exist'}, status=status.HTTP_400_BAD_REQUEST) + +# try: +# friendship = Friendship.objects.get(Q(user_from=user_from, user_to=user_remove)| +# Q(user_from=user_remove, user_to=user_from)) +# friendship.delete() +# return Response({'success': 'Friendship removed'}, status=status.HTTP_200_OK) +# except Friendship.DoesNotExist: +# return Response({'error': 'Friendship does not exist'}, status=status.HTTP_400_BAD_REQUEST) diff --git a/app/back-end/game/models.py b/app/back-end/game/models.py index 940b458c..b1ce2944 100644 --- a/app/back-end/game/models.py +++ b/app/back-end/game/models.py @@ -13,7 +13,7 @@ class Match(models.Model): tackle_user_one = models.IntegerField() tackle_user_two = models.IntegerField() class Meta: - db_table = 'Match' + db_table = 'Matches' class Tournaments(models.Model): diff --git a/app/back-end/generator.py b/app/back-end/generator.py new file mode 100644 index 00000000..2fa29968 --- /dev/null +++ b/app/back-end/generator.py @@ -0,0 +1,102 @@ +import os +import psycopg2 +from faker import Faker +from datetime import datetime + +DATABASE_HOST = os.getenv('POSTGRES_HOST', 'data-base') +DATABASE_PORT = os.getenv('POSTGRES_PORT', '5432') +DATABASE_NAME = os.getenv('POSTGRES_DB', 'postgres') +DATABASE_USER = os.getenv('POSTGRES_USER', 'postgres') +DATABASE_PASSWORD = os.getenv('POSTGRES_PASSWORD', 'postgres') + +# Connect to the PostgreSQL database +conn = psycopg2.connect( + host=DATABASE_HOST, + port=DATABASE_PORT, + database=DATABASE_NAME, + user=DATABASE_USER, + password=DATABASE_PASSWORD +) + +# Create a cursor object +cursor = conn.cursor() + +# Create a Faker instance +faker = Faker() + +# Generate fake users +for _ in range(50): + username = faker.user_name() + email = faker.email() + password = 'pbkdf2_sha256$720000$RyuAH3cW0aWocBl2a4PRpq$WTzCw+VSuwzAtgJHnIhC5d5TFFt+iCifZo0Cd425sOw=' + first_name = faker.first_name() + last_name = faker.last_name() + image_url = faker.image_url() + cover_url = faker.image_url() + location = faker.city() + is_staff = faker.boolean() + is_active = True + date_joined = datetime.now() + last_login = datetime.now() + is_superuser = faker.boolean() + is_2fa_enabled = faker.boolean() + is_email_verified = faker.boolean() + + insert_query = """ + INSERT INTO authentication_users (username, email, password, first_name, last_name, image_url, cover_url, location, is_staff, is_active, date_joined, is_superuser, last_login, is_2fa_enabled, is_email_verified) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s); + """ + cursor.execute(insert_query, (username, email, password, first_name, last_name, image_url, cover_url, location, is_staff, is_active, date_joined, is_superuser, last_login, is_2fa_enabled, is_email_verified)) + +# Generate fake matches +cursor.execute("SELECT id FROM authentication_users;") +user_ids = [row[0] for row in cursor.fetchall()] + +for _ in range(100): + user_one = faker.random_element(elements=user_ids) + user_two = faker.random_element(elements=user_ids) + score_user_one = faker.random_int(min=0, max=100) + score_user_two = faker.random_int(min=0, max=100) + match_start = faker.date_this_year() + match_end = faker.date_this_year() + tackle_user_one = faker.random_int(min=0, max=50) + tackle_user_two = faker.random_int(min=0, max=50) + + insert_query = """ + INSERT INTO "Matches" (user_one, user_two, score_user_one, score_user_two, match_start, match_end, tackle_user_one, tackle_user_two) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s); + """ + + cursor.execute(insert_query, (user_one, user_two, score_user_one, score_user_two, match_start, match_end, tackle_user_one, tackle_user_two)) + +# Generate fake tournaments +for _ in range(10): + tournament_name = faker.word() + tournament_start = faker.date_this_year() + tournament_end = faker.date_this_year() + + insert_query = """ + INSERT INTO "Tournaments" (tournament_name, tournament_start, tournament_end) + VALUES (%s, %s, %s); + """ + cursor.execute(insert_query, (tournament_name, tournament_start, tournament_end)) + +# Generate fake friendships +users = [] +cursor.execute("SELECT id FROM authentication_users;") +result = cursor.fetchall() +if result: + users = [user[0] for user in result] + +for user_from_id, user_to_id in zip(users[::2], users[1::2]): + is_accepted = faker.boolean() + + insert_query = """ + INSERT INTO "Friendship" (user_from, user_to, is_accepted) + VALUES (%s, %s, %s); + """ + cursor.execute(insert_query, (user_from_id, user_to_id, is_accepted)) + +# Commit the changes and close the connection +conn.commit() +conn.close() diff --git a/app/back-end/requirements.txt b/app/back-end/requirements.txt index 7232c29e..f6887f2b 100644 --- a/app/back-end/requirements.txt +++ b/app/back-end/requirements.txt @@ -18,4 +18,5 @@ typing-extensions asgiref daphne requests-mock -channels \ No newline at end of file +channels +faker \ No newline at end of file