Skip to content

Commit

Permalink
Merge pull request #1859 from d34d-5h07/dev
Browse files Browse the repository at this point in the history
refactor(dynamic):optimised dynamic_management_serializer , added 403 forbidden custom response
  • Loading branch information
Aashish Vinu authored Dec 27, 2023
2 parents 4c7ea2b + d3a024f commit 3ed682c
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 32 deletions.
31 changes: 18 additions & 13 deletions api/dashboard/dynamic_management/dynamic_management_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def validate_role(self, value):
return value

def validate_type(self, value):
if value not in [type for type in ManagementType.get_all_values()]:
if value not in list(ManagementType.get_all_values()):
raise serializers.ValidationError("Enter a valid type")
return value

Expand All @@ -51,8 +51,10 @@ class DynamicRoleListSerializer(serializers.ModelSerializer):

def get_roles(self, obj):
dynamic_roles = DynamicRole.objects.filter(type=obj['type']).values_list('id', 'role__title')
dynamic_roles_list = [{'id': dynamic_role[0], 'role': dynamic_role[1]} for dynamic_role in dynamic_roles]
return dynamic_roles_list
return [
{'id': dynamic_role[0], 'role': dynamic_role[1]}
for dynamic_role in dynamic_roles
]

class Meta:
model = DynamicRole
Expand All @@ -74,7 +76,7 @@ def update(self, instance, validated_data):
raise serializers.ValidationError("Dynamic Role already exists")
instance.updated_by_id = self.context.get('user_id')
instance.updated_at = DateTimeUtils.get_current_utc_time()
instance.role_id = new_role if new_role else instance.role_id
instance.role_id = new_role or instance.role_id
instance.save()
return instance

Expand Down Expand Up @@ -120,7 +122,7 @@ def validate_user(self, value):
return user

def validate_type(self, value):
if value not in [type for type in ManagementType.get_all_values()]:
if value not in list(ManagementType.get_all_values()):
raise serializers.ValidationError("Enter a valid type")
return value

Expand All @@ -130,13 +132,16 @@ class DynamicUserListSerializer(serializers.ModelSerializer):

def get_users(self, obj):
dynamic_users = DynamicUser.objects.filter(type=obj['type'])
user_data = [{
'dynamic_user_id': dynamic_user.id,
'user_id': dynamic_user.user.id,
'name': dynamic_user.user.full_name,
'muid': dynamic_user.user.muid,
'email': dynamic_user.user.email} for dynamic_user in dynamic_users]
return user_data
return [
{
'dynamic_user_id': dynamic_user.id,
'user_id': dynamic_user.user.id,
'name': f"{dynamic_user.user.first_name} {dynamic_user.user.last_name if dynamic_user.user.last_name else ''}",
'muid': dynamic_user.user.muid,
'email': dynamic_user.user.email,
}
for dynamic_user in dynamic_users
]

class Meta:
model = DynamicUser
Expand All @@ -158,7 +163,7 @@ def update(self, instance, validated_data):
raise serializers.ValidationError("Dynamic User already exists")
instance.updated_by_id = self.context.get('user_id')
instance.updated_at = DateTimeUtils.get_current_utc_time()
instance.user = new_user if new_user else instance.user
instance.user = new_user or instance.user
instance.save()
return instance

Expand Down
7 changes: 4 additions & 3 deletions utils/permission.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ def wrapped_view_func(obj, request, *args, **kwargs):

return decorator


def dynamic_role_required(type):
def decorator(view_func):
def wrapped_view_func(obj, request, *args, **kwargs):
Expand All @@ -194,11 +195,11 @@ def wrapped_view_func(obj, request, *args, **kwargs):
if user in dynamic_users:
response = view_func(obj, request, *args, **kwargs)
return response
res = CustomResponse(
general_message="You do not have the required role to access this page."
).get_failure_response()
res = CustomResponse().get_unauthorized_response()
return res

return wrapped_view_func

return decorator

# class RoleRequired:
Expand Down
52 changes: 36 additions & 16 deletions utils/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from django.core.files.storage import FileSystemStorage
from django.http import HttpResponse


class CustomResponse:
"""A custom response class for API views.
Expand All @@ -15,10 +16,10 @@ class CustomResponse:
"""

def __init__(
self,
message: Dict[str, Any] = None,
general_message: List[str] = None,
response: Dict[str, Any] = None,
self,
message: Dict[str, Any] = None,
general_message: List[str] = None,
response: Dict[str, Any] = None,
) -> None:
"""Initializes the CustomResponse object.
Expand Down Expand Up @@ -56,9 +57,9 @@ def get_success_response(self) -> Response:
)

def get_failure_response(
self,
status_code: int = 400,
http_status_code: int = status.HTTP_400_BAD_REQUEST,
self,
status_code: int = 400,
http_status_code: int = status.HTTP_400_BAD_REQUEST,
) -> Response:
"""Returns a failure response.
Expand All @@ -81,6 +82,23 @@ def get_failure_response(
status=http_status_code,
)

def get_unauthorized_response(
self
) -> Response:
"""
Returns:
Response: A failure response object.
"""
return Response(
data={
"hasError": True,
"statusCode": 403,
"message": self.message,
"response": self.response,
},
status=status.HTTP_403_FORBIDDEN,
)

def paginated_response(self, data: dict, pagination: dict) -> Response:
"""
Generates a paginated response.
Expand All @@ -107,16 +125,18 @@ def paginated_response(self, data: dict, pagination: dict) -> Response:


class ImageResponse:
def __init__(self,path:str):
def __init__(self, path: str):
fs = FileSystemStorage()
if fs.exists(path):self.file = fs.open(path)
else: self.file = None

if fs.exists(path):
self.file = fs.open(path)
else:
self.file = None

def exists(self) -> bool:
return False if self.file is None else True

def get_success_response(self) -> Response:
return HttpResponse(self.file,status=status.HTTP_200_OK,content_type='image/png')
def get_failure_response(self,http_status_code : int = status.HTTP_400_BAD_REQUEST) -> Response:
return HttpResponse(self.file,status=http_status_code,content_type='image/png')
return HttpResponse(self.file, status=status.HTTP_200_OK, content_type='image/png')

def get_failure_response(self, http_status_code: int = status.HTTP_400_BAD_REQUEST) -> Response:
return HttpResponse(self.file, status=http_status_code, content_type='image/png')

0 comments on commit 3ed682c

Please sign in to comment.