added users management and permissions
This commit is contained in:
+19
-3
@@ -14,6 +14,11 @@ from nomenclatures.models import Nomenclature, NomenclatureEntry
|
||||
from scalesapp.sse import sse_broadcast_update
|
||||
|
||||
|
||||
class IsAdminUser(IsAuthenticated):
|
||||
def has_permission(self, request, view):
|
||||
return bool(request.user and request.user.is_authenticated and request.user.is_admin)
|
||||
|
||||
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
API endpoint for user management.
|
||||
@@ -22,7 +27,7 @@ class UserViewSet(viewsets.ModelViewSet):
|
||||
create: Create a new user
|
||||
retrieve: Get a specific user
|
||||
update: Update a user
|
||||
destroy: Delete a user
|
||||
destroy: Soft-delete a user (sets is_active=False)
|
||||
me: Get current authenticated user
|
||||
change_password: Change password for current user
|
||||
"""
|
||||
@@ -31,13 +36,24 @@ class UserViewSet(viewsets.ModelViewSet):
|
||||
filterset_fields = ['role', 'is_admin', 'is_active']
|
||||
ordering = ['username']
|
||||
|
||||
@action(detail=False, methods=['get'], permission_classes=[IsAuthenticated])
|
||||
def get_permissions(self):
|
||||
if self.action in ('me', 'change_password'):
|
||||
return [IsAuthenticated()]
|
||||
return [IsAuthenticated(), IsAdminUser()]
|
||||
|
||||
def destroy(self, request, *args, **kwargs):
|
||||
instance = self.get_object()
|
||||
instance.is_active = False
|
||||
instance.save()
|
||||
return Response(status=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
@action(detail=False, methods=['get'])
|
||||
def me(self, request):
|
||||
"""Get current authenticated user details"""
|
||||
serializer = UserDetailSerializer(request.user)
|
||||
return Response(serializer.data)
|
||||
|
||||
@action(detail=False, methods=['post'], permission_classes=[IsAuthenticated],
|
||||
@action(detail=False, methods=['post'],
|
||||
url_path='change-password', url_name='change_password')
|
||||
def change_password(self, request):
|
||||
"""Change password for current user"""
|
||||
|
||||
Reference in New Issue
Block a user