def test_delCell(self): map = self._getSecurityMap() self.assertEqual(getInteraction().invalidated, 0) map._byrow[0] = {} map._bycol[1] = {} map._byrow[0][1] = 'aa' map._bycol[1][0] = 'aa' map.delCell(0, 1) self.assertEqual(getInteraction().invalidated, 1) self.assertEqual(map._byrow.get(0), None) self.assertEqual(map._bycol.get(1), None)
def test_person_logged_in_restores_participation(self): # Once outside of the person_logged_in context, the original # participation (e.g., request) is used. This can be important for # yuixhr test fixtures, in particular. a = self.factory.makePerson() login_as(a) participation = getInteraction().participations[0] b = self.factory.makePerson() with person_logged_in(b): self.assertLoggedIn(b) self.assertIs(participation, getInteraction().participations[0])
def test_usable_as_contextmanager(self): from zope.security.management import getInteraction from zope.security.management import queryInteraction with testing.interaction('foo'): ix = getInteraction() participation = ix.participations[0] self.assertEqual('foo', participation.principal.id) # Nesting doesn't change anything with testing.interaction('baz'): ix = getInteraction() participation = ix.participations[0] self.assertEqual('foo', participation.principal.id) self.assertFalse(queryInteraction())
def change_data_items(self): """Get change data items, reverse-sorted by date (most recent first). """ interaction = getInteraction() # slight performance optimization changes = [] def append_visible_changes_on_item(item): for c in domain.get_changes(item, *self.include_change_actions): if interaction.checkPermission("zope.View", c): changes.append(c) # !+ align checkPermission zope.View with listings of sub item types... # changes direct on head item if "head" in self.include_change_types: append_visible_changes_on_item(self.head) # changes on sub-items -- only Parliamentary Content may have sub-items if interfaces.IBungeniParliamentaryContent.providedBy(self.head): hwf = IWorkflow(self.head) # changes on item signatories if "signatory" in self.include_change_types: signatories = [ s for s in self.head.item_signatories if interaction.checkPermission("zope.View", s) ] for s in signatories: append_visible_changes_on_item(s) # changes on item attachments if ("attachment" in self.include_change_types and hwf.has_feature("attachment") #!+IFeatureAttachment? ): attachments = [ f for f in self.head.attachments if interaction.checkPermission("zope.View", f) ] for f in attachments: append_visible_changes_on_item(f) # changes on item events if ("event" in self.include_change_types # and workflow.has_feature("event"): #!+IEventable? # at least no recursion, on events on events... and not interfaces.IEvent.providedBy(self.head)): events = [ e for e in self.head.sa_events if interaction.checkPermission("zope.View", e) ] for e in events: append_visible_changes_on_item(e) # sort aggregated changes by date_active changes = [ dc[1] for dc in reversed(sorted([(c.date_active, c) for c in changes])) ] return changes '''
def get_principal(): """ () -> either(zope.security.interfaces.IGroupAwarePrincipal, None) """ interaction = getInteraction() for participation in interaction.participations: if IRequest.providedBy(participation): return participation.principal
def serialize(self, element, settings, url): if self.export_name: el_result = xml_el(element, self.tag, settings, name=self.context.__name__, href=url) else: el_result = xml_el(element, self.tag, settings, href=url) def priority_key(n): return (self.sort_priority.get(n, 1000), n) try: interaction = getInteraction() except NoInteraction: # XXX when running in unit tests interaction = DummyInteraction() names = sorted(self.context.keys(), key=priority_key) for name in names: obj = self.context[name] if not interaction.checkPermission('imagestore.Read', obj): continue IXml(obj).serialize(el_result, settings, url=xml_href(url, name)) return el_result
def test_controler(): principal = Principal('someone') with Interaction(principal) as inter: policy = getInteraction() assert inter is policy assert len(policy.participations) == 1 assert policy.participations[0].principal == principal
def get_request_principal(): """ () -> either(zope.security.interfaces.IGroupAwarePrincipal, None) """ interaction = getInteraction() for participation in interaction.participations: if IRequest.providedBy(participation): return participation.principal
def get_principal(): """ () -> either(IPrincipal, None) """ interaction = getInteraction() for participation in interaction.participations: if IRequest.providedBy(participation): return participation.principal
def test_controler(): principal = unauthenticated_principal with Interaction(principal) as inter: policy = getInteraction() assert inter is policy assert len(policy.participations) == 1 assert policy.participations[0].principal == principal
def __call__(self, context): terms = [] configlet = getUtility(IAvatarConfiglet) request = None for part in getInteraction().participations: if part is not None: request = part break if context is not None: profile = context if profile.avatarImage: terms.append(SimpleTerm(0, '0', '0')) elif request is not None: profile = profile = IPersonalProfile(request.principal) if profile.avatarImage: terms.append(SimpleTerm(0, '0', '0')) if configlet.enabled: ids = getUtility(IIntIds) for name, avatar in configlet.items(): id = ids.queryId(avatar) terms.append(SimpleTerm(id, str(id), str(id))) return Vocabulary(terms)
def fireTransition(self, transition_id, comment=None, side_effect=None, check_security=True): state = self.state() wf = self.workflow() # this raises InvalidTransitionError if id is invalid for current state transition = wf.getTransition(state.getState(), transition_id) # check whether we may execute this workflow transition try: interaction = getInteraction() except NoInteraction: checkPermission = nullCheckPermission else: if check_security: checkPermission = interaction.checkPermission else: checkPermission = nullCheckPermission if not checkPermission( transition.permission, self.context): raise Unauthorized(self.context, 'transition: %s' % transition_id, transition.permission) # now make sure transition can still work in this context if not transition.condition(self, self.context): raise ConditionFailedError # perform action, return any result as new version result = transition.action(self, self.context) if result is not None: if transition.source is None: self.state(result).initialize() # stamp it with version state = self.state( result ) state.setId( self.state().getId() ) # execute any side effect: if side_effect is not None: side_effect(result) event = WorkflowVersionTransitionEvent(result, self.context, transition.source, transition.destination, transition, comment) else: if transition.source is None: self.state().initialize() # execute any side effect if side_effect is not None: side_effect(self.context) event = WorkflowTransitionEvent(self.context, transition.source, transition.destination, transition, comment) # change state of context or new object state.setState(transition.destination) notify(event) # send modified event for original or new object if result is None: notify(ObjectModifiedEvent(self.context)) else: notify(ObjectModifiedEvent(result)) return result
def file_data_items(self): if self._data_items is None: interaction = getInteraction() # slight performance optimization self._data_items = [ f for f in removeSecurityProxy(self.context).attachments if interaction.checkPermission("zope.View", f) ] return self._data_items
def __init__(self, context, request, view, manager): self.context = context.attached_files self.request = request self.__parent__ = context self.manager = manager self.query = None self.for_display = len(self.context) > 0 self.interaction = getInteraction()
def file_data_items(self): if self._data_items is None: interaction = getInteraction() # slight performance optimization self._data_items = [ f for f in removeSecurityProxy(self.context).attachments if interaction.checkPermission("bungeni.attachment.View", f) ] return self._data_items
def getRequest(): i = getInteraction() # raises NoInteraction for p in i.participations: if IRequest.providedBy(p): return p raise RuntimeError('Could not find current request.')
def test_addCell(self): map = self._getSecurityMap() self.assertEqual(getInteraction().invalidated, 0) map.addCell(0, 0, 'aa') self.assertEqual(getInteraction().invalidated, 1) self.assertEqual(map._byrow[0][0], 'aa') self.assertEqual(map._bycol[0][0], 'aa') map.addCell(1, 0, 'ba') self.assertEqual(getInteraction().invalidated, 2) self.assertEqual(map._byrow[1][0], 'ba') self.assertEqual(map._bycol[0][1], 'ba') map.addCell(5, 3, 'fd') self.assertEqual(getInteraction().invalidated, 3) self.assertEqual(map._byrow[5][3], 'fd') self.assertEqual(map._bycol[3][5], 'fd')
def fireTransition(self, transition_id, comment=None, side_effect=None, check_security=True): state = self.state(self.context) transition = self.wf.getTransition(state.getState(), transition_id) if check_security and transition.permission is not CheckerPublic: # check whether we may execute this workflow transition try: interaction = getInteraction() except NoInteraction: checkPermission = nullCheckPermission else: checkPermission = interaction.checkPermission if not checkPermission(transition.permission, self.context): raise Unauthorized(self.context, 'transition: {}'.format(transition_id), transition.permission) # now make sure transition can still work in this context if not transition.condition(self, self.context): raise ConditionFailedError() # perform action, return any result as new version result = transition.action(self, self.context) if result is not None: if transition.source is None: self.state(result).initialize() # stamp it with version state = self.state(result) state.setId(self.state(self.context).getId()) # execute any side effect: if side_effect is not None: side_effect(result) event = WorkflowVersionTransitionEvent(result, self.context, transition.source, transition.destination, transition, comment) else: if transition.source is None: self.state(self.context).initialize() # execute any side effect if side_effect is not None: side_effect(self.context) event = WorkflowTransitionEvent(self.context, transition.source, transition.destination, transition, comment) # change state of context or new object state.setState(transition.destination) notify(event) # send modified event for original or new object if result is None: notify(ObjectModifiedEvent(self.context)) else: notify(ObjectModifiedEvent(result)) return result
def test_nested_interaction(): anon = unauthenticated_principal john = Principal('John') anke = Principal('Anke') paul = Principal('Paul') with Interaction(anon): policy = getInteraction() assert list(users(policy.participations)) == [anon] with Interaction(john, replace=False): policy = getInteraction() assert list(users(policy.participations)) == [anon, john] with Interaction(anke, replace=False): policy = getInteraction() assert list(users(policy.participations)) == [anon, john, anke] with Interaction(paul): policy = getInteraction() assert list(users(policy.participations)) == [paul] policy = getInteraction() assert list(users(policy.participations)) == [anon, john, anke] policy = getInteraction() assert list(users(policy.participations)) == [anon, john] policy = getInteraction() assert list(users(policy.participations)) == [anon]
def getRequest(self): """ this trick will return the request from the working interaction see http://wiki.zope.org/zope3/FAQProgramming#how-do-i-get-irequest-object-in-event-handler """ i = getInteraction() # raises NoInteraction for i_request in i.participations: if IRequest.providedBy(i_request): return i_request raise RuntimeError('Could not find current request.')
def getRequest(): try: interaction = getInteraction() request = interaction.participations[0] except NoInteraction: request = None except IndexError: request = None return request
def getManualTransitionIds(self): try: checkPermission = getInteraction().checkPermission except NoInteraction: checkPermission = nullCheckPermission return [transition.transition_id for transition in sorted(self._getTransitions(MANUAL)) if transition.condition(self, self.context) and checkPermission(transition.permission, self.context)]
def precache_permission_for_objects(participation, permission_name, objects): """Precaches the permission for the objects into the policy cache.""" if participation is None: participation = getInteraction().participations[0] permission_cache = participation.annotations.setdefault( LAUNCHPAD_SECURITY_POLICY_CACHE_KEY, weakref.WeakKeyDictionary()) for obj in objects: naked_obj = removeSecurityProxy(obj) obj_permission_cache = permission_cache.setdefault(naked_obj, {}) obj_permission_cache[permission_name] = True
def clear_cache(): """clear current interaction's IApplicationRequests' authorization caches. """ for p in getInteraction().participations: if IApplicationRequest.providedBy(p): # LaunchpadBrowserRequest provides a ``clearSecurityPolicyCache`` # method, but it is not in an interface, and not implemented by # all classes that implement IApplicationRequest. if LAUNCHPAD_SECURITY_POLICY_CACHE_KEY in p.annotations: del p.annotations[LAUNCHPAD_SECURITY_POLICY_CACHE_KEY]
def get_request(self): try: i = getInteraction() # raises NoInteraction except NoInteraction: raise Exception("No request error.") for p in i.participations: if IRequest.providedBy(p): return p raise Exception("No request error.")
def test_create_interaction_should_return_principal(self): from zope.security.management import getInteraction from zope.security.testing import create_interaction principal = create_interaction( 'foo', groups=['bar'], description='desc') ix = getInteraction() participation = ix.participations[0] self.assertEqual('foo', participation.principal.id) self.assertEqual(principal.groups, participation.principal.groups) self.assertEqual('desc', participation.principal.description)
def change_data_items(self): """Get change data items, reverse-sorted by date (most recent first). """ interaction = getInteraction() changes = [] def append_visible_changes_on_item(item): permission = view_permission(item) for c in domain.get_changes(item, *self.include_change_actions): if checkPermission(permission, c): changes.append(c) # changes direct on head item if "head" in self.include_change_types: append_visible_changes_on_item(self.head) # changes on sub-items -- only Parliamentary Content may have sub-items if interfaces.IBungeniParliamentaryContent.providedBy(self.head): hwf = IWorkflow(self.head) # changes on item signatories if "signatory" in self.include_change_types: signatories = [ s for s in self.head.item_signatories if interaction.checkPermission("bungeni.signatory.View", s) ] for s in signatories: append_visible_changes_on_item(s) # changes on item attachments if ("attachment" in self.include_change_types and hwf.has_feature("attachment") #!+IFeatureAttachment? ): attachments = [ f for f in self.head.attachments if interaction.checkPermission("bungeni.attachment.View", f) ] for f in attachments: append_visible_changes_on_item(f) # changes on item events if ("event" in self.include_change_types # and workflow.has_feature("event"): #!+IEventable? # at least no recursion, on events on events... and not interfaces.IEvent.providedBy(self.head) ): events = [ e for e in self.head.sa_events if interaction.checkPermission("bungeni.event.View", e) ] for e in events: append_visible_changes_on_item(e) # sort aggregated changes by date_active changes = [ dc[1] for dc in reversed(sorted([ (c.date_active, c) for c in changes ])) ] return changes '''
def test_create_interaction_should_return_principal(self): from zope.security.management import getInteraction from zope.security.testing import create_interaction principal = create_interaction('foo', groups=['bar'], description='desc') ix = getInteraction() participation = ix.participations[0] self.assertEqual('foo', participation.principal.id) self.assertEqual(principal.groups, participation.principal.groups) self.assertEqual('desc', participation.principal.description)
def get_request(): """ () -> either(IRequest, None) Raises zope.security.interfaces.NoInteraction if no interaction (and no request). """ # use queryInteraction() to raise interaction = getInteraction() for participation in interaction.participations: if IRequest.providedBy(participation): return participation
def version_data_items(self): # version log is only concerned with own versions (not of any child # objects) i.e. only own "version changes"; as "data_provider" we # simply use the versions attribute on context: if self._data_items is None: interaction = getInteraction() # sorted desc by sqlalchemy, so following sorting not necessary: self._data_items = [ removeSecurityProxy(v) for v in self.context.versions if interaction.checkPermission("zope.View", v) ] return self._data_items
def precache_permission_for_objects(participation, permission_name, objects): """Precaches the permission for the objects into the policy cache.""" if participation is None: participation = getInteraction().participations[0] permission_cache = participation.annotations.setdefault( LAUNCHPAD_SECURITY_POLICY_CACHE_KEY, weakref.WeakKeyDictionary() ) for obj in objects: naked_obj = removeSecurityProxy(obj) obj_permission_cache = permission_cache.setdefault(naked_obj, {}) obj_permission_cache[permission_name] = True
def getManualTransitionIds(self, check_security=True): try: checkPermission = getInteraction().checkPermission except NoInteraction: checkPermission = nullCheckPermission if not check_security: checkPermission = nullCheckPermission return [transition.transition_id for transition in sorted(self._getTransitions(MANUAL)) if transition.condition(self, self.context) and checkPermission(transition.permission, self.context)]
def __init__(self, context, request, view, manager): self.context = [] trusted = removeSecurityProxy(context) for f in trusted.attached_files: if f.type.attached_file_type_name != "system": self.context.append(f) self.request = request self.__parent__ = context self.manager = manager self.query = None self.for_display = len(self.context) > 0 self.interaction = getInteraction()
def check(*args, **kwargs): component = lookup(*args, **kwargs) if component is not None: if canAccess(component, '__call__'): return removeSecurityProxy(component) else: interaction = getInteraction() principal = interaction.participations[0].principal if principal is unauthenticated_principal: raise exceptions.HTTPUnauthorized(component) else: raise exceptions.HTTPForbidden(component) return None
def data(self): # TODO: what if we have multiple participations? principal = getInteraction().participations[0].principal ann = zope.component.getMultiAdapter((principal, self), IAnnotations) # If no preferences exist, create the root preferences object. if ann.get(pref_key) is None: ann[pref_key] = OOBTree() prefs = ann[pref_key] # If no entry for the group exists, create a new entry. if self.__id__ not in prefs.keys(): prefs[self.__id__] = OOBTree() return prefs[self.__id__]
def test_addCell_no_invalidation(self): class NoInvalidation(object): attrs = () def __getattr__(self, name): self.attrs += (name,) return object.__getattr__(self, name) setSecurityPolicy(NoInvalidation) endInteraction() newInteraction() map = self._getSecurityMap() map.addCell(0, 0, 'aa') self.assertIn('invalidate_cache', getInteraction().attrs)
def change_data_items(self): """Get change data items, reverse-sorted by date (most recent first). """ interaction = getInteraction() head_wf = IWorkflow(self.head) changes = [] def append_visible_changes_on_item(item): permission = view_permission(item) for c in domain.get_changes(item, *self.param_audit_actions): if checkPermission(permission, c): changes.append(c) def include_feature_changes(feature_name, SUPPORTED_FEATURE): # !+ interfaces.IFeatureX.providedBy(self.head) return ( (not SUPPORTED_FEATURE or head_wf.has_feature(feature_name)) and feature_name in self.param_include_subtypes) def append_visible_changes_on_sub_items(sub_type_key, items_attr, SUPPORTED_FEATURE=True # !+ ): if include_feature_changes(sub_type_key, SUPPORTED_FEATURE): pid = "bungeni.%s.View" % (sub_type_key) items = [ item for item in getattr(self.head, items_attr) if interaction.checkPermission(pid, item) ] for item in items: append_visible_changes_on_item(item) # changes direct on head item append_visible_changes_on_item(self.head) # changes on sub-items append_visible_changes_on_sub_items("signatory", "sa_signatories") append_visible_changes_on_sub_items("attachment", "attachments") append_visible_changes_on_sub_items("event", "sa_events") if interfaces.IDoc.providedBy(self.head): append_visible_changes_on_sub_items("group_assignment", "sa_group_assignments") elif interfaces.IGroup.providedBy(self.head): append_visible_changes_on_sub_items("group_assignment", "sa_group_assignments", SUPPORTED_FEATURE=False) # !+ "group_assignment" is not a "group" feature append_visible_changes_on_sub_items("member", "group_members", SUPPORTED_FEATURE=False) # !+ "member" is not a "group" feature) # sort aggregated changes by date_active changes = [ dc[1] for dc in reversed(sorted([ (c.date_active, c) for c in changes ])) ] return changes '''
def data(self): utility = zapi.getUtility(IPrincipalAnnotationUtility, context=self) # TODO: what if we have multiple participations? principal = getInteraction().participations[0].principal ann = utility.getAnnotations(principal) # If no preferences exist, create the root preferences object. if ann.get(pref_key) is None: ann[pref_key] = OOBTree() prefs = ann[pref_key] # If no entry for the group exists, create a new entry. if self.__id__ not in prefs.keys(): prefs[self.__id__] = OOBTree() return prefs[self.__id__]
def classifySubscriber(item, event): """ A subscriber for an object event that fires a quotationtool.classify workflow process for this item.""" pd = zope.component.getUtility(IProcessDefinition, name='quotationtool.classify') context = ClassificationContext(item) process = pd(context) contributor = u"unkown" for principal in getInteraction().participations: if IPrincipal.providedBy(principal): contributor = principal.id elif IRequest.providedBy(principal): contributor = principal.principal.id break history = IWorkflowHistory(item) process.start(contributor, datetime.datetime.now(), _(u"Newly created items need to be classified."), history, PersistentAttribution())
def __setitem__(self, key, value): """ See zope.interface.common.mapping.IWriteMapping This is restriced depending on the value of the 'complete' and 'open_to_users' attribute. >>> from quotationtool.categorization.categoryset import CategorySet >>> from quotationtool.categorization.category import Category >>> from quotationtool.categorization import testing >>> from zope.security.management import newInteraction >>> interaction = newInteraction() >>> descriptions = testing.generateCategorizableItemDescriptions(root) >>> container = testing.generateCategoriesContainer(root) >>> catset = container['catset'] = CategorySet() >>> catset['cat1'] = Category() >>> catset.complete = True >>> catset['cat2'] = Category() Traceback (most recent call last): ... UserError: categoryset-setitem-error-complete >>> catset.complete = False >>> catset.open_to_users = False >>> catset['cat2'] = Category() """ if self.complete: raise UserError( _( 'categoryset-setitem-error-complete', u"The set of category labels is 'complete'. New category labels cannot be added. Sorry." )) if not self.open_to_users: interaction = getInteraction() if not interaction.checkPermission( 'quotationtool.categorization.EditCategory', self): raise UserError( _( 'categoryset-setitem-error-notopentousers', u"This set of category labels is not 'open to users'. You don't have the permission to add a new category label. Sorry." )) super(CategorySet, self).__setitem__(key, value)
def __init__(self, context, request, view, manager): self.context = [] trusted = removeSecurityProxy(context) # !+(murithi, mar-2010 )Attached file versions implement IVersion # but have no attached files - an adapter on all content # might make sense to fetch attachments. # here we conditionaly skip attachment versions if not IAttachedFileVersion.providedBy(trusted): for f in trusted.attached_files: if IAttachedFileVersion.providedBy(f): self.context.append(f) else: if f.type.attached_file_type_name != "system": self.context.append(f) self.request = request self.__parent__ = context self.manager = manager self.query = None self.for_display = len(self.context) > 0 self.interaction = getInteraction() self.formatter = ui_utils.date.getLocaleFormatter( self.request, "date", "long")
def decoratedSetUp(self): self.policy = RecordedSecurityPolicy self._oldpolicy = setSecurityPolicy(self.policy) newInteraction() self.interaction = getInteraction() self.obj = object()
def __enter__(self): newInteraction(self.principal) return getInteraction()
def change_data_items(self): """Get change data items, reverse-sorted by date (most recent first). """ interaction = getInteraction() # slight performance optimization changes = [] def append_visible_changes_on_item(item): for c in domain.get_changes(item, *self.include_change_actions): if interaction.checkPermission("zope.View", c): changes.append(c) # !+ align checkPermission zope.View with listings of sub item types... # changes direct on head item if "head" in self.include_change_types: append_visible_changes_on_item(self.head) # changes on sub-items -- only Parliamentary Content may have sub-items if interfaces.IBungeniParliamentaryContent.providedBy(self.head): # changes on item signatories if "signatory" in self.include_change_types: signatories = [ s for s in self.head.item_signatories if interaction.checkPermission("zope.View", s) ] for s in signatories: append_visible_changes_on_item(s) # changes on item attachments if "attachedfile" in self.include_change_types: attachments = [ f for f in self.head.attached_files if interaction.checkPermission("zope.View", f) ] for f in attachments: append_visible_changes_on_item(f) # changes on item events if "event" in self.include_change_types: events = [ e for e in self.head.events if interaction.checkPermission("zope.View", e) ] if events: # !+AuditLogSubs(mr, dec-2011) events not currently audited, # so we temporarily simulate a singular "add" change action # and stuff it on an event.changes attribute. class EventChange(domain.ItemChanges): def __init__(self, event): self._event = event self.item_id = event.doc_id #change_id #self.content self.head = event.head self.action = "add" self.date_audit = self.date_active = \ event.status_date self.description = event.short_title self.notes = None # self.extras self.user = event.owner self.status = event.status for e in events: e.changes = [EventChange(e)] append_visible_changes_on_item(e) # sort aggregated changes by date_active changes = [ dc[1] for dc in reversed(sorted([ (c.date_active, c) for c in changes ])) ] return changes '''
def checkPermission(self): interaction = getInteraction() return interaction.checkPermission( 'quotationtool.workflow.DoEditorialReview', self.context)
def __init__(self, context, request): grok.Page.__init__(self, context, request) self.principal = getInteraction().participations[0].principal
def principal(self): try: return getInteraction().participations[0].principal except (NoInteraction, IndexError, AttributeError): return component.queryUtility(IUnauthenticatedPrincipal)
def _getCurrentUserId( self ): interaction = getInteraction() for participation in interaction.participations: if IRequest.providedBy(participation): return participation.principal.id return None
def interaction(self): try: return getInteraction() except NoInteraction: return None
def annotations(self): principal = getInteraction().participations[0].principal ann = zope.component.getMultiAdapter((principal, self), IAnnotations) return ann