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