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 5, 2024
2 parents 2b15008 + 4ccf27c commit b5fe4fd
Show file tree
Hide file tree
Showing 14 changed files with 303 additions and 185 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
9 changes: 7 additions & 2 deletions app/back-end/dashboards/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
ProfileView,
ProfileIdView,
FriendsView,
UserSearchView
UserSearchView,
RemoveFriendshipView,
AcceptFriendshipView,
AddFriendshipView
)

urlpatterns = [
Expand All @@ -12,5 +15,7 @@
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"),
]
112 changes: 70 additions & 42 deletions app/back-end/dashboards/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,45 +65,73 @@ 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)
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
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>
);
}
}
24 changes: 12 additions & 12 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
1 change: 0 additions & 1 deletion app/front-end/src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import "bootstrap/dist/css/bootstrap.min.css";
import type { Metadata } from 'next'
import './global.css';
// import Bootstrap from "@/components/bootstrap";


export const metadata = {
Expand Down
Loading

0 comments on commit b5fe4fd

Please sign in to comment.