Group Folders
=============

Group folders provide support for groups information stored in the
ZODB.

Like other principals, groups are created when they are needed.

Group folders contain group-information objects that contain group
information.  We create group information using the `GroupInformation` class:

  >>> import zope.app.authentication.groupfolder
  >>> g1 = zope.app.authentication.groupfolder.GroupInformation("Group 1")

  >>> groups = zope.app.authentication.groupfolder.GroupFolder('group.')
  >>> groups['g1'] = g1

Note that when group-info is added, a GroupAdded event is generated:

  >>> from zope.app.authentication import interfaces
  >>> from zope.app.event.tests.placelesssetup import getEvents
  >>> getEvents(interfaces.IGroupAdded)
  [<GroupAdded 'group.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'll create a sample authentication service:

  >>> from zope import interface
  >>> from zope.app.security.interfaces import IAuthentication, IPrincipal
  >>> from zope.app.authentication.groupfolder import setGroupsForPrincipal

  >>> class Principal:
  ...     interface.implements(IPrincipal)
  ...     def __init__(self, id, title, description):
  ...         self.id, self.title, self.description = id, title, description
  ...         self.groups = []

  >>> class PrincipalCreatedEvent:
  ...     def __init__(self, principal):
  ...         self.principal = principal

  >>> class Principals:
  ...
  ...     interface.implements(IAuthentication)
  ...
  ...     def __init__(self, groups):
  ...         self.principals = {
  ...            'p1': {'title': '', 'description': ''},
  ...            'p2': {'title': '', 'description': ''},
  ...            }
  ...         self.groups = groups
  ...
  ...     def getPrincipal(self, id):
  ...         info = self.principals.get(id)
  ...         if info is None:
  ...             info = self.groups.principalInfo(id)
  ...             if info is None:
  ...                return None
  ...         principal = Principal(id, **info)
  ...         setGroupsForPrincipal(PrincipalCreatedEvent(principal))
  ...         return principal

This class doesn't really implement the full `IAuthenticationService`
interface, but it implements the `getPrincipal` method used by groups.
It works very much like the pluggable authentication utility.  It
creates principals on demand.  It calls `setGroupsForPrincipal`, which
is normally called as an event subscriber, when principals are
created.  In order for `setGroupsForPrincipal` to find out group
folder, we have to register it as a utility:

  >>> from zope.app.testing import ztapi
  >>> ztapi.provideUtility(zope.app.authentication.groupfolder.IGroupFolder,
  ...                      groups)

The authentication service has a very simple implementation.  It has a
`principals` dictionary and a groups folder.

  >>> principals = Principals(groups)
  >>> ztapi.provideUtility(IAuthentication, principals)

Now we can set the principals on the group:

  >>> g1.principals = ['p1', 'p2']
  >>> g1.principals
  ('p1', 'p2')

This allows us to look up groups for the principals:

  >>> groups.getGroupsForPrincipal('p1')
  (u'group.g1',)

Note that the group id is a concatenation of the group-folder prefix
and the name of the group-information object within the folder.

If we delete a group:

  >>> del groups['g1']

then the groups folder loses the group information for that group's
principals: 

  >>> groups.getGroupsForPrincipal('p1')
  ()

but the principal information on the group is unchanged:

  >>> g1.principals
  ('p1', 'p2')

Adding the group sets the folder principal information.  Let's use a
different group name:

  >>> groups['G1'] = g1

  >>> groups.getGroupsForPrincipal('p1')
  (u'group.G1',)

Here we see that the new name is reflected in the group information.

Groups can contain groups:

  >>> g2 = zope.app.authentication.groupfolder.GroupInformation("Group Two")
  >>> groups['G2'] = g2
  >>> g2.principals = ['group.G1']

  >>> groups.getGroupsForPrincipal('group.G1')
  (u'group.G2',)

Groups cannot contain cycles:

  >>> g1.principals = ('p1', 'p2', 'group.G2')
  Traceback (most recent call last):
  ...
  GroupCycle: (u'group.G1', [u'group.G1', u'group.G2'])
  
They need not be hierarchical:

  >>> ga = zope.app.authentication.groupfolder.GroupInformation("Group A")
  >>> groups['GA'] = ga

  >>> gb = zope.app.authentication.groupfolder.GroupInformation("Group B")
  >>> groups['GB'] = gb
  >>> gb.principals = ['group.GA']

  >>> gc = zope.app.authentication.groupfolder.GroupInformation("Group C")
  >>> groups['GC'] = gc
  >>> gc.principals = ['group.GA']

  >>> gd = zope.app.authentication.groupfolder.GroupInformation("Group D")
  >>> groups['GD'] = gd
  >>> gd.principals = ['group.GA', 'group.GB']

  >>> ga.principals = ['p1']

Group folders provide a very simple search interface.  They perform
simple string searches on group titles and descriptions.

  >>> list(groups.search({'search': 'grou'})) # doctest: +NORMALIZE_WHITESPACE
  [u'group.G1', u'group.G2',
   u'group.GA', u'group.GB', u'group.GC', u'group.GD']

  >>> list(groups.search({'search': 'two'}))
  [u'group.G2']

They also support batching:

  >>> list(groups.search({'search': 'grou'}, 2, 3))
  [u'group.GA', u'group.GB', u'group.GC']


If you don't supply a search key, no results will be returned:

  >>> list(groups.search({}))
  []

Identifying groups
------------------

The function, `setGroupsForPrincipal`, is a subscriber to
principal-creation events.  It adds any group-folder-defined groups to
users in those groups:

  >>> principal = principals.getPrincipal('p1')
  >>> principal.groups
  [u'group.G1', u'group.GA']

Of course, this applies to groups too:

  >>> principal = principals.getPrincipal('group.G1')
  >>> principal.groups
  [u'group.G2']

In addition to setting principal groups, the `setGroupsForPrincipal`
function also declares the `IGroup` interface on groups:

  >>> [iface.__name__ for iface in interface.providedBy(principal)]
  ['IGroup', 'IPrincipal']
  
  >>> [iface.__name__ 
  ...  for iface in interface.providedBy(principals.getPrincipal('p1'))]
  ['IPrincipal']
