Skip to content

Commit

Permalink
Add and update permissions in VolunteerViewSet and OrganizerViewSet
Browse files Browse the repository at this point in the history
  • Loading branch information
1yunker committed Nov 9, 2023
1 parent 24cc1a0 commit de0d069
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 23 deletions.
8 changes: 4 additions & 4 deletions backend/api/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,12 +159,12 @@ def filter_queryset(self, queryset):

if user.is_organizer:
status_filter = self.data.get("draft") and self.filter_draft or \
self.data.get("active") and self.filter_active or \
self.data.get("completed") and self.filter_completed or \
self.data.get("archive") and self.filter_archive
self.data.get("active") and self.filter_active or \
self.data.get("completed") and self.filter_completed or \
self.data.get("archive") and self.filter_archive
elif user.is_volunteer:
status_filter = self.data.get("active") and self.filter_active or \
self.data.get("completed") and self.filter_completed
self.data.get("completed") and self.filter_completed

if status_filter:
queryset = status_filter(queryset)
Expand Down
51 changes: 39 additions & 12 deletions backend/api/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,19 @@


class IsAdmin(BasePermission):
"""Разрешает доступ только пользователям с ролью администратора."""
"""
Разрешает доступ только пользователям с ролью администратора.
"""

def has_permission(self, request, view):
return request.user.is_authenticated and request.user.is_admin


class IsOrganizerOrReadOnly(BasePermission):
"""Разрешает доступ для безопасных методов всем,
а для остальных только пользователям с ролью организатор."""
"""
Разрешает доступ для безопасных методов всем, а для
остальных только пользователям с ролью организатор.
"""

def has_permission(self, request, view):
return request.method in SAFE_METHODS or (
Expand All @@ -22,7 +26,9 @@ def has_permission(self, request, view):


class IsOrganizer(BasePermission):
"""Разрешает доступ только пользователям с ролью организатор."""
"""
Разрешает доступ только пользователям с ролью организатор.
"""

def has_permission(self, request, view):
return bool(
Expand All @@ -42,13 +48,10 @@ def has_object_permission(self, request, view, obj):


class IsVolunteer(BasePermission):
"""Разрешает доступ только пользователям с ролью волонтер."""
"""
Разрешает доступ только пользователям с ролью волонтер.
"""

# def has_permission(self, request, view):
# return (
# request.user.is_authenticated
# and request.user.role == User.VOLUNTEER
# )
def has_permission(self, request, view):
return bool(
request.user
Expand All @@ -72,9 +75,33 @@ def has_object_permission(self, request, view, obj):


class IsOwnerOrReadOnlyPermission(BasePermission):
"""Разрешает доступ только создателю объекта для изменения/удаления."""
"""
Разрешает доступ только создателю объекта для изменения/удаления.
"""

def has_object_permission(self, request, view, obj):
if request.method in ['GET', 'HEAD', 'OPTIONS']:
if request.method in SAFE_METHODS:
return True
return obj.volunteer == request.user


class IsOwnerVolunteer(BasePermission):
"""
Разрешает доступ волонтеру для изменения/удаления только своего профиля.
"""

def has_object_permission(self, request, view, obj):
if request.method in SAFE_METHODS:
return True
return obj.user == request.user


class IsOwnerOrganization(BasePermission):
"""
Разрешает доступ организатору для изменения/удаления только своего профиля.
"""

def has_object_permission(self, request, view, obj):
if request.method in SAFE_METHODS:
return True
return obj.contact_person == request.user
2 changes: 1 addition & 1 deletion backend/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -594,7 +594,7 @@ class Meta:

class CurrentUserSerializer(UserSerializer):
"""
Сериализатор текущего пользователя. используется по адресу auth/me.
Сериализатор текущего пользователя, используется по адресу auth/me.
"""

id_organizer_or_volunteer = serializers.SerializerMethodField()
Expand Down
4 changes: 2 additions & 2 deletions backend/api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,12 @@
name='password_reset_confirm',
),
path(
r'auth/activation/',
'auth/activation/',
UserViewSet.as_view({'post': 'activation'}),
name='activation',
),
path(
r'auth/resend_activation/',
'auth/resend_activation/',
UserViewSet.as_view({'post': 'resend_activation'}),
name='resend_activation',
),
Expand Down
25 changes: 21 additions & 4 deletions backend/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,12 @@
IsOrganizer,
IsOrganizerOfProject,
IsOrganizerOrReadOnly,
IsOwnerOrganization,
IsOwnerVolunteer,
IsVolunteer,
IsVolunteerOfIncomes,
)
from .serializers import ( # VolunteerProfileSerializer,
from .serializers import (
CitySerializer,
FeedbackSerializer,
NewsSerializer,
Expand Down Expand Up @@ -134,7 +136,6 @@ class ProjectViewSet(viewsets.ModelViewSet):
"""

queryset = Project.objects.all()
# serializer_class = ProjectSerializer
filter_backends = [DjangoFilterBackend]
filterset_class = ProjectFilter
permission_classes = [IsOrganizerOrReadOnly]
Expand Down Expand Up @@ -239,7 +240,7 @@ class VolunteerViewSet(DestroyUserMixin, viewsets.ModelViewSet):
Позволяет получать, создавать, редактировать, удалять участника-волонтера.
"""

permission_classes = (AllowAny,)
# permission_classes = (AllowAny,)
queryset = Volunteer.objects.all()

def get_serializer_class(self):
Expand All @@ -249,6 +250,14 @@ def get_serializer_class(self):
return VolunteerUpdateSerializer
return VolunteerCreateSerializer

def get_permissions(self):
if self.request.method in ('PUT', 'PATCH', 'DELETE'):
self.permission_classes = (IsOwnerVolunteer,)
else:
self.permission_classes = (AllowAny,)

return super(VolunteerViewSet, self).get_permissions()


class OrganizationViewSet(DestroyUserMixin, viewsets.ModelViewSet):
"""
Expand All @@ -258,7 +267,7 @@ class OrganizationViewSet(DestroyUserMixin, viewsets.ModelViewSet):
удалять организацию-организатора проекта.
"""

permission_classes = (AllowAny,)
# permission_classes = (AllowAny,)
queryset = Organization.objects.all()

def get_serializer_class(self):
Expand All @@ -268,6 +277,14 @@ def get_serializer_class(self):
return OgranizationUpdateSerializer
return OgranizationCreateSerializer

def get_permissions(self):
if self.request.method in ('PUT', 'PATCH', 'DELETE'):
self.permission_classes = (IsOwnerOrganization,)
else:
self.permission_classes = (AllowAny,)

return super(OrganizationViewSet, self).get_permissions()


class CityViewSet(viewsets.ReadOnlyModelViewSet):
"""
Expand Down

0 comments on commit de0d069

Please sign in to comment.