source: TI12-security/trunk/python/ndg.security.client/ndg/security/client/ssoclient/ssoclient/lib/base.py @ 3918

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg.security.client/ndg/security/client/ssoclient/ssoclient/lib/base.py@3918
Revision 3918, 5.0 KB checked in by pjkersha, 12 years ago (diff)

Initial Integration of Single Sign On Service with OpenID and Pylons AuthKit?:

  • WAYF now contains an OpenID textbox for sign in
  • No role integration carried out yet - OpenID has no better privileges than an anonymous user(!)
  • Integrated into Authkit - requires lots of config settings in pylons ini file
  • HTTP 401 error get redirected automatically to WAYF
  • Need to create an AuthKit? egg from SVN 151 checkout - will put on NDG dist
Line 
1"""The base Controller API
2
3Provides the BaseController class for subclassing, and other objects
4utilized by Controllers.
5"""
6from pylons import c, cache, config, g, request, response, session
7from pylons.controllers import WSGIController
8from pylons.controllers.util import abort, etag_cache, redirect_to
9from pylons.decorators import jsonify, validate
10from pylons.i18n import _, ungettext, N_
11from pylons.templating import render
12
13import ndg.security.client.ssoclient.ssoclient.lib.helpers as h
14import ndg.security.client.ssoclient.ssoclient.model as model
15
16import urllib
17from urlparse import urlsplit, urlunsplit
18from base64 import urlsafe_b64encode
19
20from ndg.security.common.pylons.security_util import setSecuritySession, \
21    SSOServiceQuery, SecuritySession
22
23import logging
24log = logging.getLogger(__name__)
25
26class BaseControllerError(Exception):
27    "Error handling for BaseController"
28   
29class BaseController(WSGIController):
30
31    def __before__(self):
32        '''Strip query arguments from a Login Service request and redirect from
33        https -> http
34       
35        Moved this code from __call__ because redirect_to doesn't work from
36        BaaseController.__call__.  I suspect this is a problem introduced
37        with change from Pylons 0.9.5 -> 0.9.6.  See:
38       
39        http://pylonshq.com/irclogs/%23pylons/%23pylons.2007-08-30.log.html'''
40       
41        log.debug("BaseController.__before__ ...")
42        if 'h' in request.params:
43            # 'h' corresponds to the setting of a session manager host i.e.
44            # the request has come from a completed login from the login
45            # service
46            log.debug("Setting security session from URL query args ...")
47           
48            # Copy the query arguments into security session keys
49            setSecuritySession()           
50            session.save()
51           
52            log.debug('Switching from https to http...')
53            returnToURL = g.ndg.security.common.sso.cfg.server + \
54                self.pathInfo
55
56            # Reconstruct the URL removing the security related arguments
57            qs = SSOServiceQuery.stripFromURI()
58            if qs:
59                returnToURL += "?" + qs
60               
61            log.debug('URL transport switched to http: "%s"' % returnToURL)
62            h.redirect_to(returnToURL)
63           
64        elif 'logout' in request.params:
65            # Request comes from a successful logout call.  Clean up any
66            # security cookies in this domain
67            log.debug("Removing security details following logout ...")
68
69            returnToURL = g.ndg.security.common.sso.cfg.server + \
70                self.pathInfo
71               
72            # Reconstruct the URL removing the logout flag argument
73            qs = SSOServiceQuery.stripFromURI('logout')
74            if qs:
75                returnToURL += "?" + qs
76           
77            # Delete security session cookie details
78            SecuritySession.delete()
79           
80            # Redirect to cleaned up URL
81            h.redirect_to(returnToURL)
82
83        self._OpenIDHandler()
84                         
85                         
86    def __call__(self, environ, start_response):       
87        # Insert any code to be run per request here. The Routes match
88        # is under environ['pylons.routes_dict'] should you want to check
89        # the action or route vars here
90        log.debug("BaseController.__call__: %s ..." % \
91                                                environ['pylons.routes_dict'])
92
93        log.debug("_"*80)
94        log.debug("environ = %s" % environ)
95        log.debug("_"*80)
96       
97        self.pathInfo = urllib.quote(environ.get('PATH_INFO', '')) 
98
99        # construct URL picking up setting of server name from config to
100        # avoid exposing absolute URL hidden behind mod_proxy see #857
101        c.requestURL = g.ndg.security.common.sso.cfg.server + \
102            self.pathInfo
103        qs = '&'.join(["%s=%s" % item for item in request.params.items()])
104        if qs:
105            c.requestURL += '?' + qs
106
107        self._environ = environ
108       
109        return WSGIController.__call__(self, environ, start_response)
110
111       
112    def _OpenIDHandler(self):
113        '''OpenID handling - check for user set and if so that an existing
114        session doesn't already exist'''
115
116        if 'REMOTE_USER' in request.environ and \
117           SecuritySession()['u'] != request.environ['REMOTE_USER']:
118       
119            username = request.environ['REMOTE_USER']
120                           
121            # No session exists - set one.
122            # TODO: OpenID integration with Session Manager WS?
123            # TODO: OpenID user attribute allocation
124            setSecuritySession(h=None,
125                               u=username,
126                               org=username,
127                               roles=['OpenIDUser'],
128                               sid=None)
129            SecuritySession.save()
130   
131# Include the '_' function in the public names
132__all__ = [__name for __name in locals().keys() if not __name.startswith('_') \
133           or __name == '_']
Note: See TracBrowser for help on using the repository browser.