tabdon
tabdon

Reputation: 157

tastypie - Verify permissions to create object on POST

Using the wonderful django-tastpie.

My app has a concept of a document (i.e. word doc). There is one owner of a document, and many editors. The editors can add comments.

I want to check if an editor has permissions to a document before they can POST a comment. However I can't figure out how to perform this check with tastpie.

Here's my code simplified a bit:

# 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)

If an editor is reviewing a document and submits a Comment I want to verify they are part of the EditorGroup before I allow them to create the Comment.

I've looked into using the obj_create for this but am not sure how to access the Document object to see if the Editor (who is now request.user) is part of the EditorGroup.

Also not sure if obj_create is the right place to perform this check or not.

Any help would be greatly appreciated!

Upvotes: 1

Views: 1266

Answers (2)

thinkingpotato
thinkingpotato

Reputation: 11

If you need to check something on a Document object, then solution below seems ok. You could use build_related_resource method of RelatedField class to get the resource from URI and turn it into a valid Django object. However, if you need to check for groups, permissions and authorization in general, you better have a look at Implementing Your Own Authentication/Authorization in django-tastypie docs.

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:
            [...]

Upvotes: 1

abolotnov
abolotnov

Reputation: 4332

Here is one of the options:

if request.user.groups.filter(id=self.document.editor_group.id).exists():
    ...post_comment
else:
    ...don't post comment

Upvotes: 1

Related Questions