tmuzzin
tmuzzin

Reputation: 101

Tasypie access user object in get_object_list

I am trying to filter based on the currently logged in user. I am using ApiKeyAuthentication and from what I understand in order to do this I need to use get_object_list. The problem I am having is that I can't seem to find any way to access the currently logged in user within get_object_list. The request object is empty when I try to call request.user and I can't seem to find an answer to solve my issue.

class DepartmentResource(JSONResource):

class Meta:
    resource_name = 'departments'
    list_allowed_methods = ['get', 'put', 'post', 'delete']
    detail_allowed_methods = ['get', 'put', 'post', 'delete']

    authentication = ApiKeyAuthentication()
    authorization = DjangoAuthorization()

def get_object_list(self, request):
    permissions = department_permissions()
    foo = []
    foo.append(ApiObject(permissions.get_departments_linked_to_user(bundle.request.user)))
    return foo

def obj_get_list(self, request=None, **kwargs):
    return self.get_object_list(request)

Upvotes: 0

Views: 1099

Answers (1)

tmuzzin
tmuzzin

Reputation: 101

After much research I found that I was going about this the wrong way. Tastypie has a function called authorized_read_list and this solves my issue and seems to be the ideal way to solve this type of problem. Since I am trying to filter based on the currently logged in user, this allows you to filter the query based on the current user. I hope this will save someone else a bunch of time. Here is my updated code:

class FooBarResource(ModelResource):
    class Meta:
        queryset = Foo.objects.all()
        resource_name = 'foobar'
        list_allowed_methods = ['get', 'put', 'post', 'delete']
        authentication = ApiKeyAuthentication()
        authorization = Authorization()

    def authorized_read_list(self, object_list, bundle):
        permissions = department_permissions()
        return object_list.filter(userid=bundle.request.user.id)

Upvotes: 1

Related Questions