Package: z3c.authenticator
This package provides an IAuthentication implementation for Zope3. Note that
this implementation is independent of zope.app.authentication and it doesn’t
depend on that package. This means it doesn’t even use the credential or
authentication plugins offered from zope.app.authentication package.ContentsIAuthentication UtilitySecurityWhat’s different from PluggableAuthenticationAuthenticationFAQPrincipalAuthenticator PluginCredentials PluginAuthenticatedPrincipal and FoundPrincipalConfiguring the AuthenticatorAuthenticateChanging login namesEventsCustomizationEdge casesGroupGroupGroupContainerAdding users to groupsGroups in groupsIdentifying groupsspecialGroupsallGroupsVocabularyauthenticatorPluginscredentialsPluginsCHANGES2.0 (2023-02-09)1.0.1 (2018-05-16)1.0.0 (2017-04-17)1.0.0a5 (2013-03-31)1.0.0a4 (2013-02-28)1.0.0a3 (2013-02-28)1.0.0a2 (2013-02-28)1.0.0a1 (2013-02-28)0.8.1 (2011-01-21)0.8.0 (2010-01-25)0.7.2 (2010-01-26)0.7.1 (2009-08-19)0.7.0 (2009-05-11)0.6.2 (2010-01-26)0.6.1 (2009-08-19)0.6.0 (2009-01-04)0.5.1 (2008-04-16)0.5.0 (2008-04-16)IAuthentication UtilityThe Authenticator package provides a framework for authenticating principals
and associating information with them. It uses plugins and subscribers to get
its work done.For a simple authentication utility to be used, it should be registered as a
utility providing thezope.authentication.interfaces.IAuthenticationinterface.Our target is to support a handy IAuthentication utility which offers a simple
API for custom IUser implementations and does not depend on the default
zope.app.authentication implementation.SecurityThe Authenticator supports unique id tokens for principals. This means
principal that get deleted and again added with the same id, login etc. do
not have the same id again. We support this by generate a user id token
generated by the host id, timestamp, a random string and the login attribute.What’s different from PluggableAuthenticationWe use a different pattern for IAuthenticatorPlugins in this implementation
than used in PluggableAuthentication from zope.app.authentication,
because the pluggable authentication is not very handy when it comes to
implementing custom principal information. The IPrincipalInfo hook supporting
not propagate the password of a IInternalPrincipal is droped in this
implementation.In our implementation we offer a IFoundPrincipal and IAuthenticatedPrincipal
which are implemented as adapters for a IUser. These adapters do not offer
their context which is the real IUser.The Authenticator doesn’t use a prefix. The usage of a prefix is only
implemented in the IGroupContainer.We do not use a prefix in the IUserContainer because of the used unique user
id tokens. This will make sure that the same principal id doesn’t get used at
a later time (common criteria). There is aaddmethod which creates
this id for you based on the login. The __setitem__ should not get used
directly for adding IUser instances anymore. We heavily restricted the
usage of this method. See the inline doc tests in __setitem__ for more info.AuthenticationThe primary job of Authenticator is to authenticate principals. It uses
two types of plug-ins in its work:Credentials PluginsAuthenticator PluginsCredentials plugins are responsible for extracting user credentials from a
request. A credentials plugin may in some cases issue a ‘challenge’ to obtain
credentials. For example, a ‘session’ credentials plugin reads credentials
from a session (the “extraction”). If it cannot find credentials, it will
redirect the user to a login form in order to provide them (the “challenge”).Authenticator plugins are responsible for authenticating the credentials
extracted by a credentials plugin. They are also typically able to create
principal objects for credentials they successfully authenticate.Given a request object, the Authenticator returns a principal object, if it
can. The Authenticator utility does this by first iterating through its
credentials plugins to obtain a set of credentials. If it gets credentials, it
iterates through its authenticator plugins to authenticate them.If an authenticator succeeds in authenticating a set of credentials, the
Authenticator uses the authenticator to create a principal
corresponding to the credentials. The authenticator notifies subscribers if
an authenticated principal is created. Subscribers are responsible for adding
data, especially groups, to the principal. Typically, if a subscriber adds
data, it should also add corresponding interface declarations.FAQHere some useful hints:How should I set permission for principals?You can apply roles to groups
and apply permissions to roles. Or you can directly apply local permisssions
to groups or to principals. After setting up these mappings you can grant roles to
groups. I always recommend a principal - group and permission - role mapping,
this gives you the most possible abstraction which is useful if it comes
to managing permissions and principals without directly invoking principals and
permissions themselves. But of course you can grant permissions to groups or the
worst thing, directly to principals. Granting permissions to principals is only
useful if it comes to selective local permission settings for selected
principals, e.g. an ownership-like permission setup.How can I set permissions for all principals?You can register one
group as IEveryone utility. This IGroup utility get applied to all principals.Can I apply local groups to unauthenticated principals?Yes this will work.
Since the last refactoring I refactored the IGroup implementation which makes
it compatible with the principalregistry API. This means you can now register
one local group as an unnamed IUnauthenticatedGroup. You can also register one
local group as an unnamed IAuthenticatedGroup utility which will get applied
to every authenticated principal or an unnamed utility for
IUnauthenticatedGroup.Can I apply a local group to every principal?Yes, this is possible if you
register a local unnamed utility providing IEveryoneGroup.PrincipalFirst we create a principal:>>> from z3c.authenticator import interfaces
>>> from z3c.authenticator.user import User
>>> login = 'bob'
>>> password = 'secret'
>>> title = 'Bob'
>>> p = User(login, password, title)Such a principal provides the following attributes be default>>> p.login
'bob'>>> p.password.decode('utf-8')
'secret'>>> p.title
'Bob'and IUser:>>> interfaces.IUser.providedBy(p)
TrueAuthenticator PluginFirst set up a UserContainer which will store the principals:>>> from z3c.authenticator.user import UserContainer
>>> authPlugin = UserContainer()Now we have a UserContainer that provides an IUserContainer:>>> interfaces.IUserContainer.providedBy(authPlugin)
TrueNow we will add the created principal to the principal container using the
container’saddmethod:>>> uid, user = authPlugin.add(p)The method returns the user id and the user object. The id gets generated
from the host IP address, the time, a random string and the user login attr.
This token should be unique and guaranteed that it will never get generated twice.
This allows us to add, delete and add the same user again without having such a
user inheriting existing permissions. We can test this token by comparing it
only with the __name__ of the object in this test since the token will be
different every test run.>>> user.__name__ == uid
TrueThe returned user is still our previous added IUser>>> user is p
True>>> len(user.__name__)
32>>> user.login
'bob'>>> user.password.decode('utf-8')
'secret'>>> user.title
'Bob'Let’s register the UserContainer as a named IAuthenticatorPlugin utility:>>> import zope.component
>>> zope.component.provideUtility(authPlugin,
...     provides=interfaces.IAuthenticatorPlugin,
...     name='My Authenticator Plugin')Credentials PluginAfter seting up the user and user container, we’ll create a simple credentials
plugin:>>> import zope.interface
>>> import zope.component>>> @zope.interface.implementer(interfaces.ICredentialsPlugin)
... class MyCredentialsPlugin(object):
...
...
...     def extractCredentials(self, request):
...         return {'login': request.get('login', ''),
...                 'password': request.get('password', '')}
...
...     def challenge(self, request):
...         pass # challenge is a no-op for this plugin
...
...     def logout(self, request):
...         pass # logout is a no-op for this pluginAs a plugin, MyCredentialsPlugin needs to be registered as a named utility or
it could be stored in the Authenticator attribute credentialsPlugins.
Use the first and register the plugina utility:>>> myCredentialsPlugin = MyCredentialsPlugin()
>>> zope.component.provideUtility(myCredentialsPlugin,
...     name='My Credentials Plugin')AuthenticatedPrincipal and FoundPrincipalWhile authenticator plugins provide users, they are not responsible for
creating principals. This function is performed by the Authenticator:>>> from z3c.authenticator.principal import AuthenticatedPrincipal
>>> from z3c.authenticator.principal import FoundPrincipal
>>> zope.component.provideAdapter(AuthenticatedPrincipal,
...     provides=interfaces.IAuthenticatedPrincipal)>>> zope.component.provideAdapter(FoundPrincipal,
...     provides=interfaces.IFoundPrincipal)Configuring the AuthenticatorFinally, we’ll create the Authenticator itself:>>> from z3c.authenticator import authentication
>>> auth = authentication.Authenticator()and configure it with the two plugins:>>> auth.credentialsPlugins = ('My Credentials Plugin', )
>>> auth.authenticatorPlugins = ('My Authenticator Plugin', )AuthenticateWe can now use the Authenticator to authenticate a sample request:>>> from zope.publisher.browser import TestRequest
>>> print(auth.authenticate(TestRequest()))
NoneIn this case, we cannot authenticate an empty request. In the same way, we
will not be able to authenticate a request with the wrong credentials:>>> request = TestRequest(form={'login': 'let me in!', 'password': 'secret'})
>>> print(auth.authenticate(request))
NoneHowever, if we provide the proper credentials:>>> request = TestRequest(form={'login': 'bob', 'password': 'secret'})
>>> bob = auth.authenticate(request)
>>> bob
<AuthenticatedPrincipal...>>>> interfaces.IAuthenticatedPrincipal.providedBy(bob)
Truewe get an authenticated principal.Changing login namesChanging the login (i.e. username) of a principal is always a critical task because such a
login together with a password is the key to our implemenation. Let’s try to
change the login and check if everything is correct. We can do this by getting the
principal from the UserContainer and changing the login on the IUser
implementation:>>> internal = authPlugin[bob.id]
>>> internal.login = 'bob2'Now we should be able to login with the new login:>>> request = TestRequest(form={'login': 'bob2', 'password': 'secret'})
>>> bob2 = auth.authenticate(request)
>>> bob2
<AuthenticatedPrincipal ...>>>> bob2.title
'Bob'But not with the old one:>>> request = TestRequest(form={'login': 'bob', 'password': 'secret'})
>>> auth.authenticate(request) == None
TrueThe user bob has still the same id as bob2 since the user id token doesn’t
get changed by changing the login:>>> bob.id == bob2.id
TrueEventsAuthenticating a principal will create events.>>> from zope.component.eventtesting import getEvents
>>> from zope.component.eventtesting import clearEventsWe can verify that the appropriate event was published:>>> clearEvents()
>>> request = TestRequest(form={'login': 'bob2', 'password': 'secret'})
>>> bobAgain = auth.authenticate(request)And the principal attribute in the event provides the authenticated principal:>>> [event] = getEvents(interfaces.IAuthenticatedPrincipalCreated)
>>> event.principal is bobAgain
True>>> event.principal
<AuthenticatedPrincipal ...>>>> event.request is request
TrueThe principal has the id, title, and description.>>> event.principal.title
'Bob'>>> event.principal.id == uid
True>>> event.principal.description
''We provide subscribers to these events that can be used for doing custom
processing. Note, the principal attibute provides an IAuthenticatedPrincipal:>>> def addInfo(event):
...     id = event.principal.id
...     event.principal.description = 'Description for: %s' % id>>> zope.component.provideHandler(addInfo,
...     [interfaces.IAuthenticatedPrincipalCreated])Now, if we authenticate a principal, its description is set:>>> principal = auth.authenticate(request)
>>> principal.description
'Description for: ...'CustomizationLet’s show you how the existing pattern can get used in a real use case. In
the next sample we’d like to provide an additional email attribute for principals.
First we have to define the interfaces declaring the email attribute:>>> class IMyEmail(zope.interface.Interface):
...     email = zope.schema.TextLine(
...         title='EMail',
...         description='The EMail')>>> class IMyUser(IMyEmail, interfaces.IUser):
...     """Custom IUser interface.""">>> class IMyFoundPrincipal(IMyEmail, interfaces.IFoundPrincipal):
...     """Custom IIMyFoundrincipal interface.""">>> class IMyAuthenticatedPrincipal(IMyEmail,
...     interfaces.IAuthenticatedPrincipal):
...     """Custom IAuthenticatedPrincipal interface."""After the schema, we define a custom principal implementation implementing
this interface:>>> @zope.interface.implementer(IMyUser)
... class MyUser(User):
...     def __init__(self, login, password, title, description, email):
...         super(MyUser, self).__init__(login, password, title,
...                                           description)
...         self.email = emailNow we have to define the AuthenticatedPrincipal for MyUser:>>> @zope.interface.implementer(IMyAuthenticatedPrincipal)
... class MyAuthenticatedPrincipal(AuthenticatedPrincipal):
...     def __init__(self, principal):
...         super(MyAuthenticatedPrincipal, self).__init__(principal)
...         self.email = principal.emailAnd we have to define the FoundPrincipal for MyUser:>>> @zope.interface.implementer(IMyFoundPrincipal)
... class MyFoundPrincipal(FoundPrincipal):
...     def __init__(self, principal):
...         super(MyFoundPrincipal, self).__init__(principal)
...         self.email = principal.emailNote that you can provide different attributes for the found and authenticated
principals if needed. That’s up to you what you like to do with these attributes
later.Now we need to register our custom authenticated and found principal
adapters:>>> zope.component.provideAdapter(MyAuthenticatedPrincipal,
...     provides=interfaces.IAuthenticatedPrincipal)>>> zope.component.provideAdapter(MyFoundPrincipal,
...     provides=interfaces.IFoundPrincipal)Now we can use them without any other event subscribers or other registration
in our principal container. Let’s add a principal to this container:>>> p = MyUser('max', 'password', 'Max', '', 'max@foobar.com')
>>> token, max = authPlugin.add(p)
>>> len(token)
32>>> max.__name__ == token
True>>> max.password.decode('utf-8')
'password'>>> max.title
'Max'>>> max.email
'max@foobar.com'Let’s try to authenticate…>>> request = TestRequest(form={'login': 'max', 'password': 'password'})
>>> authenticated = auth.authenticate(request)and check your authenticated principal:>>> interfaces.IAuthenticatedPrincipal.providedBy(authenticated)
True>>> authenticated
<MyAuthenticatedPrincipal ...>>>> authenticated.id == token
True>>> authenticated.email
'max@foobar.com'Check getUserByLogin:>>> max = authPlugin.getUserByLogin('max')
>>> max.__class__.__name__
'MyUser'>>> authPlugin.getUserByLogin('max').login
'max'>>> authPlugin.getUserByLogin('max').__name__ == token
TrueA handy feature for migration is that you can set your owntoken.
Usually in z.a.authentication thetoken== login and we want to keep it
that way, unless you want to iterate through all permissions and whatever.
Note, the __name__ and the id in the container must be theSAMEobject.>>> login = 'migrateduser'
>>> p = User(login, 'password', 'John')Preset thetoken>>> p.__name__ = loginWatch out, we use __setitem__ instead of add(), because add() would kill off
the presettokenin __name__.>>> authPlugin[login] = pHere we are, the user is set with the non-generated token.>>> 'migrateduser' in authPlugin.keys()
True>>> authPlugin['migrateduser']
<z3c.authenticator.user.User object at ...>>>> authPlugin.getUserByLogin('migrateduser')
<z3c.authenticator.user.User object at ...>Edge casesWe can have Users with text logins, as we allow this with TextLine in IUser.>>> p = User('bob'+chr(233), 'password', 'title')Adding it should not fail:>>> uid, user = authPlugin.add(p)GroupGroup container provide support for groups information stored in the ZODB.
They are persistent, and must be contained within the IAuthentication that
use them.GroupLike other users, groups are created when they are needed.>>> from z3c.authenticator import interfaces
>>> from z3c.authenticator.group import Group
>>> group1 = Group('groups')
>>> group1
<Group None>>>> interfaces.IGroup.providedBy(group1)
True>>> group1.title
'groups'>>> group1.description
''>>> group1.principals
()GroupContainerGroup containers contain IGroup objects. A IAuthentication will adapt
IFoundGroup to this IGroup objects.>>> from z3c.authenticator.group import GroupContainer
>>> groups = GroupContainer('groups.')>>> interfaces.IGroupContainer.providedBy(groups)
TrueWe can add your previous created group to the group container using the
addGroup method which returns the group id and group:>>> gid, g1 = groups.addGroup('g1', group1)
>>> gid
'groups.g1'>>> interfaces.IGroup.providedBy(g1)
True>>> g1.__name__
'groups.g1'Note that when group is added, a GroupAdded event is generated:>>> from zope.component.eventtesting import getEvents
>>> getEvents(interfaces.IGroupAdded)
[<GroupAdded 'groups.g1'>]Groups are defined with respect to an authentication service. Groups must be
accessible via an authentication service and can contain principals accessible
via an authentication service. To illustrate the group interaction with the
authentication service, we will setup a Authenticator utility:>>> from z3c.authenticator.authentication import Authenticator
>>> authenticator = Authenticator()Give them a location and register them as a IAuthentication utility :>>> import zope.component
>>> from zope.authentication.interfaces import IAuthentication
>>> rootFolder['authenticator'] = authenticator
>>> zope.component.provideUtility(authenticator, IAuthentication)We will create and register a new principals utility:>>> zope.component.provideUtility(authenticator, IAuthentication)We also need to register the group athentication plugin:>>> zope.component.provideUtility(groups,
...     provides=interfaces.IAuthenticatorPlugin,
...     name='My Group Plugin')After setup the group and group container, we will create a simple credentials
plugin and add them to the authentication utility:>>> import zope.interface
>>> from z3c.authenticator import interfaces>>> @zope.interface.implementer(interfaces.ICredentialsPlugin)
... class MyCredentialsPlugin(object):
...
...     def extractCredentials(self, request):
...         return {'login':request.get('login', ''),
...                 'password':request.get('password', '')}
...
...     def challenge(self, request):
...         pass # challenge is a no-op for this plugin
...
...     def logout(self, request):
...         pass # logout is a no-op for this pluginand configure and add the credential plugin to the Authenticator:>>> myCredentialsPlugin = MyCredentialsPlugin()
>>> authenticator['credentials'] = myCredentialsPlugin
>>> authenticator.credentialsPlugins = ('credentials', )We also need a principal and a IAuthenticationPlugin:>>> from z3c.authenticator.user import User
>>> p1 = User('p1', 'password', 'Principal 1')
>>> p2 = User('p2', 'password', 'Principal 2')
>>> p3 = User('p3', 'password', 'Principal 3')
>>> p4 = User('p4', 'password', 'Principal 4')>>> from z3c.authenticator.user import UserContainer
>>> users = UserContainer()
>>> token1, p1 = users.add(p1)
>>> token2, p2 = users.add(p2)
>>> token3, p3 = users.add(p3)
>>> token4, p4 = users.add(p4)Add the GroupContainer and UserContainer to the Authenticator and
set the correct plugin names>>> authenticator['users'] = users
>>> authenticator['groups'] = groups
>>> authenticator.authenticatorPlugins = ('users', 'groups')Adding users to groupsNow we can set the users on the group but first we need to register the
IFoundPrincipal adapter for groups. The FoundGroup adapter provides this
interface:>>> from z3c.authenticator.principal import FoundGroup
>>> zope.component.provideAdapter(FoundGroup,
...     provides=interfaces.IFoundPrincipal)And we also need to provide the IFoundPrincipal and IAuthenticatedPrincipal
adapter for IPrincipal objects:>>> from z3c.authenticator.principal import AuthenticatedPrincipal
>>> from z3c.authenticator.principal import FoundPrincipal
>>> zope.component.provideAdapter(AuthenticatedPrincipal,
...     provides=interfaces.IAuthenticatedPrincipal)>>> zope.component.provideAdapter(FoundPrincipal,
...     provides=interfaces.IFoundPrincipal)And we need thesetGroupsForPrincipalsubscriber:>>> from z3c.authenticator.group import setGroupsForPrincipal
>>> zope.component.provideHandler(setGroupsForPrincipal,
...     [interfaces.IPrincipalCreated])>>> g1.principals = [p1.__name__, p2.__name__]
>>> g1.principals
(..., ...)>>> g1.principals[0] == p1.__name__
True>>> g1.principals[1] == p2.__name__
TrueAdding users fires an event.>>> getEvents(interfaces.IPrincipalsAddedToGroup)[-1]
<PrincipalsAddedToGroup [..., ...] 'groups.g1'>We can now look up groups for the users:>>> groups.getGroupsForPrincipal(p1.__name__)
('groups.g1',)Note that the group id is a concatenation of the group-folder prefix
and the name of the group object within the folder.If we delete a group:>>> del groups['groups.g1']then the groups folder loses the group information for that group’s users:>>> groups.getGroupsForPrincipal('p1')
()but the principal information on the group is unchanged:>>> g1.principals
(..., ...)>>> g1.principals[0] == p1.__name__
True>>> g1.principals[1] == p2.__name__
TrueIt also fires an event showing that the users are removed from the groups.>>> getEvents(interfaces.IPrincipalsRemovedFromGroup)[-1]
<PrincipalsRemovedFromGroup [..., ...] 'groups.g1'>Adding the group again within a different name will make the groups
available for the principal. Let’s use a different group name:>>> groups['groups.G1'] = g1>>> groups.getGroupsForPrincipal(p1.__name__)
('groups.G1',)Here we see that the new name is reflected in the group information.An event is fired, as usual.>>> getEvents(interfaces.IPrincipalsAddedToGroup)[-1]
<PrincipalsAddedToGroup [..., ...] 'groups.G1'>In terms of member events (members added and removed from groups), we have
now seen that events are fired when a group object is added and when it is
removed from a group container; and we have seen that events are fired
when a principal is added to an already-registered groups.  Events are also
fired when a principal is removed from an already-registered groups.  Let’s
quickly see some more examples.>>> g1.principals = (p1.__name__, p3.__name__, p4.__name__)
>>> g1.principals
(..., ..., ...)>>> g1.principals[0] == p1.__name__
True>>> g1.principals[1] == p3.__name__
True>>> g1.principals[2] == p4.__name__
True>>> getEvents(interfaces.IPrincipalsAddedToGroup)[-1]
<PrincipalsAddedToGroup [..., ...] 'groups.G1'>>>> getEvents(interfaces.IPrincipalsRemovedFromGroup)[-1]
<PrincipalsRemovedFromGroup [...] 'groups.G1'>>>> g1.principals = (p1.__name__, p2.__name__)
>>> g1.principals
(..., ...)>>> g1.principals[0] == p1.__name__
True>>> g1.principals[1] == p2.__name__
True>>> getEvents(interfaces.IPrincipalsAddedToGroup)[-1]
<PrincipalsAddedToGroup [...] 'groups.G1'>>>> getEvents(interfaces.IPrincipalsRemovedFromGroup)[-1]
<PrincipalsRemovedFromGroup [..., ...] 'groups.G1'>>>> groups.getGroupsForPrincipal(p2.__name__)
('groups.G1',)Groups in groupsGroups can contain groups:>>> g2 = Group('Group Two')
>>> groups['groups.G2'] = g2
>>> g2.principals
()>>> g2.principals = ['groups.G1']>>> g2.principals
('groups.G1',)>>> groups.getGroupsForPrincipal('groups.G2')
()>>> g1.principals
(..., ...)>>> g1.principals[0] == p1.__name__
True>>> g1.principals[1] == p2.__name__
True>>> groups.getGroupsForPrincipal('groups.G1')
('groups.G2',)>>> old = getEvents(interfaces.IPrincipalsAddedToGroup)[-1]
>>> old
<PrincipalsAddedToGroup ['groups.G1'] 'groups.G2'>Groups cannot contain cycles:>>> g1.principals
(..., ...)>>> g1.principals[0] == p1.__name__
True>>> g1.principals[1] == p2.__name__
True>>> g2.principals
('groups.G1',)>>> g1.principals = (p1.__name__, p2.__name__, 'groups.G2')
Traceback (most recent call last):
...
z3c.authenticator.group.GroupCycle: (...)>>> g1.principals
(..., ...)>>> g1.principals[0] == p1.__name__
True>>> g1.principals[1] == p2.__name__
TrueTrying to do so does not fire an event.>>> getEvents(interfaces.IPrincipalsAddedToGroup)[-1] is old
TrueThey need not be hierarchical:>>> ga = Group("Group A")
>>> groups['groups.GA'] = ga>>> gb = Group("Group B")
>>> groups['groups.GB'] = gb
>>> gb.principals = ['groups.GA']>>> gc = Group("Group C")
>>> groups['groups.GC'] = gc
>>> gc.principals = ['groups.GA']>>> gd = Group("Group D")
>>> groups['groups.GD'] = gd
>>> gd.principals = ['groups.GA', 'groups.GB']>>> ga.principals = [p1.__name__]Group containers provide a very simple search interface.  They perform
simple string searches on group titles and descriptions.>>> list(groups.search({'search': 'gro'}))
['groups.G1', 'groups.G2',
 'groups.GA', 'groups.GB', 'groups.GC', 'groups.GD']>>> list(groups.search({'search': 'two'}))
['groups.G2']They also support batching:>>> list(groups.search({'search': 'gro'}, 2, 3))
['groups.GA', 'groups.GB', 'groups.GC']If you don’t supply a search key, no results will be returned:>>> list(groups.search({}))
[]Identifying groupsThe function,setGroupsForPrincipal, is a subscriber to
principal-creation events.  It adds any group-folder-defined groups to
users in those groups:>>> auth1 = authenticator.getPrincipal(p1.__name__)>>> auth1.groups
['groups.G1', 'groups.GA']Of course, this applies to groups too:>>> g1 = authenticator.getPrincipal('groups.G1')
>>> g1.id
'groups.G1'>>> g1.groups
['groups.G2']A FoundGroup provides IFoundGroup which is inherited from
IFoundPrincipal and IGroup:>>> interfaces.IFoundGroup.providedBy(g1)
True>>> interfaces.IFoundPrincipal.providedBy(g1)
True>>> import zope.security.interfaces
>>> zope.security.interfaces.IGroup.providedBy(g1)
TruespecialGroupsTwo special groups, IAuthenticatedGroup, and IEveryoneGroup may apply to users
created by the IAuthentication utility.  There is a subscriber calledspecialGroups. This subscriber can set this special groups on any
principal if IAuthenticatedGroup, or IEveryoneGroup utilities are
provided. The subscriber knows also how to apply local groups to principals.
Note, principals means IAuthenticatedPrincipal, IFoundPrincipal or IFoundGroup.If we notify the subscriber with the principal, nothing will happen
because the groups haven’t been defined:>>> from z3c.authenticator.principal import FoundPrincipal
>>> from z3c.authenticator.event import FoundPrincipalCreated
>>> from z3c.authenticator.group import specialGroups
>>> x = User('x', 'password', 'X')
>>> found = FoundPrincipal(x)
>>> event = FoundPrincipalCreated(authenticator, found)
>>> specialGroups(event)
>>> found.groups
[]Now, if we define the Everybody group:>>> import zope.authentication.interfaces
>>> @zope.interface.implementer(
...        zope.authentication.interfaces.IEveryoneGroup)
... class EverybodyGroup(Group):
...     pass>>> all = EverybodyGroup('groups.all')
>>> groups['groups.all'] = all
>>> zope.component.provideUtility(all,
...     zope.authentication.interfaces.IEveryoneGroup)Then the group will be added to the principal:>>> specialGroups(event)
>>> found.groups
['groups.all']Similarly for the authenticated group:>>> @zope.interface.implementer(
...         zope.authentication.interfaces.IAuthenticatedGroup)
... class AuthenticatedGroup(Group):
...     pass>>> authenticated = AuthenticatedGroup('groups.authenticated')
>>> groups['groups.authenticated'] = authenticated
>>> zope.component.provideUtility(authenticated,
...     zope.authentication.interfaces.IAuthenticatedGroup)Then the group will be added to the principal:>>> found.groups = []
>>> specialGroups(event)
>>> found.groups.sort()
>>> found.groups
['groups.all', 'groups.authenticated']It is important that we do not apply a group twice since the
UnauthenticatedPrincipal is a single instance in the securitypolicy. This issue
is fixed in version 0.6.1 and 0.7.1>>> specialGroups(event)
>>> found.groups
['groups.all', 'groups.authenticated']allGroupsTheallGroupsattribute is a readonly iterable of the full closure of the
groups in thegroupsattribute. Let’s define a new principal first:>>> p = User('p', 'password', 'Principal')
>>> token, p = users.add(p)And the groups:>>> ga = Group("Administrators")
>>> gr = Group("Reviewers")
>>> gid, ga = groups.addGroup('Administrators', ga)
>>> gid, gr = groups.addGroup('Reviewers', gr)If the principal is a direct member of the ‘Administrators’ group,>>> ga.principals = [p.__name__]then getGroupsForPrincipal would be [‘Administrators’]>>> groups.getGroupsForPrincipal(p.__name__)
('groups.Administrators',)and if the ‘Administrators’ group is a member of the ‘Reviewers’ group,>>> gr.principals = [ga.id]then groups would be [‘Administrators’] too.>>> groups.getGroupsForPrincipal(p.__name__)
('groups.Administrators',)now let’s use the setGroupsForPrincipal subscriber which knows how to apply
the groups to the found principal:>>> pFound = FoundPrincipal(p)
>>> event = FoundPrincipalCreated(authenticator, pFound)
>>> setGroupsForPrincipal(event)As you can see and pFound.groups is [‘Administrators’].>>> sorted(pFound.groups)
['groups.Administrators']And pFound.allGroups is [‘Administrators’, ‘Reviewers’].>>> sorted(pFound.allGroups)
['groups.Administrators', 'groups.Reviewers']VocabularyThe vocabulary module provides vocabularies for the authenticator plugins and
the credentials plugins.The options should include the unique names of all of the plugins that provide
the appropriate interface (IAuthentiatorPlugin or ICredentialsPlugin,
respectively) for the current context which is expected to be a IAuthenticator
utility, hereafter referred to as a Authenticator.These names may be for objects contained within the Authenticator
(“contained plugins”), or may be utilities registered for the specified
interface, found in the context of the Authenticator
(“utility plugins”). Contained plugins mask utility plugins of the same name.
They also may be names currently selected in the Authenticator that do
not actually have a corresponding plugin at this time.Here is a short example of how the vocabulary should work.  Let’s say we’re
working with authentication plugins.  We’ll create some faux
authentication plugins, and register some of them as utilities and put
others in a faux Authenticator.>>> from z3c.authenticator import interfaces
>>> import zope.interface
>>> import zope.component
>>> @zope.interface.implementer(interfaces.IAuthenticatorPlugin)
... class DemoPlugin(object):
...     def __init__(self, name):
...         self.name = name
...
>>> utility_plugins = dict(
...     (i, DemoPlugin('Plugin %d' % i)) for i in range(4))
>>> contained_plugins = dict(
...     (i, DemoPlugin('Plugin %d' % i)) for i in range(1, 5))
>>> sorted(utility_plugins.keys())
[0, 1, 2, 3]
>>> for p in utility_plugins.values():
...     zope.component.provideUtility(p, name=p.name)
...
>>> sorted(contained_plugins.keys()) # 1 will mask utility plugin 1
[1, 2, 3, 4]
>>> @zope.interface.implementer(interfaces.IAuthenticator)
... class DemoAuth(dict):
...     def __init__(self, *args, **kwargs):
...         super(DemoAuth, self).__init__(*args, **kwargs)
...         self.authenticatorPlugins = ('Plugin 3', 'Plugin X')
...         self.credentialsPlugins = ('Plugin 4', 'Plugin X')
...
>>> auth = DemoAuth((p.name, p) for p in contained_plugins.values())>>> @zope.component.adapter(zope.interface.Interface)
... @zope.interface.implementer(zope.component.IComponentLookup)
... def getSiteManager(context):
...     return zope.component.getGlobalSiteManager()
...
>>> zope.component.provideAdapter(getSiteManager)authenticatorPluginsWe are now ready to create a vocabulary that we can use.  The context is
our faux authentication utility,auth.>>> from z3c.authenticator import vocabulary
>>> vocab = vocabulary.authenticatorPlugins(auth)Iterating over the vocabulary results in all of the terms, in a relatively
arbitrary order of their names.  (This vocabulary should typically use a
widget that sorts values on the basis of localized collation order of the
term titles.)>>> [term.value for term in vocab] # doctest: +NORMALIZE_WHITESPACE
['Plugin 0', 'Plugin 1', 'Plugin 2', 'Plugin 3', 'Plugin 4',
 'Plugin X']Similarly, we can useinto test for the presence of values in the
vocabulary.>>> ['Plugin %s' % i in vocab for i in range(-1, 6)]
[False, True, True, True, True, True, False]
>>> 'Plugin X' in vocab
TrueThe length reports the expected value.>>> len(vocab)
6One can get a term for a given value usinggetTerm(); its token, in
turn, should also return the same effective term fromgetTermByToken.>>> values = ['Plugin 0', 'Plugin 1', 'Plugin 2', 'Plugin 3', 'Plugin 4',
...           'Plugin X']
>>> for val in values:
...     term = vocab.getTerm(val)
...     assert term.value == val
...     term2 = vocab.getTermByToken(term.token)
...     assert term2.token == term.token
...     assert term2.value == val
...The terms have titles, which are message ids that show the plugin title or id
and whether the plugin is a utility or just contained in the auth utility.
We’ll give one of the plugins a dublin core title just to show the
functionality.>>> import zope.dublincore.interfaces
>>> class ISpecial(zope.interface.Interface):
...     pass
...
>>> zope.interface.directlyProvides(contained_plugins[1], ISpecial)
>>> @zope.interface.implementer(
...         zope.dublincore.interfaces.IDCDescriptiveProperties)
... class DemoDCAdapter(object):
...     zope.component.adapts(ISpecial)
...     def __init__(self, context):
...         pass
...     title = 'Special Title'
...
>>> zope.component.provideAdapter(DemoDCAdapter)We need to regenerate the vocabulary, since it calculates all of its data at
once.>>> vocab = vocabulary.authenticatorPlugins(auth)Now we’ll check the titles.  We’ll have to translate them to see what we
expect.>>> from zope import i18n
>>> import pprint
>>> pprint.pprint([i18n.translate(term.title) for term in vocab])
['Plugin 0 (a utility)',
 'Special Title (in contents)',
 'Plugin 2 (in contents)',
 'Plugin 3 (in contents)',
 'Plugin 4 (in contents)',
 'Plugin X (not found; deselecting will remove)']credentialsPluginsFor completeness, we’ll do the same review of the credentialsPlugins.>>> @zope.interface.implementer(interfaces.ICredentialsPlugin)
... class DemoPlugin(object):
...     def __init__(self, name):
...         self.name = name
...
>>> utility_plugins = dict(
...     (i, DemoPlugin('Plugin %d' % i)) for i in range(4))
>>> contained_plugins = dict(
...     (i, DemoPlugin('Plugin %d' % i)) for i in range(1, 5))
>>> for p in utility_plugins.values():
...     zope.component.provideUtility(p, name=p.name)
...
>>> auth = DemoAuth((p.name, p) for p in contained_plugins.values())
>>> vocab = vocabulary.credentialsPlugins(auth)Iterating over the vocabulary results in all of the terms, in a relatively
arbitrary order of their names.  (This vocabulary should typically use a
widget that sorts values on the basis of localized collation order of the term
titles.) Similarly, we can useinto test for the presence of values in the
vocabulary. The length reports the expected value.>>> [term.value for term in vocab] # doctest: +NORMALIZE_WHITESPACE
['Plugin 0', 'Plugin 1', 'Plugin 2', 'Plugin 3', 'Plugin 4',
 'Plugin X']
>>> ['Plugin %s' % i in vocab for i in range(-1, 6)]
[False, True, True, True, True, True, False]
>>> 'Plugin X' in vocab
True
>>> len(vocab)
6One can get a term for a given value usinggetTerm(); its token, in
turn, should also return the same effective term fromgetTermByToken.>>> values = ['Plugin 0', 'Plugin 1', 'Plugin 2', 'Plugin 3', 'Plugin 4',
...           'Plugin X']
>>> for val in values:
...     term = vocab.getTerm(val)
...     assert term.value == val
...     term2 = vocab.getTermByToken(term.token)
...     assert term2.token == term.token
...     assert term2.value == val
...The terms have titles, which are message ids that show the plugin title or id
and whether the plugin is a utility or just contained in the auth utility.
We’ll give one of the plugins a dublin core title just to show the
functionality. We need to regenerate the vocabulary, since it calculates all
of its data at once. Then we’ll check the titles.  We’ll have to translate
them to see what we expect.>>> zope.interface.directlyProvides(contained_plugins[1], ISpecial)
>>> vocab = vocabulary.credentialsPlugins(auth)
>>> pprint.pprint([i18n.translate(term.title) for term in vocab])
['Plugin 0 (a utility)',
 'Special Title (in contents)',
 'Plugin 2 (in contents)',
 'Plugin 3 (in contents)',
 'Plugin 4 (in contents)',
 'Plugin X (not found; deselecting will remove)']CHANGES2.0 (2023-02-09)Drop support for Python 2.6, 2.7, 3.4, 3.5, 3.6.Add Python 3.7, 3.8, 3.9, 3.10, 3.11 support.Remove unused imports.1.0.1 (2018-05-16)bugfix: remove None from queryNextUtiliy because getNextUtility signature got
changed and None was used as name argument.cleanup, removed unused importsGet rid of deprecation warning. Switch hooks import from zope.site to
zope.componentskip test_exception_in_subscriber_leaves_item_in_place for IAuthenticator
container. This zope.container test method left over an event subscriber with
zope.container version 4.2.1 which raises an error in other methods. Needs
review and probably a tear down in zope.container test method.1.0.0 (2017-04-17)Ping Python support to 2.7, 3.5, 3.6 and PyPy.1.0.0a5 (2013-03-31)More Py3 compatibility bugs in untested code.1.0.0a4 (2013-02-28)Removed support for Zope generations. It was not used and application-wide
generations make more sense anyways. This removed thezope.app.generationsandzope.generationsdependencies.Madez3c.configuratorsupport optional.Cleaned up source code a little bit.1.0.0a3 (2013-02-28)Changed manifest to actually include the page templates.1.0.0a2 (2013-02-28)Added version Trove classifiers.1.0.0a1 (2013-02-28)Dropped support for Python 2.4 and 2.5, added Python 3.3 support.Removed dependencies onzope.apppackages.0.8.1 (2011-01-21)Bugfix: Did not handle unicode IUser.login values.Fixed DeprecationWarnings.0.8.0 (2010-01-25)Security Fix: move camefrom url to a session variable instead of exposing
the url in the login form. Because the camefrom url is built at server side
based on local information and will always only use internal traversal names.
Exposing this camefrom query in the login url gives others only a point to
attack because it could be simply set by a unfriendly domain with a custom
url. This is much better since such a unfriendly 3rd party domain url doesn’t
get redirected by default based on the changes in zope.publisher’s redirect
method. (zope.publisher 3.9.3 does only redirect to urls located in the same
domain by default)Remove all camefrom widgets and queries in our custom forms if you use any.
You can just set and get the camefrom session variable in your custom forms
if you need to.0.7.2 (2010-01-26)Bugfix: Failed miserably on challenge on pages having non-ASCII names.0.7.1 (2009-08-19)Bugfix: the method specialGroups applied groups everytime the method get
called even if the group was already applied. This is a problem if the
global shared unauthenticated principal instance is used because it will
apply similar groups till the server get restarted and a new principal
instance is used.Feature: added getUserByLogin to IUserContainerAdded a test for user migration (that they will keep their ID)0.7.0 (2009-05-11)Update dependencies:Usezope.containerinstead ofzope.app.container.Usezope.siteinstead ofzope.app.component.Usezope.authenticationandzope.principalregistryinstead
ofzope.app.security.Usezope.passwordinstead of maintaining a copy of password
managers.Drop dependency on z3c.i18n and recreate a message factory instead.0.6.2 (2010-01-26)Bugfix: Failed miserably on challenge on pages having non-ASCII names.
(Backport from 0.7.2)0.6.1 (2009-08-19)Backport bugfix 0.7.1 to 0.6.1. See branches/roger-0.6.0the method specialGroups applied groups everytime the method get
called even if the group was already applied. This is a problem if the
global shared unauthenticated principal instance is used because it will
apply similar groups till the server get restarted and a new principal
instance is used.0.6.0 (2009-01-04)Feature: added support for local IUnauthenticatedPrincipal. This is usefull
if you need to apply local roles to IUnauthenticatedPrincipal. This was not
possible before and is not possible in zope.app.authenticationFeature: implemented initial grant view based on ISource widget. Note, this
source widget terms implementation which is very complex to understand will
get moved to z3c.from if we fixed the ITerm dependency. Which means ITerm
needs to get moved out of zope.app.form first.Feature: added support for next utility lookup in authenticate call. By
default the principals from the global principalregistry get involved now.
You can disable this feature by setting includeNextUtilityForAuthenticate to
False.Feature: added PrincipalRegistryAuthenticatorPlugin which allows to
authenticate principals defined in global principal registry.Feature: implemented z3c.form prefix support in SessionCredentialsPlugin. Now
there is an option called prefixes which can be used for define a list of
used z3c.form prefixes. This makes it simpler for supporting different forms
and adjust the credential extraction.Renamed IGroupPrincipal to IFoundGroup which makes it more understandable
why this adapter implementation is needed. The IFoundGroup adapter is now
also used for zope.security.interfaces.IGroup principals. This makes it
possible to use them in the new principalregistry credential. Provide
deprecation message for the old IGroupPrincipal implementation.Removed dependency for zapi. But it’s not really gone since other packages
use zapi too.Removed unused InvalidPrincipalIds and InvalidGroupId exceptionsRemoved unused IMemberAwareGroup support. This interface is not used in zope
at all.Added documentation for Pypi home page.0.5.1 (2008-04-16)Cleanup imports and adjust dependencies0.5.0 (2008-04-16)Initial Release