Skip to content

Commit

Permalink
Merge branch 'production' of github.com:zakarm/ft_transcendence into …
Browse files Browse the repository at this point in the history
…production
  • Loading branch information
Mushigarou committed May 6, 2024
2 parents f47c62e + 74bff1a commit 1c80d84
Show file tree
Hide file tree
Showing 22 changed files with 1,044 additions and 248 deletions.
34 changes: 14 additions & 20 deletions app/back-end/dashboards/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,14 @@ async def connect(self):
self.user = await get_user(self.scope["user"].id)
await update_user_online(self.scope['user'].id)
await self.accept()
await self.channel_layer.group_add("connected_users", self.channel_name)
await self.channel_layer.group_add("users", self.channel_name)
await self.channel_layer.group_send(
"connected_users",
"users",
{
"type": "user_connected",
"type": "user_status",
"id": self.user.id,
"user": self.user.username,
"image_url": self.user.image_url
"is_online": True,
}
)
else:
Expand All @@ -56,34 +56,28 @@ async def connect(self):
async def disconnect(self, close_code):
await update_user_offline(self.scope['user'].id)
await self.channel_layer.group_send(
"connected_users",
"users",
{
"type": "user_disconnected",
"type": "user_status",
"id": self.user.id,
"user": self.user.username,
"is_online": False,
},
)
await self.channel_layer.group_discard("connected_users", self.channel_name)


async def user_connected(self, event):
await self.send(text_data=json.dumps({
"type": "user_connected",
"id": event["id"],
"user": event["user"],
"image_url": event["image_url"]
}))
await self.channel_layer.group_discard(f"users", self.channel_name)

async def user_disconnected(self, event):
async def user_status(self, event):
await self.send(text_data=json.dumps({
"type": "user_disconnected",
"type": "user_status",
"id": event["id"],
"user": event["user"]
"user": event["user"],
"image_url": event["image_url"],
"is_online": event["is_online"]
}))

async def receive(self, text_data):
user = self.scope['user']
if user:
pass
else:
await self.close()
await self.close()
4 changes: 2 additions & 2 deletions app/back-end/dashboards/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def to_representation(self, instance):
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'image_url')
fields = ('id', 'username', 'image_url', 'is_online')

class FriendshipSerializer(serializers.ModelSerializer):
user = serializers.SerializerMethodField()
Expand All @@ -90,7 +90,7 @@ class FriendsSerializer(serializers.ModelSerializer):
friends = serializers.SerializerMethodField()
class Meta:
model = User
fields = ('id', 'username', 'friends')
fields = ('id', 'username', 'image_url', 'friends')

def get_friends(self, obj):
friends_data = Friendship.objects.filter(Q(user_from = obj)| Q(user_to= obj))
Expand Down
13 changes: 11 additions & 2 deletions app/back-end/dashboards/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
ProfileView,
ProfileIdView,
FriendsView,
UserSearchView
UserSearchView,
RemoveFriendshipView,
AcceptFriendshipView,
AddFriendshipView,
BlockFriendshipView,
UnblockFriendshipView
)

urlpatterns = [
Expand All @@ -12,5 +17,9 @@
path('profile/<str:username>', ProfileIdView.as_view(), name='profile_with_id'),
path('friends', FriendsView.as_view(), name='friends'),
path('user-search', UserSearchView.as_view(), name='user-search'),
# path('friends-remove', RemoveFriendshipView.as_view(), name="friends-remove")
path('friends-remove', RemoveFriendshipView.as_view(), name="friends-remove"),
path('friends-accept', AcceptFriendshipView.as_view(), name="friends-accept"),
path('friends-add', AddFriendshipView.as_view(), name="friends-add"),
path('friends-block', BlockFriendshipView.as_view(), name="friends-block"),
path('friends-unblock', UnblockFriendshipView.as_view(), name="friends-unblock"),
]
175 changes: 133 additions & 42 deletions app/back-end/dashboards/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,45 +65,136 @@ def post(self, request):
return Response(serializer.data)


# class RemoveFriendshipView(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)


# 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)
class RemoveFriendshipView(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))
if friendship.u_one_is_blocked_u_two == True or friendship.u_two_is_blocked_u_one == True:
return Response({'error': 'Friendship blocked'}, status=status.HTTP_400_BAD_REQUEST)
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 AcceptFriendshipView(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]

def post(self, request):
user_from = request.user
username = request.data.get('username')
try:
user_accept = 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_accept)|
Q(user_from=user_accept, user_to=user_from))
if friendship.is_accepted == True:
return Response({'error': 'Friendship already accepted'}, status=status.HTTP_400_BAD_REQUEST)
elif friendship.u_one_is_blocked_u_two == True or friendship.u_two_is_blocked_u_one == True:
return Response({'error': 'Friendship blocked'}, status=status.HTTP_400_BAD_REQUEST)
friendship.is_accepted = True;
friendship.save()
return Response({'success': 'Friendship accepted'}, 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_add = User.objects.get(username=username)
except User.DoesNotExist:
return Response({'error': 'User does not exist'}, status=status.HTTP_400_BAD_REQUEST)
if user_from.id == user_add.id:
return Response({'error': 'wach nta wa7id t ajoute rassk?'}, status=status.HTTP_400_BAD_REQUEST)
elif Friendship.objects.filter(Q(user_from=user_from, user_to=user_add) |
Q(user_from=user_add, user_to=user_from)).exists():
return Response({'error': 'Friendship alrady exist'}, status=status.HTTP_400_BAD_REQUEST)
try:

friendship = Friendship.objects.create(user_from=user_from, user_to=user_add,
is_accepted = False)
friendship.save()
return Response({'success': 'Friendship Added'}, status=status.HTTP_200_OK)
except Friendship.DoesNotExist:
return Response({'error': 'Friendship does not exist'}, status=status.HTTP_400_BAD_REQUEST)

class BlockFriendshipView(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]

def block_friend(self, friendship, user_from):
if friendship.user_from == user_from:
block_flag = 'u_one_is_blocked_u_two'
else:
block_flag = 'u_two_is_blocked_u_one'

if getattr(friendship, block_flag):
return Response({'error': 'Friend already blocked'}, status=status.HTTP_400_BAD_REQUEST)
else:
setattr(friendship, block_flag, True)
friendship.save()
return Response({'success': 'Friend blocked'}, status=status.HTTP_200_OK)

def post(self, request):
user_from = request.user
username = request.data.get('username')
try:
user_accept = 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_accept)|
Q(user_from=user_accept, user_to=user_from))
return self.block_friend(friendship, user_from)
except Friendship.DoesNotExist:
return Response({'error': 'Friendship does not exist'}, status=status.HTTP_400_BAD_REQUEST)


class UnblockFriendshipView(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]

def unblock_friend(self, friendship, user_from):
if friendship.user_from == user_from:
block_flag = 'u_one_is_blocked_u_two'
else:
block_flag = 'u_two_is_blocked_u_one'

if not getattr(friendship, block_flag):
return Response({'error': 'Friend is not blocked'}, status=status.HTTP_400_BAD_REQUEST)
else:
setattr(friendship, block_flag, False)
friendship.save()
return Response({'success': 'Friend unblocked'}, status=status.HTTP_200_OK)

def post(self, request):
user_from = request.user
username = request.data.get('username')
try:
user_accept = 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_accept)|
Q(user_from=user_accept, user_to=user_from))
return self.unblock_friend(friendship, user_from)
except Friendship.DoesNotExist:
return Response({'error': 'Friendship does not exist'}, status=status.HTTP_400_BAD_REQUEST)
15 changes: 9 additions & 6 deletions app/back-end/tools/scripts/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,13 @@
is_superuser = faker.boolean()
is_2fa_enabled = faker.boolean()
is_email_verified = faker.boolean()
is_online = 0

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);
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, is_online)
VALUES (%s, %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))
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, is_online))

# Generate fake matches
cursor.execute("SELECT id FROM authentication_users;")
Expand Down Expand Up @@ -90,12 +91,14 @@

for user_from_id, user_to_id in zip(users[::2], users[1::2]):
is_accepted = faker.boolean()
u_one_is_blocked_u_two = faker.boolean()
u_two_is_blocked_u_one = faker.boolean()

insert_query = """
INSERT INTO "Friendship" (user_from, user_to, is_accepted)
VALUES (%s, %s, %s);
INSERT INTO "Friendship" (user_from, user_to, is_accepted, u_one_is_blocked_u_two, u_two_is_blocked_u_one)
VALUES (%s, %s, %s, %s, %s);
"""
cursor.execute(insert_query, (user_from_id, user_to_id, is_accepted))
cursor.execute(insert_query, (user_from_id, user_to_id, is_accepted, u_one_is_blocked_u_two, u_two_is_blocked_u_one))

# Commit the changes and close the connection
conn.commit()
Expand Down
2 changes: 1 addition & 1 deletion app/front-end/src/app/(authentication)/sign-in/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export default function SignInPage() {
if (response.ok)
{
const data = await response.json();
console.log(data);
// console.log(data);
const {access, refresh, is_2fa_enabled, email} = data;
if (is_2fa_enabled == 'True')
{
Expand Down
2 changes: 1 addition & 1 deletion app/front-end/src/app/(authentication)/sign-up/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export default function SignUp()
if (response.ok)
{
const data = await response.json();
console.log(data);
// console.log(data);
const {access, refresh} = data;
toast.success('Successfully signed up !');
Cookies.set("access", access)
Expand Down
4 changes: 2 additions & 2 deletions app/front-end/src/app/dashboard/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import MainContainer from "../../components/mainContainer";
import AuthChecker from "../../components/authChecker";
import { WebSocketProvider } from '@/components/webSocket'
import React from 'react';
import React, { useEffect } from 'react';

export default function DashboardLayout({ children }: { children: React.ReactNode }) {
return (
Expand All @@ -14,4 +14,4 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
</WebSocketProvider>
</AuthChecker>
);
}
}
26 changes: 13 additions & 13 deletions app/front-end/src/app/dashboard/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,19 +67,19 @@ export default function Dashboard() {

if (access) {
try {
const response = await fetch('http://localhost:8000/api/dashboard', {
headers: { Authorization: `Bearer ${access}` },
});
if (response.ok) {
const data = await response.json();
setDashboardData(data);
} else if (response.status === 401) {
console.log('Unauthorized');
} else {
console.error('An unexpected error happened:', response.status);
}
const response = await fetch('http://localhost:8000/api/dashboard', {
headers: { Authorization: `Bearer ${access}` },
});
if (response.ok) {
const data = await response.json();
setDashboardData(data);
} else if (response.status === 401) {
console.log('Unauthorized');
} else {
console.error('An unexpected error happened:', response.status);
}
} catch (error) {
console.error('An unexpected error happened:', error);
console.error('An unexpected error happened:', error);
}
} else {
console.log('Access token is undefined or false');
Expand Down Expand Up @@ -166,7 +166,7 @@ export default function Dashboard() {
</div>
<div className={`row`}>
<div className={`col-12 col-md-8`}>
<h1 className={`${styles.titles} valo-font`}>THE ULTIMATE PING-PONG GAME</h1>
<h1 className={`${styles.titles} valo-font`}>THE ULTIMATE PING-PONG GAME.</h1>
</div>
</div>
<div className={`row`}>
Expand Down
Loading

0 comments on commit 1c80d84

Please sign in to comment.