简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM