0

I want to disable authentication on creation in my UserViewSet, so that even non authenticated user can create an account.

I'm using django-oauth-toolkit to authenticate in my application, and I use their authentication class as default in my settings (which is great)

I have tried to use the @authentication_class decorator (https://stackoverflow.com/a/39717881/5438372), but it doesn't seem to work with ModelViewSet

And I also tried to override the get_authenticator method, in the same spirit as this : Django rest framework permission_classes of ViewSet method, but ViewSet.action doesn't seem to be available at authentication.

How can I do this ? I there something wrong with my approach ?

Here is my code :

<models.py:>
class UserViewSet(viewsets.ModelViewSet):
    serializer_class = UserSerializer
    permission_classes = (IsSelfOrStaffPermission, TokenHasReadWriteScope,)
    lookup_field = 'username'

    def get_queryset(self):
        current_user = self.request.user
        if current_user.is_staff:
            user_set = User.objects.all()
        else:
            user_set = User.objects.filter(username=current_user.username)

        query = self.request.query_params.get('q', None)

        if not query:
            return user_set

        return user_set.filter(
            Q(username__icontains=query) |
            Q(first_name__icontains=query) |
            Q(last_name__icontains=query)
        )

<settings.py:>
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    ),

    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

<permission.py:>
class IsSelfOrStaffPermission(permissions.BasePermission):
    """
    Permission to allow user actions on his own profile
    """
    def has_object_permission(self, request, view, obj):
        return obj == request.user or request.user.is_staff

1 Answer 1

0

You can check if view.action is 'create' or not inside has_permission method:

class IsSelfOrStaffPermission(permissions.BasePermission):
    """
    Permission to allow user actions on his own profile
    """
    def has_permission(self, request, view):
        return view.action == 'create'
Sign up to request clarification or add additional context in comments.

1 Comment

I thought the problem couldn't be fixed at permission level, but your answer gave me the idea. The solution was to override the has_permission method of TokenAsReadWriteScope

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.