2013-03-18 82 views
4

我正在使用django-tastypie編寫API。我有兩個定製permisions問題,我希望django-guardian可以修復。限制對僅擁有內容的訪問django

我有兩個用戶組臨牀醫師和患者。臨牀醫生應該能夠訪問屬於他們患者的對象,並且患者應該只能夠訪問由他們自己創建的對象。

我的代碼如下:

class UserResource(ModelResource): 
    class Meta: 
     queryset = User.objects.all() 
     resource_name = 'auth/user' 
     excludes = ['email', 'password', 'is_superuser'] 


class BlogPostResource(ModelResource): 
    author = fields.ToOneField(UserResource, 'author', full=True) 

    class Meta: 
     queryset = BlogPost.objects.all() 
     resource_name = 'posts' 
     allowed_methods = ["get", "post"] 
     # Add it here. 
     authentication = BasicAuthentication() 
     authorization = DjangoAuthorization() 
     filtering = { 
      'author': ALL_WITH_RELATIONS, 
     } 

我怎樣才能使用權限來限制對這個BlogPostResource訪問?

class CustomAuthorization(Authorization): 
    def apply_limits(self, request, object_list):  
     ... 
     clin_group = Group.objects.get(name='YOUR GROUP') 
     if request and hasattr(request, 'user'): 
      if clin_group in request.user.groups.all(): 
       object_list = object_list.filter(user__in=request.user.patients.all()) # or however you stop clinician>patient relation 
      else: 
       object_list = object_list.filter(user=request.user) 
     return object_list 

回答

2

我根據我的離開answer的最終解決方案,從@JamesO

+0

長期可擴展性,請參閱http://stackoverflow.com/a/16261711/454615 – airtonix 2013-04-28 10:04:08

4

你可以用自定義Authorization類實現這一點,例如像。他的回答的問題是它是在改寫Authorization類之前寫入老版本的django-tastypie的。這裏是我的代碼供將來參考:

from tastypie.authorization import Authorization 
from django.contrib.auth.models import Group 
from extendedusers.models import ExtendedUser 


class CustomAuthorization(Authorization): 
    def read_list(self, object_list, bundle): 
     clinician_group = Group.objects.get(name='clinician') 
     if bundle.request and hasattr(bundle.request, 'user'): 
      if clinician_group in bundle.request.user.groups.all(): 
       patients = ExtendedUser.objects.filter(clinician_id=bundle.request.user.id) 
       object_list = object_list.filter(author__id__in=patients) 
      else: 
       object_list = object_list.filter(author=bundle.request.user) 
      return object_list 
     else: 
      return object_list.none() 
+0

謝謝,這是我曾考慮的方法。唯一的是(我忘了在我的問題中提到)我們也有一個正常的django web界面,需要完全相同的權限創建的內容,我不想分割訪問策略代碼... – Prydie 2013-03-18 14:09:08

+0

@Prydie - 啊,我明白了。您可以創建經理,在其中設置訪問控制,然後在您的核心應用/管理員和您的tastypie應用中調用經理?將代碼保存在一個地方。 – JamesO 2013-03-18 14:58:39

+0

我很尷尬地說我不知道​​經理是什麼... – Prydie 2013-03-18 15:05:21