2012-03-31 21 views
1

使用美妙的django-tastpie。tastypie - 驗證在POST上創建對象的權限

我的應用程序有一個文件的概念(即word文檔)。有一個文件的所有者和許多編輯。編輯可以添加評論。

我想檢查編輯是否有權限文檔,然後纔可以發表評論。但我無法弄清楚如何使用tastpie執行此檢查。

這裏是我的代碼簡化了一下:

# models.py 

class Document(models.Model): 
    doc_text = models.TextInput() 
    owner = models.ForeignKey(User) 
    editor_group = models.ForeignKey(EditorGroup) 

class EditorGroup(models.Model): 
    name = models.CharField() 
    user = models.ManyToManyField(User) 

class Comment(models.Model): 
    comment = models.CharField() 
    user = models.ForeignKey() 
    document = models.ForeignKey() 

-

# api.py 

class CommentResource(ModelResource): 
    user = fields.ForeignKey(UserResource, 'user') 

    class Meta: 
     queryset = Comment.objects.all() 
     resource_name = 'comments' 
     authorization= DjangoAuthorization() 

     def obj_create(self, bundle, request, **kwargs): 

      # What code can I put here to check if the Editor is in the 
      # EditorGroup 

      return super(AnswerResource, self).obj_create(bundle, request, user=request.user) 

如果編輯器正在審查的文件和我之前提交評論我要驗證他們是EditorGroup的一部分允許他們創建評論。

我已經研究過使用obj_create,但不確定如何訪問Document對象以查看編輯器(現在是request.user)是否爲EditorGroup的一部分。

也不確定obj_create是否是執行此檢查的正確位置。

任何幫助將不勝感激!

回答

1

這裏是其中的一個選項:

​​
+0

謝謝。我給了一個嘗試,但它不工作,我認爲,因爲Comment對象尚未創建。當我嘗試使用'self.document.editor_group.id'時,我得到一個「error_message」:「int()參數必須是一個字符串或一個數字,而不是'ForeignKey'」 – tabdon 2012-03-31 23:37:16

+0

你好,我愛你看到你在做什麼。檢查你的註釋對象的副本的bundle.data []。就像'document_id = bundle.data ['document']'...從那裏你應該知道該怎麼做。 – abolotnov 2012-04-01 06:31:25

+0

太棒了 - 我可以看到評論對象的副本。現在我需要訪問相關的Document實例,但我擁有的是它的URI。你知道我可以如何將URI轉換爲對象實例嗎?我試圖用get_via_uri函數來做,但一直沒有把它拉下來。 – tabdon 2012-04-01 15:53:20

1

如果您需要檢查一個Document對象上的東西,然後在下面的解決方案似乎確定。您可以使用build_related_resource方法RelatedField類從URI獲取資源並將其轉換爲有效的Django對象。但是,如果您需要檢查羣組,權限和一般授權,則最好在django-tastypie文檔中查看Implementing Your Own Authentication/Authorization

class CommentResource(ModelResource): 

    user = fields.ForeignKey(UserResource, 'user') 
    document = fields.ForeignKey(DocumentResource, 'user') 

    def obj_create(self, bundle, request=None, **kwargs): 
     document_uri = json.loads(request.POST.keys()[0]['document']) 
     document = self.document.build_related_resource(document_uri).obj 
     if request.user.has_permission_to(document) or request.user.is_editor: 
      [...]