def test_master_user(self): principal = Principal('0101010001') self.assertTrue(IPrincipal.providedBy(principal)) masteruser = IMasterUser(principal) self.assertTrue(masteruser is principal) self.assertTrue(IPrincipal.providedBy(masteruser)) self.assertEqual(masteruser.id, "0101010001")
def getPreferredLanguages(self): # If the default locale negotiater can get a value, # that means we had a parameter or one of the cookies # (because of the subscriber that gets us here). negotiated = default_locale_negotiator(self.request) if negotiated: return [negotiated] # Here is where we would check for something during traversal, # but we don't actually support that at this time because it # relies on implementation details # Is there a non-default user preference? Right now we know # what a default is due to implementation details above. We also # know for sure that we *have* a remote use, otherwise we wouldn't # be here remote_user = IPrincipal(self.request, None) remote_user_langs = IUserPreferredLanguages(remote_user) if remote_user_langs is not EnglishUserPreferredLanguagesImpl: return remote_user_langs.getPreferredLanguages() # pylint:disable=too-many-function-args # Ok, see what the HTTP request can come up with. Note that we're # going to the Zope interface so that we don't get into an infinite # loop browser_request = IBrowserRequest(self.request) browser_langs = IModifiableUserPreferredLanguages(browser_request) return browser_langs.getPreferredLanguages() # pylint:disable=too-many-function-args
def test_co_user(self): principal = Principal('0101010001-01') self.assertTrue(IPrincipal.providedBy(principal)) co_user = IMasterUser(principal) self.assertFalse(co_user is principal) self.assertEqual(co_user.id, "0101010001")
def adjust_request_interface_for_preferred_languages(event): """ Checks the conditions outlined in this package's documentation and adds a marker interface (:class:`.IPreferredLanguagesRequest`) to the request if they hold true. This is registered as a subscriber for Pyramid's :class:`.IContextFound` event by this package's ``configure.zcml`` """ request = event.request # Does pyramid's default negotiator, which uses explicit settings # like a request param or cookie have an answer? If so, we need # our custom policy...these override the Accept-Language header if default_locale_negotiator(request): interface.alsoProvides(request, IPreferredLanguagesRequest) return # What about the zope/plone cookie? if request.cookies.get('I18N_LANGUAGE'): # For benefit of the default localization machinery # in case it's used, copy request._LOCALE_ = request.cookies.get('I18N_LANGUAGE') interface.alsoProvides(request, IPreferredLanguagesRequest) return # Ok, is there an authenticated user with preferred languages? # (We leave detecting defaults up to the actual policy) remote_user = IPrincipal(request, None) if remote_user and not IUnauthenticatedPrincipal.providedBy(remote_user): remote_user_langs = IUserPreferredLanguages(remote_user) if remote_user_langs and remote_user_langs.getPreferredLanguages(): # pylint:disable=too-many-function-args interface.alsoProvides(request, IPreferredLanguagesRequest)
def fset(self, new_owner): if not (new_owner is None or IPrincipal.providedBy(new_owner)): raise ValueError('IPrincipal object or None required') if new_owner is None: new_owner_id = None else: new_owner_id = new_owner.id current_owner_id = self._getCurrentOwnerId() if new_owner_id == current_owner_id: return if current_owner_id is not None: self._rolemanager.unsetRoleForPrincipal( OWNER_ROLE, current_owner_id) current_owner = getUtility(IAuthentication).getPrincipal( current_owner_id) else: current_owner = None if new_owner_id: self._rolemanager.assignRoleToPrincipal( OWNER_ROLE, new_owner_id) notify(OwnerChangedEvent(self.context, new_owner, current_owner))
def canAssignPrincipal(self, principal): if (not IUnauthenticatedPrincipal.providedBy(principal) and IPrincipal.providedBy(principal) and not IGroup.providedBy(principal) and checkPermissionForPrincipal(principal,'zojax.PersonalSpace',self)): return True return False
def new_interaction(principal): if not IPrincipal.providedBy(principal): auth = getUtility(IAuthentication, context=None) principal = auth.getPrincipal(principal) interaction = OmsSecurityPolicy() interaction.add(SessionStub(principal)) return interaction
def test_principal_from_iteraction(self): principal = _Principal('bob') participation = _Participation(principal) newInteraction(participation) try: interaction = queryInteraction() p_from_i = IPrincipal(interaction) assert_that(p_from_i.username, is_(principal.username)) finally: endInteraction()
def owner(self, owner): if IPrincipal.providedBy(owner): oldOwner = self.owner self._ownerId = owner.id self.isGroup = IGroup.providedBy(owner) self.annotations[ANNOTATION_KEY] = {'ownerId': self._ownerId, 'isGroup': self.isGroup} event.notify(OwnerChangedEvent(self.context, owner, oldOwner)) else: raise ValueError('IPrincipal object is required.')
def test_principal(self): pr = principal.Principal("0101010001") self.assertTrue(isinstance(pr, principal.Principal)) self.assertTrue(IPrincipal.providedBy(pr)) class F: def __init__(self, pr): self.object = pr with testing.AuthenticatedRequest("0101010001"): self.layer.create_application("app") applyPermissionsForExistentCoUsers(F(pr)) self.assertEqual(str(pr.homefolder), "<Homefolder for 0101010001>") self.assertEqual(pr.homefolder_url, "http://127.0.0.1/app/members/0101010001") self.assertEqual(pr.getRoles(), ['ENMS'])
def remove_subscriptions_for_principal(principal, event): """ Subscriber to find and remove all subscriptions for the *principal* when it is removed. This is an adapter for ``(IPrincipal, IObjectRemovedEvent)`` by default, but that may not be the correct event in every system. Register it for the appropriate events in your system. :param principal: The principal being removed. It should still be located (having a proper ``__parent__``) when this subscriber is invoked; this is the default for ``zope.container`` objects that use :func:`zope.container.contained.uncontained` in their ``__delitem__`` method. This can be any type of object. It is first adapted to :class:`nti.webhooks.interfaces.IWebhookPrincipal`; if that fails, it is adapted to ``IPrincipal``, and if that fails, it is used as-is. The final object must have the ``id`` attribute. :param event: This is not used by this subscriber. This subscriber removes all subscriptions owned by the *principal* found in subscription managers: - in the current site; and - in sites up the lineage of the original principal and adapted object (if different). If the principal may have subscriptions in more places, provide an implementation of :class:`nti.webhooks.interfaces.IWebhookSubscriptionManagers` for the original *principal* object. One (exhaustive) implementation is provided (but not registered) in :class:`ExhaustiveWebhookSubscriptionManagers`. """ orig_principal = principal principal = IWebhookPrincipal(principal, None) or IPrincipal( principal, principal) prin_id = principal.id manager_iters = [_find_subscription_managers(principal)] if principal is not orig_principal: manager_iters.append(_find_subscription_managers(orig_principal)) manager_iters.append(IWebhookSubscriptionManagers(orig_principal, ())) for manager in chain(*manager_iters): manager.deleteSubscriptionsForPrincipal(prin_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 authenticated(self): """Check whether context is an authenticated principal. Sample usage in a page template: <tal:span tal:define="user request/principal" tal:condition="user/schooltool:authenticated" tal:replace="user/title"> User title </tal:span> <tal:span tal:define="user request/principal" tal:condition="not:user/schooltool:authenticated"> Anonymous </tal:span> """ if self.context is None: # no one is logged in return False if not IPrincipal.providedBy(self.context): raise TypeError("schooltool:authenticated can only be applied" " to a principal but was applied on %r" % self.context) return not IUnauthenticatedPrincipal.providedBy(self.context)
def principal_from_request(request=None): """ principal_from_request(request: IRequest) -> IPrincipal Find the primary :class:`IPrincipal` for the *request*. First adapts the request into an :class:`IInteraction` (probably using :func:`interaction_from_request`), and then adapts the interaction into an ``IPrincipal`` (probably using :func:`principal_from_interaction`). If there is no interaction, the unauthenticated principal is returned. This is registered as an adapter on the Pyramid ``IRequest`` interface; to provide a more specific policy, register an adapter on the concrete class. """ try: interaction = IInteraction( request if request is not None else get_current_request(), ) except NoInteraction: return component.getUtility(IFallbackUnauthenticatedPrincipal) return IPrincipal(interaction)
def isAvailable(group): principal = group.__principal__ if IPrincipal.providedBy(principal) and not IGroup.providedBy(principal): return getUtility(IProduct, 'zojax-forum').isInstalled() return False
def isUser(group): principal = group.__principal__ return IPrincipal.providedBy(principal) and not IGroup.providedBy(principal)
def test_checkRoles(self): principal = Principal('0101010001', '0101010001') self.assertTrue(IPrincipal(principal)) roles = IMyRoles(principal) self.assertEqual(roles.getAllRoles(), ['ENMS'])
def __init__(self, principal=unauthenticated_principal, replace=True): assert IPrincipal.providedBy(principal) self.participation = Participation(principal) self.replace = replace self.previous = None self.current = None