Skip to content

Commit

Permalink
Simplify permission handling in views and permissions logic.
Browse files Browse the repository at this point in the history
Refactored `get_permissions` in `cinema/views.py` to streamline behavior and rely more on `super()`. Updated comments in `user/permissions.py` for clarity and removed redundant code, improving maintainability and readability.
  • Loading branch information
frezworx committed Dec 26, 2024
1 parent f297195 commit 10d7c47
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 18 deletions.
9 changes: 3 additions & 6 deletions cinema/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,12 +170,9 @@ class OrderViewSet(
permission_classes = [IsAdminOrIfAuthenticatedReadOnly]

def get_permissions(self):
if self.action in (
"list",
"create"
):
return (IsAdminOrIfAuthenticatedReadOnly(),)
return (IsAuthenticated(),)
if self.action == "create":
return [IsAuthenticated()]
return super().get_permissions()

def get_queryset(self):
return Order.objects.filter(user=self.request.user)
Expand Down
36 changes: 24 additions & 12 deletions user/permissions.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,36 @@
from rest_framework.permissions import SAFE_METHODS, BasePermission


# class IsAdminOrIfAuthenticatedReadOnly(BasePermission):
# def has_permission(self, request, view):
# # If the user is an admin, we allow everything.
# if request.user and request.user.is_staff:
# return True
#
# # If the request is "read" (GET/HEAD/OPTIONS),
# # then we allow authenticated
# if request.method in SAFE_METHODS:
# return bool(request.user and request.user.is_authenticated)
#
# # Allow POST to regular authenticated users
# if (
# request.method == "POST"
# and request.user
# and request.user.is_authenticated
# ):
# return True
#
# # Everything else (POST, PUT, PATCH, DELETE) is prohibited
# return False
class IsAdminOrIfAuthenticatedReadOnly(BasePermission):
def has_permission(self, request, view):
# If the user is an admin, we allow everything.
# Разрешаем всё админам
if request.user and request.user.is_staff:
return True

# If the request is "read" (GET/HEAD/OPTIONS),
# then we allow authenticated
# Разрешаем GET/HEAD/OPTIONS аутентифицированным
if request.method in SAFE_METHODS:
return bool(request.user and request.user.is_authenticated)

# Allow POST to regular authenticated users
if (
request.method == "POST"
and request.user
and request.user.is_authenticated
):
return True

# Everything else (POST, PUT, PATCH, DELETE) is prohibited
# Иначе (POST/PUT/PATCH/DELETE) — запрещаем
return False

0 comments on commit 10d7c47

Please sign in to comment.