1

I am following the Flask-potion tutorial and trying to secure my api. I am stuck on trying to figure out how to set permissions on the User endpoint so that a User cannot look at another User's record. Here is my code:

class UserResource(PrincipalResource):
    class Meta:
        model = User
        permissions = {
            'read': 'id'
        }

class ArticleResource(PrincipalResource):
    class Schema:
        author = fields.ToOne('user')

class Meta:
    model = Article
    read_only_fields = ['author']
    permissions = {
        'create': 'editor',
        'update': ['user:author', 'admin']
    }

Would i need a custom permission to do this? It seems like this would be a common scenario.

lyschoening
  • 18,170
  • 11
  • 44
  • 54
tauren.kristich
  • 449
  • 1
  • 6
  • 22

1 Answers1

2

All "needs" in Flask-Principals are tuples. Your permission configuration for the UserResource, {'read': 'id'} as you have written it, matches a RoleNeed ('role', 'id'). You want to match something like ('id', user_id). Unfortunately that is not currently supported.

However what you can match is an ItemNeed, e.g. ('read', user_id, 'user'). To match that ItemNeed, set your permissions configuration to {'read': 'read'}, then when loading your identity, just add the item permission like this:

identity.provides.add(ItemNeed('read', current_user.id, 'user'))
lyschoening
  • 18,170
  • 11
  • 44
  • 54
  • I got a bit confused with this - Is there a reason the first property of ItemNeed has to be named "read" in this instance? That's what tripped me up. Also For some reason when I implement something like this and go to a resource that I dont have access to, I get a 404? Is that correct? – DaBeeeenster Jun 14 '16 at 10:57
  • @DaBeeeenster Flask-Principals item-needs are a triple of `(method, value, model)`. The ItemNeed you refer to allows read access to the user model. There is a pending PR for simplifying this: From the next release or so `'user:$id'` will resolve to a UserNeed. – lyschoening Jun 14 '16 at 11:50
  • @DaBeeeenster 404 is the correct response. If you returned 400 it would allow people to spy on ids of resources they don't have access to. – lyschoening Jun 14 '16 at 11:51
  • Perfect thanks for clearing it up. Great project! Look forward to the next version... – DaBeeeenster Jun 14 '16 at 15:05