Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model resource with users as FK TastyPie API

Using TastyPie I have a model resource which has a FK user. When I make a POST to the API I have to include the user id like this:

 data : JSON.stringify({ name : 'value a', user : '12' }), 

My users have to authenticate either by logging in or using an API Key and username and password. In both cases I already know who the user is.

1) How can I make user sure that user1 does not create a resource for user2?

2) or it is counterintuitive to send the user ID at all? Should I somehow get the user from the authorization details, if so how?

like image 210
GrantU Avatar asked Oct 20 '22 22:10

GrantU


1 Answers

To answer question #1: The Tastypie documentation describes how to create per-user resources. Assuming that the user is already part of the request:

class MyResource(ModelResource):
    class Meta:
        queryset = MyModel.objects.all()
        resource_name = 'environment'
        list_allowed_methods = ['get', 'post']
        authentication = ApiKeyAuthentication()
        authorization = Authorization()

    # Only allow creation of objects belonging to the user
    def obj_create(self, bundle, **kwargs):
        return super(EnvironmentResource, self).obj_create(bundle, user=bundle.request.user)

    # Only allow accessing resources for this user
    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(user=request.user)

To answer question #2, you should probably have the user be part of the session.

like image 71
NT3RP Avatar answered Oct 27 '22 20:10

NT3RP