Skip to content

Commit

Permalink
Merge branch 'production' of https://github.com/zakarm/ft_transcendence
Browse files Browse the repository at this point in the history
… into wip/chatfolio
  • Loading branch information
Nouakchi committed May 2, 2024
2 parents ed69365 + 6c828b6 commit 6133fa0
Show file tree
Hide file tree
Showing 6 changed files with 179 additions and 29 deletions.
41 changes: 33 additions & 8 deletions app/back-end/dashboards/consumers.py
Original file line number Diff line number Diff line change
@@ -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}))
4 changes: 2 additions & 2 deletions app/back-end/dashboards/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -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/<str:username>', 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")
]
56 changes: 39 additions & 17 deletions app/back-end/dashboards/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
2 changes: 1 addition & 1 deletion app/back-end/game/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
102 changes: 102 additions & 0 deletions app/back-end/generator.py
Original file line number Diff line number Diff line change
@@ -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()
3 changes: 2 additions & 1 deletion app/back-end/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ typing-extensions
asgiref
daphne
requests-mock
channels
channels
faker

0 comments on commit 6133fa0

Please sign in to comment.