zope.pluggableauth-1.3/ 0000755 0001750 0001750 00000000000 11524202367 014241 5 ustar jw jw 0000000 0000000 zope.pluggableauth-1.3/CHANGES.txt 0000644 0001750 0001750 00000003133 11524202361 016044 0 ustar jw jw 0000000 0000000 =======
Changes
=======
1.3 (2011-02-08)
----------------
- As the camefrom information is most probably used for a redirect, require
it to be an absolute URL (see also
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30).
1.2 (2010-12-16)
----------------
- SessionCredentialsPlugin has a hook (_makeCredentials) that can be overriden
in subclasses to store the credentials in the session differently.
For example, you could use keas.kmi and encrypt the passwords of the
currently logged-in users so they don't appear in plain text in the ZODB.
1.1 (2010-10-18)
----------------
* Moved concrete IAuthenticatorPlugin implementations from
zope.app.authentication to zope.pluggableauth.plugins.
As a result projects that want to use the IAuthenticator plugins (previously
found in zope.app.authentication) do not automatically also pull in the
zope.app.* dependencies that are needed to register the ZMI views.
1.0.3 (2010-07-09)
------------------
* Fixed dependency declaration.
1.0.2 (2010-07-90)
------------------
* Added persistent.Persistent and zope.container.contained.Contained as
bases zope.pluggableauth.plugins.session.SessionCredentialsPlugin, so
instances of zope.app.authentication.session.SessionCredentialsPlugin
won't be changed.
(https://mail.zope.org/pipermail/zope-dev/2010-July/040898.html)
1.0.1 (2010-02-11)
------------------
* Adapters are now declared in a new ZCML file :
`principalfactories.zcml`. This avoids duplication errors in
``zope.app.authentication``.
1.0 (2010-02-05)
----------------
* Splitting off from zope.app.authentication
zope.pluggableauth-1.3/setup.cfg 0000644 0001750 0001750 00000000073 11524202367 016062 0 ustar jw jw 0000000 0000000 [egg_info]
tag_build =
tag_date = 0
tag_svn_revision = 0
zope.pluggableauth-1.3/LICENSE.txt 0000644 0001750 0001750 00000004026 11524202361 016060 0 ustar jw jw 0000000 0000000 Zope Public License (ZPL) Version 2.1
A copyright notice accompanies this license document that identifies the
copyright holders.
This license has been certified as open source. It has also been designated as
GPL compatible by the Free Software Foundation (FSF).
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions in source code must retain the accompanying copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the accompanying copyright
notice, this list of conditions, and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Names of the copyright holders must not be used to endorse or promote
products derived from this software without prior written permission from the
copyright holders.
4. The right to distribute this software or to use it for any purpose does not
give you the right to use Servicemarks (sm) or Trademarks (tm) of the
copyright
holders. Use of them is covered by separate agreement with the copyright
holders.
5. If any files are modified, you must cause the modified files to carry
prominent notices stating that you changed the files and the date of any
change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zope.pluggableauth-1.3/setup.py 0000644 0001750 0001750 00000005475 11524202361 015760 0 ustar jw jw 0000000 0000000 ##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
##############################################################################
# This package is developed by the Zope Toolkit project, documented here:
# http://docs.zope.org/zopetoolkit
# When developing and releasing this package, please follow the documented
# Zope Toolkit policies as described by this documentation.
##############################################################################
"""Pluggable Authentication Utility
"""
import os
from setuptools import setup, find_packages
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
setup(name='zope.pluggableauth',
version='1.3',
author='Zope Foundation and Contributors',
author_email='zope-dev@zope.org',
description='Pluggable Authentication Utility',
long_description= "\n".join((
read('README.txt'),
'.. contents::\n\n',
read('CHANGES.txt'),
read('src', 'zope', 'pluggableauth', 'README.txt'),
)),
url='http://pypi.python.org/pypi/zope.pluggableauth',
license='ZPL 2.1',
keywords='zope3 ztk authentication pluggable',
packages=find_packages('src'),
package_dir = {'': 'src'},
namespace_packages=['zope'],
include_package_data = True,
zip_safe = False,
extras_require=dict(test=['zope.component[test]']),
install_requires=[
'ZODB3',
'setuptools',
'zope.authentication',
'zope.component',
'zope.container',
'zope.event',
'zope.i18nmessageid',
'zope.interface',
'zope.password >= 3.5.1',
'zope.publisher>=3.12',
'zope.schema',
'zope.security',
'zope.session',
'zope.site',
'zope.traversing',
],
classifiers = [
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: Zope Public License',
'Programming Language :: Python',
'Natural Language :: English',
'Operating System :: OS Independent',
'Topic :: Internet :: WWW/HTTP',
'Framework :: Zope3'],
)
zope.pluggableauth-1.3/bootstrap.py 0000644 0001750 0001750 00000003302 11524202361 016620 0 ustar jw jw 0000000 0000000 ##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Bootstrap a buildout-based project
Simply run this script in a directory containing a buildout.cfg.
The script accepts buildout command-line options, so you can
use the -c option to specify an alternate configuration file.
"""
import os, shutil, sys, tempfile, urllib2
tmpeggs = tempfile.mkdtemp()
ez = {}
exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0)
import pkg_resources
cmd = 'from setuptools.command.easy_install import main; main()'
if sys.platform == 'win32':
cmd = '"%s"' % cmd # work around spawn lamosity on windows
ws = pkg_resources.working_set
assert os.spawnle(
os.P_WAIT, sys.executable, sys.executable,
'-c', cmd, '-mqNxd', tmpeggs, 'zc.buildout',
dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse('setuptools')).location
),
) == 0
ws.add_entry(tmpeggs)
ws.require('zc.buildout')
import zc.buildout.buildout
zc.buildout.buildout.main(sys.argv[1:] + ['bootstrap'])
shutil.rmtree(tmpeggs)
zope.pluggableauth-1.3/README.txt 0000644 0001750 0001750 00000000333 11524202361 015730 0 ustar jw jw 0000000 0000000 ==========================
Pluggable Authentication
==========================
Based on zope.authentication, this package provides a flexible and
pluggable authentication utility. Several common plugins are provided.
zope.pluggableauth-1.3/src/ 0000755 0001750 0001750 00000000000 11524202367 015030 5 ustar jw jw 0000000 0000000 zope.pluggableauth-1.3/src/zope.pluggableauth.egg-info/ 0000755 0001750 0001750 00000000000 11524202367 022322 5 ustar jw jw 0000000 0000000 zope.pluggableauth-1.3/src/zope.pluggableauth.egg-info/namespace_packages.txt 0000644 0001750 0001750 00000000005 11524202364 026645 0 ustar jw jw 0000000 0000000 zope
zope.pluggableauth-1.3/src/zope.pluggableauth.egg-info/SOURCES.txt 0000644 0001750 0001750 00000002707 11524202364 024211 0 ustar jw jw 0000000 0000000 CHANGES.txt
COPYRIGHT.txt
LICENSE.txt
README.txt
ZPL.txt
bootstrap.py
buildout.cfg
setup.py
src/zope/__init__.py
src/zope.pluggableauth.egg-info/PKG-INFO
src/zope.pluggableauth.egg-info/SOURCES.txt
src/zope.pluggableauth.egg-info/dependency_links.txt
src/zope.pluggableauth.egg-info/namespace_packages.txt
src/zope.pluggableauth.egg-info/not-zip-safe
src/zope.pluggableauth.egg-info/requires.txt
src/zope.pluggableauth.egg-info/top_level.txt
src/zope/pluggableauth/README.txt
src/zope/pluggableauth/__init__.py
src/zope/pluggableauth/authentication.py
src/zope/pluggableauth/configure.zcml
src/zope/pluggableauth/factories.py
src/zope/pluggableauth/interfaces.py
src/zope/pluggableauth/principalfactories.zcml
src/zope/pluggableauth/tests.py
src/zope/pluggableauth/plugins/__init__.py
src/zope/pluggableauth/plugins/ftpplugins.py
src/zope/pluggableauth/plugins/ftpplugins.zcml
src/zope/pluggableauth/plugins/generic.py
src/zope/pluggableauth/plugins/generic.zcml
src/zope/pluggableauth/plugins/groupfolder.py
src/zope/pluggableauth/plugins/groupfolder.txt
src/zope/pluggableauth/plugins/groupfolder.zcml
src/zope/pluggableauth/plugins/httpplugins.py
src/zope/pluggableauth/plugins/httpplugins.zcml
src/zope/pluggableauth/plugins/idpicker.py
src/zope/pluggableauth/plugins/principalfolder.py
src/zope/pluggableauth/plugins/principalfolder.txt
src/zope/pluggableauth/plugins/principalfolder.zcml
src/zope/pluggableauth/plugins/session.py
src/zope/pluggableauth/plugins/session.zcml zope.pluggableauth-1.3/src/zope.pluggableauth.egg-info/dependency_links.txt 0000644 0001750 0001750 00000000001 11524202364 026365 0 ustar jw jw 0000000 0000000
zope.pluggableauth-1.3/src/zope.pluggableauth.egg-info/not-zip-safe 0000644 0001750 0001750 00000000001 11524202361 024542 0 ustar jw jw 0000000 0000000
zope.pluggableauth-1.3/src/zope.pluggableauth.egg-info/requires.txt 0000644 0001750 0001750 00000000371 11524202364 024720 0 ustar jw jw 0000000 0000000 ZODB3
setuptools
zope.authentication
zope.component
zope.container
zope.event
zope.i18nmessageid
zope.interface
zope.password >= 3.5.1
zope.publisher>=3.12
zope.schema
zope.security
zope.session
zope.site
zope.traversing
[test]
zope.component[test] zope.pluggableauth-1.3/src/zope.pluggableauth.egg-info/top_level.txt 0000644 0001750 0001750 00000000005 11524202364 025044 0 ustar jw jw 0000000 0000000 zope
zope.pluggableauth-1.3/src/zope.pluggableauth.egg-info/PKG-INFO 0000644 0001750 0001750 00000062154 11524202364 023424 0 ustar jw jw 0000000 0000000 Metadata-Version: 1.0
Name: zope.pluggableauth
Version: 1.3
Summary: Pluggable Authentication Utility
Home-page: http://pypi.python.org/pypi/zope.pluggableauth
Author: Zope Foundation and Contributors
Author-email: zope-dev@zope.org
License: ZPL 2.1
Description: ==========================
Pluggable Authentication
==========================
Based on zope.authentication, this package provides a flexible and
pluggable authentication utility. Several common plugins are provided.
.. contents::
=======
Changes
=======
1.3 (2011-02-08)
----------------
- As the camefrom information is most probably used for a redirect, require
it to be an absolute URL (see also
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30).
1.2 (2010-12-16)
----------------
- SessionCredentialsPlugin has a hook (_makeCredentials) that can be overriden
in subclasses to store the credentials in the session differently.
For example, you could use keas.kmi and encrypt the passwords of the
currently logged-in users so they don't appear in plain text in the ZODB.
1.1 (2010-10-18)
----------------
* Moved concrete IAuthenticatorPlugin implementations from
zope.app.authentication to zope.pluggableauth.plugins.
As a result projects that want to use the IAuthenticator plugins (previously
found in zope.app.authentication) do not automatically also pull in the
zope.app.* dependencies that are needed to register the ZMI views.
1.0.3 (2010-07-09)
------------------
* Fixed dependency declaration.
1.0.2 (2010-07-90)
------------------
* Added persistent.Persistent and zope.container.contained.Contained as
bases zope.pluggableauth.plugins.session.SessionCredentialsPlugin, so
instances of zope.app.authentication.session.SessionCredentialsPlugin
won't be changed.
(https://mail.zope.org/pipermail/zope-dev/2010-July/040898.html)
1.0.1 (2010-02-11)
------------------
* Adapters are now declared in a new ZCML file :
`principalfactories.zcml`. This avoids duplication errors in
``zope.app.authentication``.
1.0 (2010-02-05)
----------------
* Splitting off from zope.app.authentication
================================
Pluggable-Authentication Utility
================================
The Pluggable-Authentication Utility (PAU) provides a framework for
authenticating principals and associating information with them. It uses
plugins and subscribers to get its work done.
For a pluggable-authentication utility to be used, it should be
registered as a utility providing the
`zope.authentication.interfaces.IAuthentication` interface.
Authentication
--------------
The primary job of PAU is to authenticate principals. It uses two types of
plug-ins in its work:
- Credentials Plugins
- Authenticator Plugins
Credentials 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 PAU returns a principal object, if it can. The PAU
does this by first iterateing 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 PAU
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.
Simple Credentials Plugin
~~~~~~~~~~~~~~~~~~~~~~~~~
To illustrate, we'll create a simple credentials plugin::
>>> from zope import interface
>>> from zope.pluggableauth.authentication import interfaces
>>> class MyCredentialsPlugin(object):
...
... interface.implements(interfaces.ICredentialsPlugin)
...
... def extractCredentials(self, request):
... return request.get('credentials')
...
... 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 plugin
As a plugin, MyCredentialsPlugin needs to be registered as a named utility::
>>> myCredentialsPlugin = MyCredentialsPlugin()
>>> provideUtility(myCredentialsPlugin, name='My Credentials Plugin')
Simple Authenticator Plugin
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Next we'll create a simple authenticator plugin. For our plugin, we'll need
an implementation of IPrincipalInfo::
>>> class PrincipalInfo(object):
...
... interface.implements(interfaces.IPrincipalInfo)
...
... def __init__(self, id, title, description):
... self.id = id
... self.title = title
... self.description = description
...
... def __repr__(self):
... return 'PrincipalInfo(%r)' % self.id
Our authenticator uses this type when it creates a principal info::
>>> class MyAuthenticatorPlugin(object):
...
... interface.implements(interfaces.IAuthenticatorPlugin)
...
... def authenticateCredentials(self, credentials):
... if credentials == 'secretcode':
... return PrincipalInfo('bob', 'Bob', '')
...
... def principalInfo(self, id):
... pass # plugin not currently supporting search
As with the credentials plugin, the authenticator plugin must be registered
as a named utility::
>>> myAuthenticatorPlugin = MyAuthenticatorPlugin()
>>> provideUtility(myAuthenticatorPlugin, name='My Authenticator Plugin')
Configuring a PAU
~~~~~~~~~~~~~~~~~
Finally, we'll create the PAU itself::
>>> from zope.pluggableauth import authentication
>>> pau = authentication.PluggableAuthentication('xyz_')
and configure it with the two plugins::
>>> pau.credentialsPlugins = ('My Credentials Plugin', )
>>> pau.authenticatorPlugins = ('My Authenticator Plugin', )
Using the PAU to Authenticate
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>>> from zope.pluggableauth.factories import AuthenticatedPrincipalFactory
>>> provideAdapter(AuthenticatedPrincipalFactory)
We can now use the PAU to authenticate a sample request::
>>> from zope.publisher.browser import TestRequest
>>> print pau.authenticate(TestRequest())
None
In 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::
>>> print pau.authenticate(TestRequest(credentials='let me in!'))
None
However, if we provide the proper credentials::
>>> request = TestRequest(credentials='secretcode')
>>> principal = pau.authenticate(request)
>>> principal
Principal('xyz_bob')
we get an authenticated principal.
Multiple Authenticator Plugins
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The PAU works with multiple authenticator plugins. It uses each plugin, in the
order specified in the PAU's authenticatorPlugins attribute, to authenticate
a set of credentials.
To illustrate, we'll create another authenticator::
>>> class MyAuthenticatorPlugin2(MyAuthenticatorPlugin):
...
... def authenticateCredentials(self, credentials):
... if credentials == 'secretcode':
... return PrincipalInfo('black', 'Black Spy', '')
... elif credentials == 'hiddenkey':
... return PrincipalInfo('white', 'White Spy', '')
>>> provideUtility(MyAuthenticatorPlugin2(), name='My Authenticator Plugin 2')
If we put it before the original authenticator::
>>> pau.authenticatorPlugins = (
... 'My Authenticator Plugin 2',
... 'My Authenticator Plugin')
Then it will be given the first opportunity to authenticate a request::
>>> pau.authenticate(TestRequest(credentials='secretcode'))
Principal('xyz_black')
If neither plugins can authenticate, pau returns None::
>>> print pau.authenticate(TestRequest(credentials='let me in!!'))
None
When we change the order of the authenticator plugins::
>>> pau.authenticatorPlugins = (
... 'My Authenticator Plugin',
... 'My Authenticator Plugin 2')
we see that our original plugin is now acting first::
>>> pau.authenticate(TestRequest(credentials='secretcode'))
Principal('xyz_bob')
The second plugin, however, gets a chance to authenticate if first does not::
>>> pau.authenticate(TestRequest(credentials='hiddenkey'))
Principal('xyz_white')
Multiple Credentials Plugins
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As with with authenticators, we can specify multiple credentials plugins. To
illustrate, we'll create a credentials plugin that extracts credentials from
a request form::
>>> class FormCredentialsPlugin:
...
... interface.implements(interfaces.ICredentialsPlugin)
...
... def extractCredentials(self, request):
... return request.form.get('my_credentials')
...
... def challenge(self, request):
... pass
...
... def logout(request):
... pass
>>> provideUtility(FormCredentialsPlugin(),
... name='Form Credentials Plugin')
and insert the new credentials plugin before the existing plugin::
>>> pau.credentialsPlugins = (
... 'Form Credentials Plugin',
... 'My Credentials Plugin')
The PAU will use each plugin in order to try and obtain credentials from a
request::
>>> pau.authenticate(TestRequest(credentials='secretcode',
... form={'my_credentials': 'hiddenkey'}))
Principal('xyz_white')
In this case, the first credentials plugin succeeded in getting credentials
from the form and the second authenticator was able to authenticate the
credentials. Specifically, the PAU went through these steps:
- Get credentials using 'Form Credentials Plugin'
- Got 'hiddenkey' credentials using 'Form Credentials Plugin', try to
authenticate using 'My Authenticator Plugin'
- Failed to authenticate 'hiddenkey' with 'My Authenticator Plugin', try
'My Authenticator Plugin 2'
- Succeeded in authenticating with 'My Authenticator Plugin 2'
Let's try a different scenario::
>>> pau.authenticate(TestRequest(credentials='secretcode'))
Principal('xyz_bob')
In this case, the PAU went through these steps::
- Get credentials using 'Form Credentials Plugin'
- Failed to get credentials using 'Form Credentials Plugin', try
'My Credentials Plugin'
- Got 'scecretcode' credentials using 'My Credentials Plugin', try to
authenticate using 'My Authenticator Plugin'
- Succeeded in authenticating with 'My Authenticator Plugin'
Let's try a slightly more complex scenario::
>>> pau.authenticate(TestRequest(credentials='hiddenkey',
... form={'my_credentials': 'bogusvalue'}))
Principal('xyz_white')
This highlights PAU's ability to use multiple plugins for authentication:
- Get credentials using 'Form Credentials Plugin'
- Got 'bogusvalue' credentials using 'Form Credentials Plugin', try to
authenticate using 'My Authenticator Plugin'
- Failed to authenticate 'boguskey' with 'My Authenticator Plugin', try
'My Authenticator Plugin 2'
- Failed to authenticate 'boguskey' with 'My Authenticator Plugin 2' --
there are no more authenticators to try, so lets try the next credentials
plugin for some new credentials
- Get credentials using 'My Credentials Plugin'
- Got 'hiddenkey' credentials using 'My Credentials Plugin', try to
authenticate using 'My Authenticator Plugin'
- Failed to authenticate 'hiddenkey' using 'My Authenticator Plugin', try
'My Authenticator Plugin 2'
- Succeeded in authenticating with 'My Authenticator Plugin 2' (shouts and
cheers!)
Multiple Authenticator Plugins
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As with the other operations we've seen, the PAU uses multiple plugins to
find a principal. If the first authenticator plugin can't find the requested
principal, the next plugin is used, and so on.
>>> class AnotherAuthenticatorPlugin:
...
... interface.implements(interfaces.IAuthenticatorPlugin)
...
... def __init__(self):
... self.infos = {}
... self.ids = {}
...
... def principalInfo(self, id):
... return self.infos.get(id)
...
... def authenticateCredentials(self, credentials):
... id = self.ids.get(credentials)
... if id is not None:
... return self.infos[id]
...
... def add(self, id, title, description, credentials):
... self.infos[id] = PrincipalInfo(id, title, description)
... self.ids[credentials] = id
To illustrate, we'll create and register two authenticators::
>>> authenticator1 = AnotherAuthenticatorPlugin()
>>> provideUtility(authenticator1, name='Authentication Plugin 1')
>>> authenticator2 = AnotherAuthenticatorPlugin()
>>> provideUtility(authenticator2, name='Authentication Plugin 2')
and add a principal to them::
>>> authenticator1.add('bob', 'Bob', 'A nice guy', 'b0b')
>>> authenticator1.add('white', 'White Spy', 'Sneaky', 'deathtoblack')
>>> authenticator2.add('black', 'Black Spy', 'Also sneaky', 'deathtowhite')
When we configure the PAU to use both searchable authenticators (note the
order)::
>>> pau.authenticatorPlugins = (
... 'Authentication Plugin 2',
... 'Authentication Plugin 1')
we register the factories for our principals::
>>> from zope.pluggableauth.factories import FoundPrincipalFactory
>>> provideAdapter(FoundPrincipalFactory)
we see how the PAU uses both plugins::
>>> pau.getPrincipal('xyz_white')
Principal('xyz_white')
>>> pau.getPrincipal('xyz_black')
Principal('xyz_black')
If more than one plugin know about the same principal ID, the first plugin is
used and the remaining are not delegated to. To illustrate, we'll add
another principal with the same ID as an existing principal::
>>> authenticator2.add('white', 'White Rider', '', 'r1der')
>>> pau.getPrincipal('xyz_white').title
'White Rider'
If we change the order of the plugins::
>>> pau.authenticatorPlugins = (
... 'Authentication Plugin 1',
... 'Authentication Plugin 2')
we get a different principal for ID 'white'::
>>> pau.getPrincipal('xyz_white').title
'White Spy'
Issuing a Challenge
-------------------
Part of PAU's IAuthentication contract is to challenge the user for
credentials when its 'unauthorized' method is called. The need for this
functionality is driven by the following use case:
- A user attempts to perform an operation he is not authorized to perform.
- A handler responds to the unauthorized error by calling IAuthentication
'unauthorized'.
- The authentication component (in our case, a PAU) issues a challenge to
the user to collect new credentials (typically in the form of logging in
as a new user).
The PAU handles the credentials challenge by delegating to its credentials
plugins.
Currently, the PAU is configured with the credentials plugins that don't
perform any action when asked to challenge (see above the 'challenge' methods).
To illustrate challenges, we'll subclass an existing credentials plugin and
do something in its 'challenge'::
>>> class LoginFormCredentialsPlugin(FormCredentialsPlugin):
...
... def __init__(self, loginForm):
... self.loginForm = loginForm
...
... def challenge(self, request):
... request.response.redirect(self.loginForm)
... return True
This plugin handles a challenge by redirecting the response to a login form.
It returns True to signal to the PAU that it handled the challenge.
We will now create and register a couple of these plugins::
>>> provideUtility(LoginFormCredentialsPlugin('simplelogin.html'),
... name='Simple Login Form Plugin')
>>> provideUtility(LoginFormCredentialsPlugin('advancedlogin.html'),
... name='Advanced Login Form Plugin')
and configure the PAU to use them::
>>> pau.credentialsPlugins = (
... 'Simple Login Form Plugin',
... 'Advanced Login Form Plugin')
Now when we call 'unauthorized' on the PAU::
>>> request = TestRequest()
>>> pau.unauthorized(id=None, request=request)
we see that the user is redirected to the simple login form::
>>> request.response.getStatus()
302
>>> request.response.getHeader('location')
'simplelogin.html'
We can change the challenge policy by reordering the plugins::
>>> pau.credentialsPlugins = (
... 'Advanced Login Form Plugin',
... 'Simple Login Form Plugin')
Now when we call 'unauthorized'::
>>> request = TestRequest()
>>> pau.unauthorized(id=None, request=request)
the advanced plugin is used because it's first::
>>> request.response.getStatus()
302
>>> request.response.getHeader('location')
'advancedlogin.html'
Challenge Protocols
~~~~~~~~~~~~~~~~~~~
Sometimes, we want multiple challengers to work together. For example, the
HTTP specification allows multiple challenges to be issued in a response. A
challenge plugin can provide a `challengeProtocol` attribute that effectively
groups related plugins together for challenging. If a plugin returns `True`
from its challenge and provides a non-None challengeProtocol, subsequent
plugins in the credentialsPlugins list that have the same challenge protocol
will also be used to challenge.
Without a challengeProtocol, only the first plugin to succeed in a challenge
will be used.
Let's look at an example. We'll define a new plugin that specifies an
'X-Challenge' protocol::
>>> class XChallengeCredentialsPlugin(FormCredentialsPlugin):
...
... challengeProtocol = 'X-Challenge'
...
... def __init__(self, challengeValue):
... self.challengeValue = challengeValue
...
... def challenge(self, request):
... value = self.challengeValue
... existing = request.response.getHeader('X-Challenge', '')
... if existing:
... value += ' ' + existing
... request.response.setHeader('X-Challenge', value)
... return True
and register a couple instances as utilities::
>>> provideUtility(XChallengeCredentialsPlugin('basic'),
... name='Basic X-Challenge Plugin')
>>> provideUtility(XChallengeCredentialsPlugin('advanced'),
... name='Advanced X-Challenge Plugin')
When we use both plugins with the PAU::
>>> pau.credentialsPlugins = (
... 'Basic X-Challenge Plugin',
... 'Advanced X-Challenge Plugin')
and call 'unauthorized'::
>>> request = TestRequest()
>>> pau.unauthorized(None, request)
we see that both plugins participate in the challange, rather than just the
first plugin::
>>> request.response.getHeader('X-Challenge')
'advanced basic'
Pluggable-Authentication Prefixes
---------------------------------
Principal ids are required to be unique system wide. Plugins will often provide
options for providing id prefixes, so that different sets of plugins provide
unique ids within a PAU. If there are multiple pluggable-authentication
utilities in a system, it's a good idea to give each PAU a unique prefix, so
that principal ids from different PAUs don't conflict. We can provide a prefix
when a PAU is created::
>>> pau = authentication.PluggableAuthentication('mypau_')
>>> pau.credentialsPlugins = ('My Credentials Plugin', )
>>> pau.authenticatorPlugins = ('My Authenticator Plugin', )
When we create a request and try to authenticate::
>>> pau.authenticate(TestRequest(credentials='secretcode'))
Principal('mypau_bob')
Note that now, our principal's id has the pluggable-authentication
utility prefix.
We can still lookup a principal, as long as we supply the prefix::
>> pau.getPrincipal('mypas_42')
Principal('mypas_42', "{'domain': 42}")
>> pau.getPrincipal('mypas_41')
OddPrincipal('mypas_41', "{'int': 41}")
Keywords: zope3 ztk authentication pluggable
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Web Environment
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Zope Public License
Classifier: Programming Language :: Python
Classifier: Natural Language :: English
Classifier: Operating System :: OS Independent
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Framework :: Zope3
zope.pluggableauth-1.3/src/zope/ 0000755 0001750 0001750 00000000000 11524202367 016005 5 ustar jw jw 0000000 0000000 zope.pluggableauth-1.3/src/zope/pluggableauth/ 0000755 0001750 0001750 00000000000 11524202367 020631 5 ustar jw jw 0000000 0000000 zope.pluggableauth-1.3/src/zope/pluggableauth/plugins/ 0000755 0001750 0001750 00000000000 11524202367 022312 5 ustar jw jw 0000000 0000000 zope.pluggableauth-1.3/src/zope/pluggableauth/plugins/ftpplugins.zcml 0000644 0001750 0001750 00000000402 11524202361 025362 0 ustar jw jw 0000000 0000000
zope.pluggableauth-1.3/src/zope/pluggableauth/plugins/session.zcml 0000644 0001750 0001750 00000000407 11524202361 024657 0 ustar jw jw 0000000 0000000
zope.pluggableauth-1.3/src/zope/pluggableauth/plugins/groupfolder.zcml 0000644 0001750 0001750 00000001034 11524202361 025521 0 ustar jw jw 0000000 0000000
zope.pluggableauth-1.3/src/zope/pluggableauth/plugins/generic.py 0000644 0001750 0001750 00000006260 11524202361 024276 0 ustar jw jw 0000000 0000000 ##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Generic PAS Plugins
"""
__docformat__ = "reStructuredText"
from zope.authentication.interfaces import IUnauthenticatedPrincipal
from zope.interface import implements
from zope.pluggableauth import interfaces
class NoChallengeCredentialsPlugin(object):
"""A plugin that doesn't challenge if the principal is authenticated.
There are two reasonable ways to handle an unauthorized error for an
authenticated principal:
- Inform the user of the unauthorized error
- Let the user login with a different set of credentials
Since either approach is reasonable, we need to give the site manager
some way of specifying one of the two policies.
By default, a user will be challenged for a new set of credentials if
unauthorized. A site manager can insert this plugin in the front of the
plugin list to prevent that challenge from occurring. This will
typically result in an 'Unauthorized' message to the user.
The 'challenge' behavior of the plugin is simple. To illustrate, we'll
create a plugin:
>>> challenger = NoChallengeCredentialsPlugin()
and a test request with an authenticated principal:
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> IUnauthenticatedPrincipal.providedBy(request.principal)
False
When we challenge using the plugin:
>>> challenger.challenge(request)
True
we get a value that signals the PAU that this plugin successfully
challenged the user (even though it actually did nothing). The PAU
will stop trying to challenge and the user will not get a chance to
provide different credentials. The result is typically an error message.
On the other hand, if the user is unauthenticated:
>>> class Principal(object):
... implements(IUnauthenticatedPrincipal)
>>> request.setPrincipal(Principal())
>>> IUnauthenticatedPrincipal.providedBy(request.principal)
True
the plugin challenge will return None:
>>> print challenger.challenge(request)
None
signaling the PAU that it should try the next plugin for a challenge. If
the PAU is configured properly, the user will receive a challenge and be
allowed to provide different credentials.
"""
implements(interfaces.ICredentialsPlugin)
def extractCredentials(self, request):
return None
def challenge(self, request):
if not IUnauthenticatedPrincipal.providedBy(request.principal):
return True
return None
def logout(self, request):
return False
zope.pluggableauth-1.3/src/zope/pluggableauth/plugins/groupfolder.txt 0000644 0001750 0001750 00000035317 11524202361 025406 0 ustar jw jw 0000000 0000000 =============
Group Folders
=============
Group folders provide support for groups information stored in the ZODB. They
are persistent, and must be contained within the PAUs that use them.
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.pluggableauth.plugins.groupfolder
>>> g1 = zope.pluggableauth.plugins.groupfolder.GroupInformation("Group 1")
>>> groups = zope.pluggableauth.plugins.groupfolder.GroupFolder('group.')
>>> groups['g1'] = g1
Note that when group-info is added, a GroupAdded event is generated:
>>> from zope.pluggableauth import interfaces
>>> from zope.component.eventtesting import getEvents
>>> getEvents(interfaces.IGroupAdded)
[]
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.authentication.interfaces import IAuthentication
>>> from zope.authentication.interfaces import PrincipalLookupError
>>> from zope.security.interfaces import IGroupAwarePrincipal
>>> from zope.pluggableauth.plugins.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.pluggableauth.plugins 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', '', '', ''),
... 'p3': principalfolder.PrincipalInfo('p3', '', '', ''),
... 'p4': principalfolder.PrincipalInfo('p4', '', '', ''),
... }
... self.groups = groups
... groups.__parent__ = self
...
... def getAuthenticatorPlugins(self):
... return [('principals', self.principals), ('groups', self.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.pluggableauth.interfaces import IAuthenticatorPlugin
>>> from zope.component import provideUtility
>>> provideUtility(groups, IAuthenticatorPlugin)
We will create and register a new principals utility:
>>> principals = Principals(groups)
>>> provideUtility(principals, IAuthentication)
Now we can set the principals on the group:
>>> g1.principals = ['auth.p1', 'auth.p2']
>>> g1.principals
('auth.p1', 'auth.p2')
Adding principals fires an event.
>>> getEvents(interfaces.IPrincipalsAddedToGroup)[-1]
We can now 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')
It also fires an event showing that the principals are removed from the group
(g1 is group information, not a zope.security.interfaces.IGroup).
>>> getEvents(interfaces.IPrincipalsRemovedFromGroup)[-1]
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.
An event is fired, as usual.
>>> getEvents(interfaces.IPrincipalsAddedToGroup)[-1]
In terms of member events (principals added and removed from groups), we have
now seen that events are fired when a group information object is added and
when it is removed from a group folder; and we have seen that events are fired
when a principal is added to an already-registered group. Events are also
fired when a principal is removed from an already-registered group. Let's
quickly see some more examples.
>>> g1.principals = ('auth.p1', 'auth.p3', 'auth.p4')
>>> getEvents(interfaces.IPrincipalsAddedToGroup)[-1]
>>> getEvents(interfaces.IPrincipalsRemovedFromGroup)[-1]
>>> g1.principals = ('auth.p1', 'auth.p2')
>>> getEvents(interfaces.IPrincipalsAddedToGroup)[-1]
>>> getEvents(interfaces.IPrincipalsRemovedFromGroup)[-1]
Groups can contain groups:
>>> g2 = zope.pluggableauth.plugins.groupfolder.GroupInformation("Group Two")
>>> groups['G2'] = g2
>>> g2.principals = ['auth.group.G1']
>>> groups.getGroupsForPrincipal('auth.group.G1')
(u'group.G2',)
>>> old = getEvents(interfaces.IPrincipalsAddedToGroup)[-1]
>>> old
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'])
Trying to do so does not fire an event.
>>> getEvents(interfaces.IPrincipalsAddedToGroup)[-1] is old
True
They need not be hierarchical:
>>> ga = zope.pluggableauth.plugins.groupfolder.GroupInformation("Group A")
>>> groups['GA'] = ga
>>> gb = zope.pluggableauth.plugins.groupfolder.GroupInformation("Group B")
>>> groups['GB'] = gb
>>> gb.principals = ['auth.group.GA']
>>> gc = zope.pluggableauth.plugins.groupfolder.GroupInformation("Group C")
>>> groups['GC'] = gc
>>> gc.principals = ['auth.group.GA']
>>> gd = zope.pluggableauth.plugins.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.pluggableauth.plugins.groupfolder.specialGroups(event)
>>> prin.groups
[]
Now, if we define the Everybody group:
>>> import zope.authentication.interfaces
>>> class EverybodyGroup(Principal):
... interface.implements(zope.authentication.interfaces.IEveryoneGroup)
>>> everybody = EverybodyGroup('all')
>>> provideUtility(everybody, zope.authentication.interfaces.IEveryoneGroup)
Then the group will be added to the principal:
>>> zope.pluggableauth.plugins.groupfolder.specialGroups(event)
>>> prin.groups
['all']
Similarly for the authenticated group:
>>> class AuthenticatedGroup(Principal):
... interface.implements(
... zope.authentication.interfaces.IAuthenticatedGroup)
>>> authenticated = AuthenticatedGroup('auth')
>>> provideUtility(authenticated, zope.authentication.interfaces.IAuthenticatedGroup)
Then the group will be added to the principal:
>>> prin.groups = []
>>> zope.pluggableauth.plugins.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.pluggableauth.plugins.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.pluggableauth.plugins.groupfolder.specialGroups(event)
>>> prin.groups
[]
Member-aware groups
-------------------
The groupfolder includes a subscriber that gives group principals the
zope.security.interfaces.IGroupAware interface and an implementation thereof.
This allows groups to be able to get and set their members.
Given an info object and a group...
>>> class DemoGroupInformation(object):
... interface.implements(
... zope.pluggableauth.plugins.groupfolder.IGroupInformation)
... def __init__(self, title, description, principals):
... self.title = title
... self.description = description
... self.principals = principals
...
>>> i = DemoGroupInformation(
... 'Managers', 'Taskmasters', ('joe', 'jane'))
...
>>> info = zope.pluggableauth.plugins.groupfolder.GroupInfo(
... 'groups.managers', i)
>>> class DummyGroup(object):
... interface.implements(IGroupAwarePrincipal)
... def __init__(self, id, title=u'', description=u''):
... self.id = id
... self.title = title
... self.description = description
... self.groups = []
...
>>> principal = DummyGroup('foo')
>>> zope.security.interfaces.IMemberAwareGroup.providedBy(principal)
False
...when you call the subscriber, it adds the two pseudo-methods to the
principal and makes the principal provide the IMemberAwareGroup interface.
>>> zope.pluggableauth.plugins.groupfolder.setMemberSubscriber(
... interfaces.FoundPrincipalCreated(
... 'dummy auth (ignored)', principal, info))
>>> principal.getMembers()
('joe', 'jane')
>>> principal.setMembers(('joe', 'jane', 'jaimie'))
>>> principal.getMembers()
('joe', 'jane', 'jaimie')
>>> zope.security.interfaces.IMemberAwareGroup.providedBy(principal)
True
The two methods work with the value on the IGroupInformation object.
>>> i.principals == principal.getMembers()
True
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 containing 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).
zope.pluggableauth-1.3/src/zope/pluggableauth/plugins/httpplugins.py 0000644 0001750 0001750 00000011024 11524202361 025235 0 ustar jw jw 0000000 0000000 ##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""PAS plugins related to HTTP
"""
__docformat__ = "reStructuredText"
import base64
from zope.interface import implements, Interface
from zope.publisher.interfaces.http import IHTTPRequest
from zope.schema import TextLine
from zope.pluggableauth import interfaces
class IHTTPBasicAuthRealm(Interface):
"""HTTP Basic Auth Realm
Represents the realm string that is used during basic HTTP authentication
"""
realm = TextLine(title=u'Realm',
description=u'HTTP Basic Authentication Realm',
required=True,
default=u'Zope')
class HTTPBasicAuthCredentialsPlugin(object):
implements(interfaces.ICredentialsPlugin, IHTTPBasicAuthRealm)
realm = 'Zope'
protocol = 'http auth'
def extractCredentials(self, request):
"""Extracts HTTP basic auth credentials from a request.
First we need to create a request that contains some credentials.
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest(
... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3'})
Now create the plugin and get the credentials.
>>> plugin = HTTPBasicAuthCredentialsPlugin()
>>> plugin.extractCredentials(request)
{'login': u'mgr', 'password': u'mgrpw'}
Make sure we return `None`, if no authentication header has been
specified.
>>> print plugin.extractCredentials(TestRequest())
None
Also, this plugin can *only* handle basic authentication.
>>> request = TestRequest(environ={'HTTP_AUTHORIZATION': 'foo bar'})
>>> print plugin.extractCredentials(TestRequest())
None
This plugin only works with HTTP requests.
>>> from zope.publisher.base import TestRequest
>>> print plugin.extractCredentials(TestRequest('/'))
None
"""
if not IHTTPRequest.providedBy(request):
return None
if request._auth:
if request._auth.lower().startswith(u'basic '):
credentials = request._auth.split()[-1]
login, password = base64.decodestring(credentials).split(':')
return {'login': login.decode('utf-8'),
'password': password.decode('utf-8')}
return None
def challenge(self, request):
"""Issues an HTTP basic auth challenge for credentials.
The challenge is issued by setting the appropriate response headers.
To illustrate, we'll create a plugin:
>>> plugin = HTTPBasicAuthCredentialsPlugin()
The plugin adds its challenge to the HTTP response.
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> response = request.response
>>> plugin.challenge(request)
True
>>> response._status
401
>>> response.getHeader('WWW-Authenticate', literal=True)
'basic realm="Zope"'
Notice that the realm is quoted, as per RFC 2617.
The plugin only works with HTTP requests.
>>> from zope.publisher.base import TestRequest
>>> request = TestRequest('/')
>>> response = request.response
>>> print plugin.challenge(request)
False
"""
if not IHTTPRequest.providedBy(request):
return False
request.response.setHeader("WWW-Authenticate",
'basic realm="%s"' % self.realm,
literal=True)
request.response.setStatus(401)
return True
def logout(self, request):
"""Always returns False as logout is not supported by basic auth.
>>> plugin = HTTPBasicAuthCredentialsPlugin()
>>> from zope.publisher.browser import TestRequest
>>> plugin.logout(TestRequest())
False
"""
return False
zope.pluggableauth-1.3/src/zope/pluggableauth/plugins/generic.zcml 0000644 0001750 0001750 00000000424 11524202361 024607 0 ustar jw jw 0000000 0000000