|
| 1 | +""" |
| 2 | +Views for the sample_plugin app. |
| 3 | +""" |
| 4 | +import logging |
| 5 | +from django.utils import timezone |
| 6 | +from django_filters.rest_framework import DjangoFilterBackend |
| 7 | +from rest_framework import filters, permissions, viewsets |
| 8 | +from rest_framework.exceptions import PermissionDenied, ValidationError |
| 9 | +from rest_framework.pagination import PageNumberPagination |
| 10 | +from rest_framework.throttling import UserRateThrottle, AnonRateThrottle |
| 11 | + |
| 12 | +from sample_plugin.models import CourseArchiveStatus |
| 13 | +from sample_plugin.serializers import CourseArchiveStatusSerializer |
| 14 | + |
| 15 | + |
| 16 | +logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | + |
| 19 | +class IsOwnerOrStaffSuperuser(permissions.BasePermission): |
| 20 | + """ |
| 21 | + Custom permission to only allow owners of an object or staff/superusers to view or edit it. |
| 22 | + """ |
| 23 | + |
| 24 | + def has_permission(self, request, view): |
| 25 | + """ |
| 26 | + Return True if permission is granted to the view. |
| 27 | + """ |
| 28 | + # Allow authenticated users to list and create |
| 29 | + return request.user and request.user.is_authenticated |
| 30 | + |
| 31 | + def has_object_permission(self, request, view, obj): |
| 32 | + """ |
| 33 | + Return True if permission is granted to the object. |
| 34 | + """ |
| 35 | + # Allow if the object belongs to the requesting user |
| 36 | + if obj.user == request.user: |
| 37 | + return True |
| 38 | + |
| 39 | + # Allow staff users and superusers |
| 40 | + if request.user.is_staff or request.user.is_superuser: |
| 41 | + return True |
| 42 | + |
| 43 | + return False |
| 44 | + |
| 45 | + |
| 46 | +class CourseArchiveStatusPagination(PageNumberPagination): |
| 47 | + """ |
| 48 | + Pagination class for CourseArchiveStatus. |
| 49 | + """ |
| 50 | + page_size = 20 |
| 51 | + page_size_query_param = 'page_size' |
| 52 | + max_page_size = 100 |
| 53 | + |
| 54 | + |
| 55 | +class CourseArchiveStatusThrottle(UserRateThrottle): |
| 56 | + """ |
| 57 | + Throttle for the CourseArchiveStatus API. |
| 58 | + """ |
| 59 | + rate = '60/minute' |
| 60 | + |
| 61 | + |
| 62 | +class CourseArchiveStatusViewSet(viewsets.ModelViewSet): |
| 63 | + """ |
| 64 | + API viewset for CourseArchiveStatus. |
| 65 | +
|
| 66 | + Allows users to view their own course archive statuses and staff/superusers to view all. |
| 67 | + Pagination is applied with a default page size of 20 (max 100). |
| 68 | + Filtering is available on course_id, user, and is_archived fields. |
| 69 | + Ordering is available on all fields. |
| 70 | + """ |
| 71 | + serializer_class = CourseArchiveStatusSerializer |
| 72 | + permission_classes = [IsOwnerOrStaffSuperuser] |
| 73 | + pagination_class = CourseArchiveStatusPagination |
| 74 | + throttle_classes = [CourseArchiveStatusThrottle, AnonRateThrottle] |
| 75 | + filter_backends = [DjangoFilterBackend, filters.OrderingFilter] |
| 76 | + filterset_fields = ['course_id', 'user', 'is_archived'] |
| 77 | + ordering_fields = ['course_id', 'user', 'is_archived', 'archive_date', 'created_at', 'updated_at'] |
| 78 | + ordering = ['-updated_at'] |
| 79 | + |
| 80 | + def get_queryset(self): |
| 81 | + """ |
| 82 | + Return the queryset for this viewset. |
| 83 | +
|
| 84 | + Regular users can only see their own records. |
| 85 | + Staff and superusers can see all records but with optimized queries. |
| 86 | + """ |
| 87 | + user = self.request.user |
| 88 | + |
| 89 | + # Validate query parameters to prevent injection |
| 90 | + self._validate_query_params() |
| 91 | + |
| 92 | + # Always use select_related to avoid N+1 queries |
| 93 | + base_queryset = CourseArchiveStatus.objects.select_related('user') |
| 94 | + |
| 95 | + if user.is_staff or user.is_superuser: |
| 96 | + return base_queryset |
| 97 | + |
| 98 | + # Regular users only see their own records |
| 99 | + return base_queryset.filter(user=user) |
| 100 | + |
| 101 | + def _validate_query_params(self): |
| 102 | + """ |
| 103 | + Validate query parameters to prevent injection. |
| 104 | + """ |
| 105 | + # Example validation for course_id format |
| 106 | + course_id = self.request.query_params.get('course_id') |
| 107 | + if course_id and not self._is_valid_course_id(course_id): |
| 108 | + logger.warning( |
| 109 | + "Invalid course_id in request: %s, user: %s", |
| 110 | + course_id, |
| 111 | + self.request.user.username |
| 112 | + ) |
| 113 | + raise ValidationError({"course_id": "Invalid course ID format."}) |
| 114 | + |
| 115 | + def _is_valid_course_id(self, course_id): |
| 116 | + """ |
| 117 | + Check if the course_id is in a valid format. |
| 118 | +
|
| 119 | + This is a basic implementation - in production, you might use a more |
| 120 | + sophisticated validator from the edx-platform. |
| 121 | + """ |
| 122 | + try: |
| 123 | + from opaque_keys.edx.keys import CourseKey |
| 124 | + CourseKey.from_string(course_id) |
| 125 | + return True |
| 126 | + except: |
| 127 | + return False |
| 128 | + |
| 129 | + def perform_create(self, serializer): |
| 130 | + """ |
| 131 | + Perform creation of a new CourseArchiveStatus. |
| 132 | +
|
| 133 | + Sets the user to the requesting user if not specified. |
| 134 | + Sets archive_date and archived_by if is_archived is True. |
| 135 | + """ |
| 136 | + data = serializer.validated_data.copy() |
| 137 | + |
| 138 | + # Set user to requesting user if not specified |
| 139 | + if 'user' not in data: |
| 140 | + data['user'] = self.request.user |
| 141 | + # Only allow staff/superusers to create records for other users |
| 142 | + elif data['user'] != self.request.user and not (self.request.user.is_staff or self.request.user.is_superuser): |
| 143 | + logger.warning( |
| 144 | + "Permission denied: User %s tried to create a record for user %s", |
| 145 | + self.request.user.username, |
| 146 | + data['user'].username |
| 147 | + ) |
| 148 | + raise PermissionDenied("You do not have permission to create records for other users.") |
| 149 | + |
| 150 | + # Set archive_date if is_archived is True |
| 151 | + if data.get('is_archived', False): |
| 152 | + data['archive_date'] = timezone.now() |
| 153 | + |
| 154 | + # Create the record |
| 155 | + instance = serializer.save(**data) |
| 156 | + |
| 157 | + # Log at debug level for normal operation |
| 158 | + logger.debug( |
| 159 | + "CourseArchiveStatus created: course_id=%s, user=%s, is_archived=%s", |
| 160 | + instance.course_id, |
| 161 | + instance.user.username, |
| 162 | + instance.is_archived |
| 163 | + ) |
| 164 | + |
| 165 | + return instance |
| 166 | + |
| 167 | + def perform_update(self, serializer): |
| 168 | + """ |
| 169 | + Perform update of an existing CourseArchiveStatus. |
| 170 | +
|
| 171 | + Updates archive_date and archived_by if is_archived changes. |
| 172 | + """ |
| 173 | + instance = serializer.instance |
| 174 | + data = serializer.validated_data.copy() |
| 175 | + |
| 176 | + # Handle archive_date if is_archived changes |
| 177 | + if 'is_archived' in data: |
| 178 | + # If changing from not archived to archived |
| 179 | + if data['is_archived'] and not instance.is_archived: |
| 180 | + data['archive_date'] = timezone.now() |
| 181 | + # If changing from archived to not archived |
| 182 | + elif not data['is_archived'] and instance.is_archived: |
| 183 | + data['archive_date'] = None |
| 184 | + |
| 185 | + # Update the record |
| 186 | + updated_instance = serializer.save(**data) |
| 187 | + |
| 188 | + # Log at debug level |
| 189 | + logger.debug( |
| 190 | + "CourseArchiveStatus updated: course_id=%s, user=%s, is_archived=%s", |
| 191 | + updated_instance.course_id, |
| 192 | + updated_instance.user.username, |
| 193 | + updated_instance.is_archived |
| 194 | + ) |
| 195 | + |
| 196 | + return updated_instance |
| 197 | + |
| 198 | + def perform_destroy(self, instance): |
| 199 | + """ |
| 200 | + Perform deletion of an existing CourseArchiveStatus. |
| 201 | + """ |
| 202 | + # Log at debug level before deletion |
| 203 | + logger.debug( |
| 204 | + "CourseArchiveStatus deleted: course_id=%s, user=%s, by=%s", |
| 205 | + instance.course_id, |
| 206 | + instance.user.username, |
| 207 | + self.request.user.username |
| 208 | + ) |
| 209 | + |
| 210 | + # Delete the instance |
| 211 | + return super().perform_destroy(instance) |
0 commit comments