=============
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
  >>> from zope.app.security.interfaces import PrincipalLookupError
  >>> from zope.security.interfaces import IGroupAwarePrincipal
  >>> from zope.app.authentication.groupfolder import setGroupsForPrincipal

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

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

  >>> from zope.app.authentication import principalfolder

  >>> class Principals:
  ...
  ...     interface.implements(IAuthentication)
  ...
  ...     def __init__(self, groups, prefix='auth.'):
  ...         self.prefix = prefix
  ...         self.principals = {
  ...            'p1': principalfolder.PrincipalInfo('p1', '', '', ''),
  ...            'p2': principalfolder.PrincipalInfo('p2', '', '', ''),
  ...            }
  ...         self.groups = groups
  ...
  ...     def getPrincipal(self, id):
  ...         if not id.startswith(self.prefix):
  ...             raise PrincipalLookupError(id)
  ...         id = id[len(self.prefix):]
  ...         info = self.principals.get(id)
  ...         if info is None:
  ...             info = self.groups.principalInfo(id)
  ...             if info is None:
  ...                raise PrincipalLookupError(id)
  ...         principal = Principal(self.prefix+info.id, 
  ...                               info.title, info.description)
  ...         setGroupsForPrincipal(PrincipalCreatedEvent(self, principal))
  ...         return principal

This class doesn't really implement the full `IAuthentication` 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
  >>> from zope.app.authentication.interfaces import IAuthenticatorPlugin
  >>> ztapi.provideUtility(IAuthenticatorPlugin, groups)

We will create and register a new principals utility:

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

Now we can set the principals on the group:

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

This allows us to look up groups for the principals:

  >>> groups.getGroupsForPrincipal('auth.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('auth.p1')
  ()

but the principal information on the group is unchanged:

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

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

  >>> groups['G1'] = g1

  >>> groups.getGroupsForPrincipal('auth.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 = ['auth.group.G1']

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

Groups cannot contain cycles:

  >>> g1.principals = ('auth.p1', 'auth.p2', 'auth.group.G2')
  ... # doctest: +NORMALIZE_WHITESPACE
  Traceback (most recent call last):
  ...
  GroupCycle: (u'auth.group.G1', 
               ['auth.p2', u'auth.group.G1', u'auth.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 = ['auth.group.GA']

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

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

  >>> ga.principals = ['auth.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('auth.p1')

  >>> principal.groups
  [u'auth.group.G1', u'auth.group.GA']

Of course, this applies to groups too:

  >>> principal = principals.getPrincipal('auth.group.G1')
  >>> principal.id
  'auth.group.G1'

  >>> principal.groups
  [u'auth.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', 'IGroupAwarePrincipal']

  >>> [iface.__name__
  ...  for iface in interface.providedBy(principals.getPrincipal('auth.p1'))]
  ['IGroupAwarePrincipal']

Special groups
--------------
Two special groups, Authenticated, and Everyone may apply to users
created by the pluggable-authentication utility.  There is a
subscriber, specialGroups, that will set these groups on any non-group
principals if IAuthenticatedGroup, or IEveryoneGroup utilities are
provided.

Lets define a group-aware principal:

  >>> import zope.security.interfaces
  >>> class GroupAwarePrincipal(Principal):
  ...     interface.implements(zope.security.interfaces.IGroupAwarePrincipal)
  ...     def __init__(self, id):
  ...         Principal.__init__(self, id)
  ...         self.groups = []

If we notify the subscriber with this principal, nothing will happen
because the groups haven't been defined:

  >>> prin = GroupAwarePrincipal('x')
  >>> event = interfaces.FoundPrincipalCreated(42, prin, {})
  >>> zope.app.authentication.groupfolder.specialGroups(event)
  >>> prin.groups
  []

Now, if we define the Everybody group:

  >>> import zope.app.security.interfaces
  >>> class EverybodyGroup(Principal):
  ...     interface.implements(zope.app.security.interfaces.IEveryoneGroup)

  >>> everybody = EverybodyGroup('all')
  >>> ztapi.provideUtility(zope.app.security.interfaces.IEveryoneGroup,
  ...                      everybody)

Then the group will be added to the principal:

  >>> zope.app.authentication.groupfolder.specialGroups(event)
  >>> prin.groups
  ['all']

Similarly for the authenticated group:

  >>> class AuthenticatedGroup(Principal):
  ...     interface.implements(
  ...         zope.app.security.interfaces.IAuthenticatedGroup)

  >>> authenticated = AuthenticatedGroup('auth')
  >>> ztapi.provideUtility(zope.app.security.interfaces.IAuthenticatedGroup,
  ...                      authenticated)

Then the group will be added to the principal:

  >>> prin.groups = []
  >>> zope.app.authentication.groupfolder.specialGroups(event)
  >>> prin.groups.sort()
  >>> prin.groups
  ['all', 'auth']

These groups are only added to non-group principals:

  >>> prin.groups = []
  >>> interface.directlyProvides(prin, zope.security.interfaces.IGroup)
  >>> zope.app.authentication.groupfolder.specialGroups(event)
  >>> prin.groups
  []

And they are only added to group aware principals:

  >>> class SolitaryPrincipal:
  ...     interface.implements(zope.security.interfaces.IPrincipal)
  ...     id = title = description = ''

  >>> event = interfaces.FoundPrincipalCreated(42, SolitaryPrincipal(), {})
  >>> zope.app.authentication.groupfolder.specialGroups(event)
  >>> prin.groups
  []

Limitation
==========

The current group-folder design has an important limitation!

There is no point in assigning principals to a group 
from a group folder unless the principal is from the same pluggable
authentication utility.

o If a principal is from a higher authentication utility, the user
  will not get the group definition. Why? Because the principals
  group assignments are set when the principal is authenticated. At
  that point, the current site is the site containing the principal
  definition. Groups defined in lower sites will not be consulted,

o It is impossible to assign users from lower authentication
  utilities because they can't be seen when managing the group,
  from the site cntaining the group.

A better design might be to store user-role assignments independent of
the group definitions and to look for assignments during (url)
traversal.  This could get quite complex though.

While it is possible to have multiple authentication utilities long a
URL path, it is generally better to stick to a simpler model in which
there is only one authentication utility along a URL path (in addition
to the global utility, which is used for bootstrapping purposes).
