Ycon Ycon - 1 month ago 9
Python Question

Filter API request according header auth token

I would like to filter the objects according to the token header which gets sent with the GET requests.

My request is sending the token in the header (

get curl -H "Authorization: Token 3f3f3fzzz" https://1.com/api
)

The code below returns no results (just an empty array- no error). I am unable to determine where my request object headers are.

My guess is that I need some middleware function to mutate the response and put the user object in it too.

views.py

class AllViewSet(viewsets.ModelViewSet):
queryset = Movie.objects.order_by('-created',)
serializer_class = AllSerializer
def get_queryset(self):
Movie.objects.filter(owner = self.request.user)


I tried some debugging after the def_queryset (using
import pdb; pdb.set_trace()
).

def(sel.request)
returns: http://dpaste.com/2VQARE3

Here are other parts of my code which may be relevant.

models.py

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)

class Movie(models.Model):
title = models.CharField("Title", max_length=10000, blank=True)
tag = models.ManyToManyField('Tag', blank=True)
created = models.DateTimeField("Created", auto_now_add=True)
owner = models.ForeignKey('auth.User', blank=True, null=True)


setting.py

REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}

MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)

Answer

You can write custom filter backend http://www.django-rest-framework.org/api-guide/filtering/#custom-generic-filtering

from rest_framework import filters
class OwnerFilterBackend(filters.BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        return queryset.filter(owner=request.user)

class AllViewSet(viewsets.ModelViewSet):
    filter_backends = (OwnerFilterBackend,)
    ...