[Zope-CVS] CVS: Products/PluggableAuthService/plugins - InlineAuthHelper.py:1.2 HTTPBasicAuthHelper.py:1.7 CookieAuthHelper.py:1.8

Zachery Bir zbir at urbanape.com
Sat Oct 16 16:16:17 EDT 2004


Update of /cvs-repository/Products/PluggableAuthService/plugins
In directory cvs.zope.org:/tmp/cvs-serv25732/plugins

Modified Files:
	HTTPBasicAuthHelper.py CookieAuthHelper.py 
Added Files:
	InlineAuthHelper.py 
Log Message:
Merging pre-1_0_3-zbir-challenge-branch to the head.


=== Products/PluggableAuthService/plugins/InlineAuthHelper.py 1.1 => 1.2 ===
--- /dev/null	Sat Oct 16 16:16:17 2004
+++ Products/PluggableAuthService/plugins/InlineAuthHelper.py	Sat Oct 16 16:15:47 2004
@@ -0,0 +1,157 @@
+##############################################################################
+#
+# Copyright (c) 2001 Zope Corporation 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.
+#
+##############################################################################
+""" Class: CookieAuthHelper
+
+$Id$
+"""
+
+from base64 import encodestring, decodestring
+from urllib import quote
+
+from AccessControl.SecurityInfo import ClassSecurityInfo
+from OFS.Folder import Folder
+from App.class_init import default__class_init__ as InitializeClass
+from Products.PageTemplates.PageTemplateFile import PageTemplateFile
+from Products.PageTemplates.ZopePageTemplate import manage_addPageTemplate
+
+from Products.PluggableAuthService.plugins.BasePlugin import BasePlugin
+from Products.PluggableAuthService.interfaces.plugins import \
+        ILoginPasswordHostExtractionPlugin, IChallengePlugin,  \
+        ICredentialsUpdatePlugin, ICredentialsResetPlugin
+
+
+manage_addInlineAuthHelperForm = PageTemplateFile(
+    'www/iaAdd', globals(), __name__='manage_addInlineAuthHelperForm')
+
+
+def addInlineAuthHelper( dispatcher
+                       , id
+                       , title=None
+                       , REQUEST=None
+                       ):
+    """ Add an Inline Auth Helper to a Pluggable Auth Service. """
+    iah = InlineAuthHelper(id, title)
+    dispatcher._setObject(iah.getId(), iah)
+
+    if REQUEST is not None:
+        REQUEST['RESPONSE'].redirect( '%s/manage_workspace'
+                                      '?manage_tabs_message='
+                                      'InlineAuthHelper+added.'
+                                    % dispatcher.absolute_url() )
+
+
+class InlineAuthHelper(Folder, BasePlugin):
+    """ Multi-plugin for managing details of Inline Authentication. """
+    __implements__ = ( ILoginPasswordHostExtractionPlugin
+                     , IChallengePlugin
+                     )
+
+    meta_type = 'Inline Auth Helper'
+    security = ClassSecurityInfo()
+
+    _properties = ( { 'id'    : 'title'
+                    , 'label' : 'Title'
+                    , 'type'  : 'string'
+                    , 'mode'  : 'w'
+                    }
+                  )
+
+    manage_options = ( BasePlugin.manage_options[:1]
+                     + Folder.manage_options[:1]
+                     + Folder.manage_options[2:]
+                     )
+
+    def __init__(self, id, title=None):
+        self.id = self._id = id
+        self.title = title
+        self.body = BASIC_LOGIN_FORM
+
+    security.declarePrivate('extractCredentials')
+    def extractCredentials(self, request):
+        """ Extract credentials from cookie or 'request'. """
+        creds = {}
+
+        # Look in the request for the names coming from the login form
+        login = request.get('__ac_name', '')
+        password = request.get('__ac_password', '')
+
+        if login:
+            creds['login'] = login
+            creds['password'] = password
+
+        if creds:
+            creds['remote_host'] = request.get('REMOTE_HOST', '')
+
+            try:
+                creds['remote_address'] = request.getClientAddr()
+            except AttributeError:
+                creds['remote_address'] = request.get('REMOTE_ADDR', '')
+
+        return creds
+
+    security.declarePrivate('challenge')
+    def challenge(self, request, response, **kw):
+        """ Challenge the user for credentials. """
+        response.setStatus('200')
+        response.setBody(self.body)
+
+        # Keep HTTPResponse.exception() from further writing on the
+        # response body, without using HTTPResponse.write()
+        response._locked_status = True
+        response.setBody = self._setBody # Keep response.exception
+        return True
+
+    # Methods to override on response
+
+    def _setBody(self, body, *args, **kw):
+        pass
+
+InitializeClass(InlineAuthHelper)
+
+
+BASIC_LOGIN_FORM = """<html>
+  <head>
+    <title> Login Form </title>
+  </head>
+
+  <body>
+
+    <h3> Please log in </h3>
+
+    <form method="post">
+      <table cellpadding="2">
+        <tr>
+          <td><b>Login:</b> </td>
+          <td><input type="text" name="__ac_name" size="30" /></td>
+        </tr>
+        <tr>
+          <td><b>Password:</b></td>
+          <td><input type="password" name="__ac_password" size="30" /></td>
+        </tr>
+        <tr>
+          <td colspan="2">
+            <br />
+            <input type="submit" value=" Log In " />
+          </td>
+        </tr>
+      </table>
+
+    </form>
+
+  </body>
+
+</html>
+"""
+


=== Products/PluggableAuthService/plugins/HTTPBasicAuthHelper.py 1.6 => 1.7 ===
--- Products/PluggableAuthService/plugins/HTTPBasicAuthHelper.py:1.6	Fri Sep 24 12:40:48 2004
+++ Products/PluggableAuthService/plugins/HTTPBasicAuthHelper.py	Sat Oct 16 16:15:47 2004
@@ -36,7 +36,7 @@
 
 def addHTTPBasicAuthHelper( dispatcher, id, title=None, REQUEST=None ):
 
-    """ Add a HTTP Basic Auth Helper to a Pluggable Auth Service. 
+    """ Add a HTTP Basic Auth Helper to a Pluggable Auth Service.
     """
     sp = HTTPBasicAuthHelper( id, title )
     dispatcher._setObject( sp.getId(), sp )
@@ -61,6 +61,8 @@
 
     security = ClassSecurityInfo()
 
+    protocol = "http" # The PAS challenge 'protocol' we use.
+
     def __init__( self, id, title=None ):
         self._setId( id )
         self.title = title
@@ -94,18 +96,19 @@
         """
         realm = response.realm
         if realm:
-            response.setHeader('WWW-Authenticate', 'basic realm="%s"' % realm, 1)
+            response.addHeader('WWW-Authenticate',
+                               'basic realm="%s"' % realm)
         m = "<strong>You are not authorized to access this resource.</strong>"
         if response.debug_mode:
             if response._auth:
                 m = m + '<p>\nUsername and password are not correct.'
             else:
                 m = m + '<p>\nNo Authorization header found.'
-            
+
         response.setBody(m, is_error=1)
         response.setStatus(401)
         return 1
- 
+
     security.declarePrivate( 'resetCredentials' )
     def resetCredentials( self, request, response ):
 


=== Products/PluggableAuthService/plugins/CookieAuthHelper.py 1.7 => 1.8 ===
--- Products/PluggableAuthService/plugins/CookieAuthHelper.py:1.7	Fri Sep 24 12:49:18 2004
+++ Products/PluggableAuthService/plugins/CookieAuthHelper.py	Sat Oct 16 16:15:47 2004
@@ -18,6 +18,7 @@
 """
 
 from base64 import encodestring, decodestring
+from urllib import quote
 
 from AccessControl.SecurityInfo import ClassSecurityInfo
 from OFS.Folder import Folder
@@ -104,7 +105,7 @@
         if cookie:
             cookie_val = decodestring(cookie)
             login, password = cookie_val.split(':')
-            
+
             creds['login'] = login
             creds['password'] = password
         else:
@@ -119,11 +120,6 @@
                 request.set('__ac_name', '')
                 request.set('__ac_password', '')
 
-                cookie_val = encodestring('%s:%s' % (login, password))
-                cookie_val = cookie_val.replace( '\n', '' )
-                response = request['RESPONSE']
-                response.setCookie(self.cookie_name, cookie_val, path='/')
-
         if creds:
             creds['remote_host'] = request.get('REMOTE_HOST', '')
 
@@ -145,7 +141,7 @@
     def updateCredentials(self, request, response, login, new_password):
         """ Respond to change of credentials (NOOP for basic auth). """
         cookie_val = encodestring('%s:%s' % (login, new_password))
-        
+        cookie_val = cookie_val.replace( '\n', '' )
         response.setCookie(self.cookie_name, cookie_val, path='/')
 
 
@@ -163,11 +159,13 @@
                               , title='Login Form'
                               , text=BASIC_LOGIN_FORM
                               )
+        self.login_form.__roles__ = []
 
 
     security.declarePrivate('unauthorized')
     def unauthorized(self):
-        resp = self.REQUEST['RESPONSE']
+        req = self.REQUEST
+        resp = req['RESPONSE']
         # If we set the auth cookie before, delete it now.
         if resp.cookies.has_key(self.cookie_name):
             del resp.cookies[self.cookie_name]
@@ -175,7 +173,16 @@
         # Redirect if desired.
         url = self.getLoginURL()
         if url is not None:
-            response.redirect(url)
+            came_from = req.get('came_from', None)
+            if came_from is None:
+                came_from = req.get('URL', '')
+                query = req.get('QUERY_STRING')
+                if query:
+                    if not query.startswith('?'):
+                        query = '?' + query
+                    came_from = came_from + query
+            url = url + '?came_from=%s' % quote(came_from)
+            resp.redirect(url, lock=1)
             return 1
 
         # Could not challenge.
@@ -192,6 +199,23 @@
         else:
             return None
 
+    security.declarePublic('login')
+    def login(self):
+        """ Set a cookie and redirect to the url that we tried to
+        authenticate against originally.
+        """
+        request = self.REQUEST
+        response = request['RESPONSE']
+
+        login = request.get('__ac_name', '')
+        password = request.get('__ac_password', '')
+
+        self.updateCredentials(request, response, login, password)
+
+        came_from = request.form['came_from']
+
+        return response.redirect(came_from)
+
 
 InitializeClass(CookieAuthHelper)
 
@@ -206,9 +230,10 @@
     <h3> Please log in </h3>
 
     <form method="post" action=""
-          tal:define="acl_path here/acl_users/absolute_url"
-          tal:attributes="action string:${acl_path}/login">
+          tal:attributes="action string:${here/absolute_url}/login">
 
+      <input type="hidden" name="came_from" value=""
+             tal:attributes="value request/came_from | string:"/>
       <table cellpadding="2">
         <tr>
           <td><b>Login:</b> </td>



More information about the Zope-CVS mailing list