Skip to content

Commit

Permalink
we updated game_server docker file and removed versions of packages a…
Browse files Browse the repository at this point in the history
…nd also we had a mistake in token_service app inside of views.py where we mocked our user by mistake we had id 1 which we had fixed
  • Loading branch information
abbastoof committed Jul 10, 2024
1 parent cc80562 commit a3004bb
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 41 deletions.
28 changes: 14 additions & 14 deletions Backend/profile_service/profile_service/profile_app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ def login(self, request, *args, **kwargs) -> Response:
"""
Post method to generate tokens for the user.
This method overrides the post method of TokenObtainPairView to generate tokens for the user.
This method overrides the post method of TokenObtainPairView to generate tokens for the user.
It sends a request to the user service to validate the user credentials
and get the user data. It then generates the tokens for the user and returns the tokens in the response.
Args:
request: The request object.
Returns:
Response: The response object containing the tokens.
"""
Expand All @@ -41,7 +41,7 @@ def login(self, request, *args, **kwargs) -> Response:

# Define a callback function to process the message
def handle_response(ch, method, properties, body):
nonlocal user_data
nonlocal user_data #
user_data.update(json.loads(body))
ch.stop_consuming()

Expand All @@ -60,23 +60,23 @@ def handle_response(ch, method, properties, body):
"refresh":serializer["token_data"]["refresh"],
"access":serializer["token_data"]["access"]}
except UserTokens.DoesNotExist:
publish_message("user_token_request_queue", json.dumps({"username": username}))
publish_message("user_token_request_queue", json.dumps({"id": user_data["id"], "username": username}))

user_token_data = {}

def handle_token_response(ch, method, properties, body):
nonlocal user_token_data
user_token_data.update(json.loads(body))
ch.stop_consuming()

consume_message("user_token_response_queue", handle_token_response)

if "error" in user_token_data:
return Response(
{"error": "Invalid credentials"}, status=status.HTTP_401_UNAUTHORIZED
)
response_messsage = {"id": user_data["id"],

response_messsage = {"id": user_data["id"],
"refresh":user_token_data["refresh"],
"access":user_token_data["access"]}

Expand All @@ -89,9 +89,9 @@ def handle_token_response(ch, method, properties, body):
})

if serializer.is_valid():
serializer.save()
serializer.save()
return Response(response_messsage, status=status.HTTP_200_OK)


def logout(self, request, *args, **kwargs) -> Response:
"""
Expand All @@ -101,7 +101,7 @@ def logout(self, request, *args, **kwargs) -> Response:
Args:
request: The request object.
Returns:
Response: The response object containing the message.
"""
Expand All @@ -112,7 +112,7 @@ def logout(self, request, *args, **kwargs) -> Response:
user_id = request.data.get("id")
user = get_object_or_404(UserTokens, id=user_id)
user.delete()
return Response({'detail': 'Successfully logged out'}, status=status.HTTP_200_OK)
return Response({'detail': 'Successfully logged out'}, status=status.HTTP_200_OK)

class ValidateToken():
@staticmethod
Expand All @@ -125,7 +125,7 @@ def validate_token(access_token) -> bool:
Args:
access_token: The refresh token to validate.
Returns:
bool: True if the token is valid, False otherwise.
"""
Expand All @@ -136,7 +136,7 @@ def validate_token(access_token) -> bool:
return False
except jwt.InvalidTokenError:
return False

def validate_token_request_queue(self, ch, method, properties, body):
"""
Method to handle the token validation request.
Expand Down Expand Up @@ -168,4 +168,4 @@ def validate_token_request_queue(self, ch, method, properties, body):
publish_message("validate_token_response_queue", json.dumps(response))

def start_consumer(self) -> None:
consume_message("validate_token_request_queue", self.validate_token_request_queue)
consume_message("validate_token_request_queue", self.validate_token_request_queue)
7 changes: 4 additions & 3 deletions Backend/token_service/token_service/token_app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ def handle_token_request(ch, method, properties, body):
"""
data = json.loads(body)
username = data.get("username")
user = type('User', (object,), {"id": 1, "username": username})
id = data.get("id")
user = type('User', (object,), {"id": id, "username": username})
refresh = RefreshToken.for_user(user)
access_token = str(refresh.access_token)
publish_message("user_token_response_queue", json.dumps({"refresh": str(refresh), "access": access_token}))
Expand All @@ -61,7 +62,7 @@ def post(self, request, *args, **kwargs) -> Response:
request: The request object.
Returns:
Response: The response object containing the new access token.
Response: The response object containing the new access token.
"""
bearer = request.headers.get("Authorization")
if not bearer or not bearer.startswith('Bearer '):
Expand All @@ -74,4 +75,4 @@ def post(self, request, *args, **kwargs) -> Response:
access_token = str(refresh.access_token)
return Response({"access": access_token}, status=status.HTTP_200_OK)
except Exception as err:
return Response({"error": "Could not generate access token", "details": str(err)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
return Response({"error": "Could not generate access token", "details": str(err)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
3 changes: 2 additions & 1 deletion Backend/user_service/user_service/user_app/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from django.contrib.auth.models import AbstractUser

from django.db import models
# Create your models here.


Expand All @@ -14,4 +14,5 @@ class User(AbstractUser):
Email: The email field is required for the user model.
"""
friends = models.ManyToManyField("self", null=True, symmetrical=True)
REQUIRED_FIELDS = ["email"]
25 changes: 14 additions & 11 deletions Backend/user_service/user_service/user_app/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,27 @@
class UserSerializer(serializers.ModelSerializer):
"""
UserSerializer class to define the user serializer.
This class defines the user serializer to serialize the user data.
Attributes:
email: The email field.
Meta: The meta class to define the model and fields for the serializer.
Methods:
create: Method to create a new user.
update: Method to update a user.
"""
email = serializers.EmailField(
validators=[UniqueValidator(queryset=User.objects.all())]
)
friends = serializers.PrimaryKeyRelatedField(
many=True, queryset=User.objects.all(), required=False # required=False means that the field is not required
)

class Meta:
model = User
fields = ["id", "username", "email", "password"]
fields = ["id", "username", "email", "password", "friends"]
extra_kwargs = {"password": {"write_only": True}}

### Password should be strong password, minimum 8 characters, at least one uppercase letter, one lowercase letter, one number and one special character
Expand All @@ -37,10 +40,10 @@ def create(self, validate_data) -> User:
Method to create a new user.
This method creates a new user with the given data.
The password is validated using CustomPasswordValidator.
The password is validated using CustomPasswordValidator.
The password is hashed before saving the user object.
Args:
validate_data: The data to validate.
validate_data: The data to validate.
Returns:
User: The user object.
Expand All @@ -59,20 +62,20 @@ def create(self, validate_data) -> User:
def update(self, instance, validate_data) -> User:
"""
Method to update a user.
This method updates a user with the given data.
The password is hashed before saving the user object.
Args:
instance: The user object.
validate_data: The data to validate.
Returns:
User: The updated user object.
Raises:
serializers.ValidationError: If the password is the same as the current password.
"""
for attr, value in validate_data.items():
if attr == "password" and value is not None:
Expand Down
16 changes: 10 additions & 6 deletions Backend/user_service/user_service/user_app/views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import json

import jwt
from django.conf import settings
from django.contrib.auth import authenticate
from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
Expand All @@ -9,7 +10,7 @@
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework_simplejwt.authentication import JWTAuthentication

from rest_framework import status
from .models import User
from .rabbitmq_utils import consume_message, publish_message
from .serializers import UserSerializer
Expand Down Expand Up @@ -59,7 +60,7 @@ def users_list(self, request) -> Response:
return Response(serializer.data)
except Exception as err:
return Response({"error": str(err)}, status=status.HTTP_400_BAD_REQUEST)


def retrieve_user(self, request, pk=None) -> Response:
"""
Expand Down Expand Up @@ -98,12 +99,15 @@ def update_user(self, request, pk=None) -> Response:
try:
self.send_data_to_user_service(request)
data = get_object_or_404(User, id=pk)
if data != request.user and not request.user.is_superuser:
return Response(status=status.HTTP_401_UNAUTHORIZED)
# if data != request.user and not request.user.is_superuser:
# return Response(status=status.HTTP_401_UNAUTHORIZED)
serializer = UserSerializer(instance=data, data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
# if User updated Username should send message to all microservices to update the username related to this user using Kafka
serializer.save()
# if User updated Username should send message to all microservices to update the username related to this user using Kafka
friends_data = request.data.get("friends")
if friends_data is not None:
data.friends.set(friends_data)
return Response(serializer.data, status=status.HTTP_202_ACCEPTED)
except Exception as err:
return Response({"error": str(err)}, status=status.HTTP_400_BAD_REQUEST)
Expand Down
11 changes: 5 additions & 6 deletions Game_server/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ ENV LANG=C.UTF-8

USER root
# Update and install dependencies
RUN apk update && apk add --no-cache \
python3=3.12.3-r1 \
py3-pip=24.0-r2 \
postgresql16=16.3-r0 \
postgresql16-client=16.3-r0 \
bash=5.2.26-r0 && \
# trunk-ignore(hadolint/DL3018)
RUN apk update && apk add --no-cache python3 py3-pip \
postgresql16 postgresql16-client \
bash supervisor curl openssl bash \
build-base libffi-dev python3-dev nano && \
mkdir /run/postgresql && \
chown -R postgres:postgres /run/postgresql
WORKDIR /app/
Expand Down

0 comments on commit a3004bb

Please sign in to comment.