Created
April 25, 2018 08:47
-
-
Save robinharms/226770283995e447b13d2cf250584b15 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import unittest | |
from pyramid import testing | |
from pyramid.authorization import ACLAuthorizationPolicy | |
from pyramid.security import Allow, DENY_ALL | |
from pyramid.authentication import SessionAuthenticationPolicy | |
from pyramid.testing import DummySession | |
EDIT = 'edit' | |
class Resource(testing.DummyResource): | |
# We'll set {'username': ['Editors']} for this test | |
local_roles = None | |
__acl__ = [ | |
(Allow, 'Editors', [EDIT]), | |
DENY_ALL, | |
] | |
def __init__(self, local_roles={}): | |
testing.DummyResource.__init__(self) | |
self.local_roles = local_roles | |
def groupfinder(name, request): | |
# So how do we find groups from context during a request...? | |
# This is of course the cause of the problem | |
context = getattr(request, 'context', None) | |
result = set() | |
while context: | |
result.update(context.local_roles.get(name, ())) | |
try: | |
context = context.__parent__ | |
except AttributeError: | |
#For instance broken objects or root | |
context = None | |
return result | |
class ContextGroupsTests(unittest.TestCase): | |
def setUp(self): | |
self.config = testing.setUp() | |
authorization_policy = ACLAuthorizationPolicy() | |
self.config.set_authorization_policy(authorization_policy) | |
authentication_policy = SessionAuthenticationPolicy(callback = groupfinder) | |
self.config.set_authentication_policy(authentication_policy) | |
session_fact = DummySession() | |
self.config.set_session_factory(session_fact) | |
def tearDown(self): | |
testing.tearDown() | |
def _fixture(self): | |
root = Resource() | |
root['myspace'] = Resource(local_roles={'me': ['Editors']}) | |
root['myspace']['mystuff'] = Resource() | |
root['secret'] = Resource() | |
root['secret']['very_secret_stuff'] = Resource() | |
request = testing.DummyRequest() | |
# A request at /myspace | |
request.context = root['myspace'] | |
# User called 'me' | |
request.session['auth.userid'] = 'me' | |
self.config.begin(request) | |
return root, request | |
def test_good_permission_check(self): | |
root, request = self._fixture() | |
self.assertTrue(request.has_permission(EDIT, root['myspace'])) | |
def test_perm_outside_of_request_tree(self): | |
root, request = self._fixture() | |
self.assertFalse(request.has_permission(EDIT, root['secret'])) | |
if __name__ == "__main__": | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment