Skip to content
This repository has been archived by the owner on Sep 28, 2022. It is now read-only.

Commit

Permalink
Merge pull request #31 from postatum/93349732_self_route
Browse files Browse the repository at this point in the history
Implement ACL mixin to convert `self` to model id field value
  • Loading branch information
jstoiko committed May 11, 2015
2 parents 1ed8afa + 4805c76 commit f8e14c9
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
25 changes: 24 additions & 1 deletion nefertari/acl.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,29 @@
from pyramid.security import ALL_PERMISSIONS, Allow, Everyone, Authenticated


class BaseACL(object):
class SelfParamMixin(object):
""" ACL mixin that implements method to translate input key value
to a user ID field, when key value equals to :param_value:
Value is only converted if user is logged in and :request.user:
is an instance of :__context_class__:, thus for routes that display
auth users.
"""
param_value = 'self'

def convert_self_key(self, key):
if key != self.param_value:
return key
user = getattr(self.request, 'user', None)
if not user or not self.__context_class__:
return key
if not isinstance(user, self.__context_class__):
return key
obj_id = getattr(user, user.id_field()) or key
return obj_id


class BaseACL(SelfParamMixin):
""" Base ACL class.
Grants:
Expand All @@ -28,6 +50,7 @@ def context_acl(self, obj):

def __getitem__(self, key):
assert(self.__context_class__)
key = self.convert_self_key(key)

id_field = self.__context_class__.id_field()
obj = self.__context_class__.get(
Expand Down
34 changes: 34 additions & 0 deletions tests/test_acl.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,37 @@ def test_authenticatedreadacl_context_acl(self):
(Allow, 'g:admin', ALL_PERMISSIONS),
(Allow, Authenticated, 'show'),
]


class TestSelfParamMixin(object):

def test_convert_self_key_wrong_key(self):
obj = acl.SelfParamMixin()
assert obj.param_value == 'self'
assert obj.convert_self_key('') == ''
assert obj.convert_self_key('foo') == 'foo'

def test_convert_self_key_user_not_logged_in(self):
obj = acl.SelfParamMixin()
obj.request = Mock(user=None)
assert obj.convert_self_key('self') == 'self'

def test_convert_self_key_no_model_Cls(self):
obj = acl.SelfParamMixin()
obj.__context_class__ = None
obj.request = Mock(user=1)
assert obj.convert_self_key('self') == 'self'

def test_convert_self_key_user_wrong_class(self):
obj = acl.SelfParamMixin()
obj.__context_class__ = dict
obj.request = Mock(user='a')
assert obj.convert_self_key('self') == 'self'

def test_convert_self_key(self):
obj = acl.SelfParamMixin()
obj.__context_class__ = Mock
user = Mock(username='user12')
user.id_field.return_value = 'username'
obj.request = Mock(user=user)
assert obj.convert_self_key('self') == 'user12'

0 comments on commit f8e14c9

Please sign in to comment.