Skip to content

Commit 577672f

Browse files
Add staff check endpoint, improve category serializer, and use slug for product creation
Added /users/staff-check/ endpoint to check if the authenticated user is staff. Updated CategorySerializer to include id, name, and slug fields. Ensured product creation uses category slug (recommended) for consistency and usability. Cleaned up and improved API usability for category and staff-related features.
1 parent aa30ec1 commit 577672f

File tree

4 files changed

+24
-127
lines changed

4 files changed

+24
-127
lines changed

account/views.py

Lines changed: 18 additions & 121 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,13 @@
11
from logging import getLogger
22

3-
from django.shortcuts import render
4-
from django.views import View
53
from djoser.views import UserViewSet as BaseUserViewSet
64
from drf_spectacular.utils import OpenApiResponse, extend_schema
75
from rest_framework import status
86
from rest_framework.decorators import action
97
from rest_framework.response import Response
10-
from rest_framework_simplejwt.tokens import RefreshToken
11-
from rest_framework_simplejwt.views import (
12-
TokenObtainPairView as BaseTokenObtainPairView,
13-
TokenRefreshView as BaseTokenRefreshView,
14-
TokenVerifyView as BaseTokenVerifyView, TokenBlacklistView,
15-
)
168

179
from .models import Profile
18-
from .serializers import UserProfileSerializer, RefreshTokenSerializer
10+
from .serializers import UserProfileSerializer
1911

2012
logger = getLogger(__name__)
2113

@@ -226,123 +218,28 @@ def reset_password_confirm(self, request, *args, **kwargs):
226218
logger.error(f"Error during password reset confirmation: {e}", exc_info=True)
227219
raise
228220

229-
230-
class TokenObtainPairView(BaseTokenObtainPairView):
231-
"""
232-
Handle POST requests to obtain a new pair of access and refresh tokens.
233-
"""
234-
235221
@extend_schema(
236-
operation_id="token_obtain",
237-
description="Obtain a new pair of access and refresh tokens.",
238-
tags=["User Authentication"],
239-
responses={
240-
200: OpenApiResponse(description="Token successfully obtained."),
241-
400: OpenApiResponse(description="Invalid credentials."),
242-
}
243-
)
244-
def post(self, request, *args, **kwargs):
245-
try:
246-
response = super().post(request, *args, **kwargs)
247-
return Response({
248-
"message": "Token successfully obtained",
249-
"data": response.data
250-
}, status=response.status_code)
251-
except Exception as e:
252-
logger.error(f"Error during token obtain: {e}", exc_info=True)
253-
raise
254-
255-
256-
class TokenRefreshView(BaseTokenRefreshView):
257-
"""
258-
Handle POST requests to refresh an access token using a refresh token.
259-
"""
260-
261-
@extend_schema(
262-
operation_id="token_refresh",
263-
description="Refresh an access token using a refresh token.",
264-
tags=["User Authentication"],
265-
responses={
266-
200: OpenApiResponse(description="Access token successfully refreshed."),
267-
400: OpenApiResponse(description="Invalid refresh token."),
268-
}
269-
)
270-
def post(self, request, *args, **kwargs):
271-
try:
272-
response = super().post(request, *args, **kwargs)
273-
return Response({
274-
"message": "Access token successfully refreshed",
275-
"data": response.data
276-
}, status=response.status_code)
277-
except Exception as e:
278-
logger.error(f"Error during token refresh: {e}", exc_info=True)
279-
raise
280-
281-
282-
class TokenVerifyView(BaseTokenVerifyView):
283-
"""
284-
Verify if an access token is valid.
285-
"""
286-
287-
@extend_schema(
288-
operation_id="token_verify",
289-
description="Verify if an access token is valid.",
290-
tags=["User Authentication"],
222+
operation_id="user_staff_check",
223+
description="Check if the authenticated user has staff privileges.",
224+
tags=["User Management"],
291225
responses={
292-
200: OpenApiResponse(description="Token is valid."),
293-
401: OpenApiResponse(description="Token is invalid or expired."),
226+
200: OpenApiResponse(description="Staff status retrieved successfully."),
227+
401: OpenApiResponse(description="Authentication required."),
294228
}
295229
)
296-
def post(self, request, *args, **kwargs):
230+
@action(detail=False, methods=['get'])
231+
def staff_check(self, request):
232+
"""
233+
Check if the authenticated user is a staff member.
234+
"""
297235
try:
298-
response = super().post(request, *args, **kwargs)
236+
is_staff = request.user.is_staff
299237
return Response({
300-
"message": "Token is valid",
301-
"data": response.data
302-
}, status=response.status_code)
238+
"is_staff": is_staff,
239+
"message": f"User {'is' if is_staff else 'is not'} a staff member"
240+
}, status=status.HTTP_200_OK)
303241
except Exception as e:
304-
logger.error(f"Error during token verification: {e}", exc_info=True)
305-
raise
306-
307-
308-
class TokenDestroyView(TokenBlacklistView):
309-
"""
310-
Log out the user by blacklisting their refresh token.
311-
"""
312-
serializer_class = RefreshTokenSerializer
313-
314-
@extend_schema(
315-
operation_id="logout_user",
316-
description="Log out the user by blacklisting their refresh token.",
317-
tags=["User Authentication"],
318-
request=RefreshTokenSerializer,
319-
responses={
320-
205: OpenApiResponse(description="Successfully logged out"),
321-
400: OpenApiResponse(description="Invalid Token"),
322-
},
323-
)
324-
def post(self, request, *args, **kwargs):
325-
serializer = self.get_serializer(data=request.data)
326-
try:
327-
serializer.is_valid(raise_exception=True)
328-
refresh_token = serializer.validated_data["refresh"]
329-
token = RefreshToken(refresh_token)
330-
token.blacklist()
242+
logger.error("Error checking staff status: %s", e, exc_info=True)
331243
return Response({
332-
"message": "Successfully logged out"
333-
}, status=status.HTTP_205_RESET_CONTENT)
334-
except Exception as e:
335-
logger.error(f"Error during logout: {e}", exc_info=True)
336-
raise
337-
338-
339-
class ActivateView(View):
340-
def get(self, request, uid, token):
341-
return render(
342-
request,
343-
'account/activate.html',
344-
{
345-
'uid': uid,
346-
'token': token,
347-
}
348-
)
244+
"error": "Unable to check staff status"
245+
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

shop/filters.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ class Meta:
2020
'description': ['icontains'],
2121
'price': ['exact', 'lt', 'gt', 'range'],
2222
'stock': ['exact', 'lt', 'gt'],
23+
'category__slug': ['exact'],
2324
'category__name': ['exact', 'icontains'],
2425
'tags__name': ['exact', 'icontains'],
2526
}

shop/serializers.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@ class Meta:
1717

1818

1919
class ProductSerializer(serializers.ModelSerializer):
20-
# Use PrimaryKeyRelatedField for input and CategorySerializer for output
21-
category = serializers.PrimaryKeyRelatedField(
20+
# Use SlugRelatedField for input to accept category slug and CategorySerializer for output
21+
category = serializers.SlugRelatedField(
22+
slug_field='slug',
2223
queryset=Category.objects.all(),
2324
write_only=True
2425
)

shop/views.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -290,13 +290,11 @@ def list(self, request, *args, **kwargs):
290290
logger.info("Listing products for user id: %s", request.user.id)
291291
queryset = self.get_queryset()
292292
tag_slug = request.query_params.get(r'tag')
293-
category_slug = request.query_params.get(r'category')
293+
# Removed manual category filtering - now handled by ProductFilter
294294
if tag_slug:
295295
tag = get_object_or_404(Tag, slug=tag_slug)
296296
queryset = queryset.filter(tags__in=[tag])
297-
if category_slug:
298-
category = get_object_or_404(Category, slug=category_slug)
299-
queryset = queryset.filter(category=category)
297+
300298
recommender = Recommender()
301299
cart = Cart(request)
302300
recommendation_base = [item[r'product'] for item in cart]

0 commit comments

Comments
 (0)