change: I switched the authentication framework from repoze.who to authkit.
authorRicardo Velhote <rvelhote@gmail.com>
Tue, 2 Mar 2010 00:14:41 +0000 (00:14 +0000)
committerRicardo Velhote <rvelhote@gmail.com>
Tue, 2 Mar 2010 00:14:41 +0000 (00:14 +0000)
I was having problems using the pylons session object with repoze that I
could not solve and could not find an answer to.
change: SwatMessages class is now used per session. I placed its methods
under the @staticmethod decorator
change: references to the helper variable swat_messages were replaced
by the class name SwatMessages

development.ini
swat/config/middleware.py
swat/controllers/authentication.py
swat/controllers/dashboard.py
swat/controllers/share.py
swat/lib/helpers.py
swat/templates/default/base/base.mako
swat/templates/default/base/login-screen.mako
who.ini

index a15246a273a30d775a002b0ee769435e272e40dc..d686692159dc477618bb72d3a931371803233136 100644 (file)
@@ -24,7 +24,17 @@ lang = en
 #
 # repoze.who
 #
-who.config_file = %(here)s/who.ini
+#who.config_file = %(here)s/who.ini
+authkit.setup.method = forward,cookie
+
+authkit.forward.signinpath = /authentication/login
+authkit.cookie.signoutpath = /authentication/logout
+authkit.cookie.secret = cookie secret
+authkit.cookie.name = authkit_cookie_name
+#authkit.cookie.params = expires: 3600
+
+
+#authkit.forward.signoutpath = /authentication/logout
 
 yaml.config = %(here)s/swat/config/yaml
 
index 8f42ca00cf84f88b98f18177e221aa625def6067..07f62240f6278408ea38ab00502448a32aa80f45 100644 (file)
@@ -14,8 +14,10 @@ from swat.config.environment import load_environment
 #
 #   repoze.who
 #
-from repoze.who.config import make_middleware_with_config
+#from repoze.who.config import make_middleware_with_config
 
+import authkit.authenticate
+from paste.recursive import RecursiveMiddleware
 
 def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
     """Create a Pylons WSGI application and return it
@@ -54,13 +56,16 @@ def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
     # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
     
     if asbool(full_stack):
+        app = RecursiveMiddleware(app, global_conf)
+        
         # Handle Python exceptions
         app = ErrorHandler(app, global_conf, **config['pylons.errorware'])
         
         #
         # repoze.who
         #
-        app = make_middleware_with_config(app, global_conf, app_conf['who.config_file'])        
+        #app = make_middleware_with_config(app, global_conf, app_conf['who.config_file'])
+        app = authkit.authenticate.middleware(app, app_conf)
 
         # Display error documents for 401, 403, 404 status codes (and
         # 500 when debug is disabled)
index 9a7dc2129d64612b11a225631cd9a2a7a06d0490..2fe83e40c0898bfe3435d6b083a04a4c8cdb5de1 100644 (file)
@@ -19,7 +19,7 @@ from pylons import request, response, session, tmpl_context as c
 from pylons.controllers.util import abort, redirect_to
 
 from swat.lib.base import BaseController, render
-from swat.lib.helpers import swat_messages
+from swat.lib.helpers import SwatMessages
 
 from pylons.i18n.translation import _
 
@@ -47,7 +47,7 @@ class AuthenticationController(BaseController):
         """
         redirect_to(controller = 'authentication', action = 'login')
         
-    def authenticate(self, environ, identity):
+    def __authenticate(self):
         """ Performs the custom authentication. This method is required by
         repoze and we are sent here by it.
         
@@ -63,28 +63,34 @@ class AuthenticationController(BaseController):
         work here. Maybe I'm using repoze.who wrong?
         
         """
-        username = identity['login']
-        password = identity['password']
+        username = request.params.get("login", "").strip()
+        password = request.params.get("password", "").strip()
+        
+        # FIXME!!!!
+        environ = []
         
         len_username = len(username)
-        len_password = len(password)        
+        len_password = len(password)
+        
+        print username + " -- " + password
         
         if len_username == 0:
-            swat_messages.add('Username cannot be empty', 'critical')
+            SwatMessages.add('Username cannot be empty', 'critical')
             
         if len_password == 0:
-            swat_messages.add('Password cannot be empty', 'critical')
+            SwatMessages.add('Password cannot be empty', 'critical')
 
         if self.__perform_authentication(username, password, environ):
-            swat_messages.add('Authentication successful!')
-            log.info("login attempt sucessful by " + username)
+            SwatMessages.add('Authentication successful!')
+            log.info("login attempt successful by " + username)
+            request.environ['paste.auth_tkt.set_user'](username)
             
-            return username
+            return True
         
         log.warning("failed login attempt by " + username)
-        swat_messages.add('Authentication failed' + ' -- ' + self.__reason, 'critical')
+        SwatMessages.add('Authentication failed' + ' -- ' + self.__reason, 'critical')
         
-        return None
+        return False
     
     def __perform_authentication(self, username, password, environ):
         """ Performs the authentication of a user depending on the available
@@ -181,4 +187,7 @@ class AuthenticationController(BaseController):
         set this to login otherwise it would just send me to the login method
         
         """
-        pass
+        if self.__authenticate():
+            redirect_to(controller='dashboard', action='index')
+        else:
+            redirect_to(controller='authentication', action='login')
index 29aa0710df646ac98345d3e0ffd0183a0c626932..340847c601a451cf6e618829ce7c26c4e9608530 100644 (file)
@@ -25,7 +25,7 @@ from routes import url_for
 from pylons.i18n.translation import _
 
 from swat.lib.helpers import ControllerConfiguration, DashboardConfiguration, \
-BreadcrumbTrail, SwatMessages, swat_messages
+BreadcrumbTrail, SwatMessages
 
 log = logging.getLogger(__name__)
 
@@ -47,11 +47,20 @@ class DashboardController(BaseController):
         c.samba_lp.load_default()
 
     def index(self):
-        identity = request.environ.get('repoze.who.identity')
+        from authkit.permissions import NotAuthenticatedError
         
-        if identity is None:
-            swat_messages.add(_("You must be authenticated to perform that action"), "critical")
+        if not request.environ.has_key('REMOTE_USER'):
+            SwatMessages.add(_("You must be authenticated to perform that action"), "critical")
             abort(401)
+          # raise NotAuthenticatedError('Not Authenticated')
+
+        
+        
+        #identity = request.environ.get('repoze.who.identity')
+        
+        #if identity is None:
+          #  SwatMessages.add(_("You must be authenticated to perform that action"), "critical")
+          #  abort(401)
         
         """ The default Dashboard. The entry point for SWAT """
         return render('/default/derived/dashboard.mako')
index 96e6a093ddbf16d8adc4d4bcbbd06efd2d7eb22f..d153052a41e8d4b7f13db792259da35811bb5eea 100644 (file)
@@ -24,7 +24,7 @@ from swat.lib.base import BaseController, render
 from pylons.templating import render_mako_def
 from pylons.i18n.translation import _
 from swat.lib.helpers import ControllerConfiguration, DashboardConfiguration, \
-BreadcrumbTrail, swat_messages, ParamConfiguration, filter_list
+BreadcrumbTrail, SwatMessages, ParamConfiguration, filter_list
 
 log = logging.getLogger(__name__)
 
@@ -47,7 +47,7 @@ class ShareController(BaseController):
         is a list of allowed operations that is checked to see if it's ok to
         load the configuration
         
-        """        
+        """
         me = request.environ['pylons.routes_dict']['controller']
         action = request.environ['pylons.routes_dict']['action']
         
@@ -75,7 +75,7 @@ class ShareController(BaseController):
             log.error( c.samba_lp.get("share backend") + "is unsupported at the moment")
             
             message = _("Your chosen backend is not yet supported")
-            swat_messages.add(message, "critical")
+            SwatMessages.add(message, "critical")
     
     def index(self):        
         """ Point of entry. Loads the Share List Template """
@@ -112,7 +112,7 @@ class ShareController(BaseController):
         
         if name not in c.share_list and not is_new:
             log.warning("Share " + name + " doesn't exist in the chosen backend")
-            swat_messages.add(_("Can't edit a Share that doesn't exist"), "warning")
+            SwatMessages.add(_("Can't edit a Share that doesn't exist"), "warning")
             redirect_to(controller='share', action='index')
         else:
             c.p = ParamConfiguration('share-parameters')
@@ -137,14 +137,14 @@ class ShareController(BaseController):
             
             if stored:
                 message = _("Share Information was Saved")
-                swat_messages.add(message)
+                SwatMessages.add(message)
             else:
-                swat_messages.add(backend.get_error_message(), backend.get_error_type())
+                SwatMessages.add(backend.get_error_message(), backend.get_error_type())
         else:
             log.error("Error saving because the backend (" + c.samba_lp.get("share backend") + ") is unsupported")
             
             message = _("Your chosen backend is not yet supported")
-            swat_messages.add(message, "critical")
+            SwatMessages.add(message, "critical")
 
         if request.environ['pylons.routes_dict']['action'] == "save":
             redirect_to(controller='share', action='index')
@@ -169,7 +169,7 @@ class ShareController(BaseController):
         elif request.params.get("task", "edit") == "edit":
             message = _("Cancelled Share editing. No changes were saved!")
         
-        swat_messages.add(message, "warning")
+        SwatMessages.add(message, "warning")
         redirect_to(controller='share', action='index')
         
     def path(self):
@@ -235,11 +235,11 @@ class ShareController(BaseController):
                 
                 log.warning(message)
             
-            swat_messages.add(message, type)
+            SwatMessages.add(message, type)
         else:
             log.error("Error removing because the backend (" + c.samba_lp.get("share backend") + ") is unsupported")
             message = _("Your chosen backend is not yet supported")
-            swat_messages.add(message, "critical")
+            SwatMessages.add(message, "critical")
         
         redirect_to(controller='share', action='index')
     
@@ -279,11 +279,11 @@ class ShareController(BaseController):
                 
                 log.warning(message)
 
-            swat_messages.add(message, type)
+            SwatMessages.add(message, type)
         else:
             log.error("Error copying because the backend (" + c.samba_lp.get("share backend") + ") is unsupported")
             message = _("Your chosen backend is not yet supported")
-            swat_messages.add(message, "critical")
+            SwatMessages.add(message, "critical")
             
         redirect_to(controller='share', action='index')
     
@@ -303,12 +303,12 @@ class ShareController(BaseController):
             
             if toggled:
                 message = _("Share Toggled successfuly")
-                swat_messages.add(message)
+                SwatMessages.add(message)
             else:
-                swat_messages.add(backend.get_error_message(), backend.get_error_type())
+                SwatMessages.add(backend.get_error_message(), backend.get_error_type())
         else:
             message = _("Your chosen backend is not yet supported")
-            swat_messages.add(message, "critical")
+            SwatMessages.add(message, "critical")
         
         redirect_to(controller='share', action='index')
 
index 16752397643294f97980bd2cfbd22ebcf24fd946..dc4d0f623f87669049064d1986da70392966c655 100644 (file)
@@ -22,7 +22,7 @@ from webhelpers.html.tags import *
 from webhelpers.html import literal
 
 from routes import url_for
-from pylons import request, app_globals as g, config
+from pylons import request, app_globals as g, config, session
 
 import yaml
 import logging
@@ -408,11 +408,8 @@ class SwatMessages:
     in there will be a problem of them seeing messages that don't belong to them
     
     """
-    def __init__(self):
-        """ Initialization """
-       self._items = []
-    
-    def add(self, text, type='cool'):
+    @staticmethod
+    def add(text, type='cool'):
         """ Add a message to the message queue.
         
         Concerning the message type, it can be anything but to have any
@@ -429,40 +426,48 @@ class SwatMessages:
         type -- the type of message. default value is 'cool'
         
         """
-       if len(type) == 0:
-           type = 'cool'
-           
-       self._items.append({'text' : text, 'type' : type})
-       
-    def clean(self):
+        if len(type) == 0:
+            type = 'cool'
+            
+        if not session.has_key('swat_messages'):
+            session['swat_messages'] = []
+
+        session['swat_messages'].append({'text' : text, 'type' : type})
+        session.save()
+
+    @staticmethod
+    def clean():
         """ Cleanup message queue. This should be called after messages are
         shown in the template
         
         """
-       del self._items[:]
+        if session.has_key('swat_messages'):
+            del session['swat_messages']
+            session.save()
 
-    def get(self):
+    @staticmethod
+    def get():
         """ Gets all messages currently stored as a dictionary """
-       return self._items
-    
-    def __len__(self):
+        return session['swat_messages']
+
+    @staticmethod
+    def __len__():
         """ Returns the number of messsages in store """
-       return len(self._items)
+        return len(session['swat_messages'])
     
-    def any(self):
+    @staticmethod
+    def any():
         """ Checks if there are any messages in the queue.
         Returns a boolean value
         
         """
-       has_any = False
-       
-       if len(self._items) > 0:
+        has_any = False
+
+       if session.has_key('swat_messages') and len(session['swat_messages']) > 0:
            has_any = True
            
        return has_any
 
-swat_messages = SwatMessages()
-
 def get_samba_server_status():
     """ Gets the current Samba4 status to be used in the CSS class name for the
     top template in the Server Name area.
index a84d240264761117709997befa5596f193a18d91..23036e2c0ad690cb8a2b02553bf6cb371e82460b 100644 (file)
@@ -31,9 +31,9 @@
            <div id="swat-main-area">   
                ${menu.breadcrumb()}
                
-               % if h.swat_messages.any():
-                   ${messages.write(h.swat_messages.get())}
-                   <% h.swat_messages.clean() %>
+               % if h.SwatMessages.any():
+                   ${messages.write(h.SwatMessages.get())}
+                   <% h.SwatMessages.clean() %>
                % endif
                
                ${self.body()}
index 96692e757eca32a6d400b00eaa89eb6211f443ea..e539e965ecb6818c0fd9df4e01f210a3fc356cdf 100644 (file)
@@ -9,9 +9,9 @@
     
     <body>        
        <div class="swat-content login round-2px">
-            % if h.swat_messages.any():
-                ${messages.write(h.swat_messages.get())}
-                <% h.swat_messages.clean() %>
+            % if h.SwatMessages.any():
+                ${messages.write(h.SwatMessages.get())}
+                <% h.SwatMessages.clean() %>
             % endif
             
            ${base.samba_logo(False)}
diff --git a/who.ini b/who.ini
index 32dee09a28112fcc325ac38294d66466b4c9a4a3..e605ef7f16a157782a75a2c9a561e853749c2fcd 100644 (file)
--- a/who.ini
+++ b/who.ini
@@ -9,7 +9,7 @@ rememberer_name = auth_tkt
 
 [plugin:auth_tkt]
 use = repoze.who.plugins.auth_tkt:make_plugin
-secret = to-be_randomly--generated
+secret = 6CBC8654B175A121826543483E99F9E4
 
 [general]
 request_classifier = repoze.who.classifiers:default_request_classifier