Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solution #665

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions cinema/permissions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from rest_framework.permissions import BasePermission, SAFE_METHODS


class IsAdminOrIfAuthenticatedReadOnly(BasePermission):
"""
Permission allows administrators full access (read and write),
while regular authenticated users have read-only access.
"""

def has_permission(self, request, view):
if request.method in SAFE_METHODS:
return bool(request.user and request.user.is_authenticated)
return bool(request.user and request.user.is_staff)
72 changes: 53 additions & 19 deletions cinema/views.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
from datetime import datetime

from django.utils import timezone
from django.db.models import F, Count
from rest_framework import viewsets
from rest_framework import mixins, viewsets
from rest_framework.pagination import PageNumberPagination

from cinema.models import Genre, Actor, CinemaHall, Movie, MovieSession, Order

from rest_framework.permissions import IsAuthenticated, IsAdminUser

from cinema.models import (
Genre,
Actor,
CinemaHall,
Movie,
MovieSession,
Order
)
from cinema.serializers import (
GenreSerializer,
ActorSerializer,
Expand All @@ -21,24 +28,52 @@
)


class GenreViewSet(viewsets.ModelViewSet):
class GenreViewSet(mixins.ListModelMixin,
mixins.CreateModelMixin,
viewsets.GenericViewSet):
queryset = Genre.objects.all()
serializer_class = GenreSerializer

def get_permissions(self):
if self.action == "create":
return [IsAdminUser()]
return [IsAuthenticated()]
Comment on lines +38 to +40

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The get_permissions method in GenreViewSet restricts the create action to admins only. According to the task requirements, both list and create actions should be accessible to all users, not just admins. Consider removing the permission restriction for the create action.



class ActorViewSet(viewsets.ModelViewSet):
class ActorViewSet(mixins.ListModelMixin,
mixins.CreateModelMixin,
viewsets.GenericViewSet):
queryset = Actor.objects.all()
serializer_class = ActorSerializer

def get_permissions(self):
if self.action == "create":
return [IsAdminUser()]
return [IsAuthenticated()]
Comment on lines +50 to +52

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The get_permissions method in ActorViewSet restricts the create action to admins only. As per the task requirements, both list and create actions should be accessible to all users. Consider adjusting the permissions to allow all users to create.


class CinemaHallViewSet(viewsets.ModelViewSet):

class CinemaHallViewSet(mixins.ListModelMixin,
mixins.CreateModelMixin,
viewsets.GenericViewSet):
queryset = CinemaHall.objects.all()
serializer_class = CinemaHallSerializer

def get_permissions(self):
if self.action == "create":
return [IsAdminUser()]
return [IsAuthenticated()]
Comment on lines +62 to +64

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The get_permissions method in CinemaHallViewSet restricts the create action to admins only. The task specifies that both list and create actions should be available to all users. Please modify the permissions to meet this requirement.



class MovieViewSet(viewsets.ModelViewSet):
queryset = Movie.objects.prefetch_related("genres", "actors")
serializer_class = MovieSerializer
permission_classes = [IsAuthenticated]
http_method_names = ["get", "post", "patch"]

def get_permissions(self):
if self.action in ["create", "update", "partial_update", "destroy"]:
return [IsAdminUser()]
return [IsAuthenticated()]

@staticmethod
def _params_to_ints(qs):
Expand Down Expand Up @@ -69,10 +104,8 @@ def get_queryset(self):
def get_serializer_class(self):
if self.action == "list":
return MovieListSerializer

if self.action == "retrieve":
return MovieDetailSerializer

return MovieSerializer


Expand All @@ -88,28 +121,27 @@ class MovieSessionViewSet(viewsets.ModelViewSet):
)
serializer_class = MovieSessionSerializer

def get_permissions(self):
if self.action in ["create", "update", "partial_update", "destroy"]:
return [IsAdminUser()]
return [IsAuthenticated()]

def get_queryset(self):
date = self.request.query_params.get("date")
movie_id_str = self.request.query_params.get("movie")

queryset = self.queryset

if date:
date = datetime.strptime(date, "%Y-%m-%d").date()
date = timezone.make_aware(datetime.strptime(date, "%Y-%m-%d"))
queryset = queryset.filter(show_time__date=date)

if movie_id_str:
queryset = queryset.filter(movie_id=int(movie_id_str))

return queryset

def get_serializer_class(self):
if self.action == "list":
return MovieSessionListSerializer

if self.action == "retrieve":
return MovieSessionDetailSerializer

return MovieSessionSerializer


Expand All @@ -118,20 +150,22 @@ class OrderPagination(PageNumberPagination):
max_page_size = 100


class OrderViewSet(viewsets.ModelViewSet):
class OrderViewSet(mixins.ListModelMixin,
mixins.CreateModelMixin,
viewsets.GenericViewSet):
queryset = Order.objects.prefetch_related(
"tickets__movie_session__movie", "tickets__movie_session__cinema_hall"
)
serializer_class = OrderSerializer
pagination_class = OrderPagination
permission_classes = [IsAuthenticated]

def get_queryset(self):
return Order.objects.filter(user=self.request.user)

def get_serializer_class(self):
if self.action == "list":
return OrderListSerializer

return OrderSerializer

def perform_create(self, serializer):
Expand Down
12 changes: 11 additions & 1 deletion cinema_service/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"debug_toolbar",
"cinema",
"user",
"django_extensions",
]

MIDDLEWARE = [
Expand Down Expand Up @@ -125,7 +126,7 @@

USE_I18N = True

USE_TZ = False
USE_TZ = True


# Static files (CSS, JavaScript, Images)
Expand All @@ -137,3 +138,12 @@
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES": [
"cinema.permissions.IsAdminOrIfAuthenticatedReadOnly",
],
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.TokenAuthentication",
]
}
1 change: 1 addition & 0 deletions cinema_service/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@
path("admin/", admin.site.urls),
path("api/cinema/", include("cinema.urls", namespace="cinema")),

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure that the cinema.urls module defines a namespace 'cinema' since you are using namespace="cinema" in the include function.

path("__debug__/", include("debug_toolbar.urls")),
path("api/user/", include("user.urls", namespace="user")),

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure that the user.urls module defines a namespace 'user' since you are using namespace="user" in the include function.

]
29 changes: 28 additions & 1 deletion user/serializers.py
Original file line number Diff line number Diff line change
@@ -1 +1,28 @@
# write your code here
from django.contrib.auth import get_user_model
from rest_framework import serializers


class UserSerializer(serializers.ModelSerializer):

class Meta:
model = get_user_model()
fields = ("id", "username", "email", "password", "is_staff")
read_only_fields = ("id", "is_staff")
extra_kwargs = {
"password": {"write_only": True, "min_length": 5}
}

def create(self, validated_data):
"""create user with encrypted password"""
return get_user_model().objects.create_user(**validated_data)

def update(self, instance, validated_data):
"""update user with encrypted password"""
password = validated_data.pop("password", None)
user = super().update(instance, validated_data)

if password:
user.set_password(password)
user.save()

return user
18 changes: 17 additions & 1 deletion user/urls.py
Original file line number Diff line number Diff line change
@@ -1 +1,17 @@
# write your code here
from django.urls import path

from user.views import (
CreateUserView,
LoginUserView,
ManageUserView
)

from rest_framework.authtoken import views

urlpatterns = [
path("register/", CreateUserView.as_view(), name="create"),
path("login/", LoginUserView.as_view(), name="login"),
path("me/", ManageUserView.as_view(), name="manage"),
]

app_name = "user"
24 changes: 23 additions & 1 deletion user/views.py
Original file line number Diff line number Diff line change
@@ -1 +1,23 @@
# write your code here
from rest_framework import generics
from rest_framework.authentication import TokenAuthentication
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.permissions import IsAuthenticated
from rest_framework.settings import api_settings
from user.serializers import UserSerializer


class CreateUserView(generics.CreateAPIView):
serializer_class = UserSerializer


class LoginUserView(ObtainAuthToken):
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES


class ManageUserView(generics.RetrieveUpdateAPIView):
serializer_class = UserSerializer
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)

def get_object(self):
return self.request.user
Loading