source: TI12-security/trunk/python/ndg.security.server/ndg/security/server/sso/sso/controllers/logout.py @ 4893

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg.security.server/ndg/security/server/sso/sso/controllers/logout.py@4893
Revision 4893, 4.5 KB checked in by pjkersha, 11 years ago (diff)

Fix ref to cfg object.

Line 
1"""Single Sign On Service Logout Controller
2
3NERC DataGrid Project
4"""
5__author__ = "P J Kershaw"
6__date__ = "10/12/08"
7__copyright__ = "(C) 2009 Science and Technology Facilities Council"
8__license__ = "BSD - see LICENSE file in top-level directory"
9__contact__ = "Philip.Kershaw@stfc.ac.uk"
10__revision__ = '$Id$'
11from ndg.security.server.sso.sso.lib.base import *
12from ndg.security.common.pylons.security_util import SecuritySession
13import logging
14log = logging.getLogger(__name__)
15
16import sys # include in case tracefile is set to sys.stderr
17import base64 # decode the return to address
18from urlparse import urlsplit, urlunsplit
19
20from ndg.security.server.wsgi.utils.sessionmanagerclient import \
21    WSGISessionManagerClient, SessionExpired, AttributeRequestDenied
22
23
24class LogoutController(BaseController):
25    '''Provides the pylons controller for logging out and removing security
26    session cookie content
27    '''
28
29    def index(self):
30        '''Logout - remove session from Session Manager tidy up cookie'''
31
32        log.info("LogoutController.index ...")
33       
34        # Convenience alias
35        cfg = g.ndg.security.server.sso.cfg
36       
37
38        if 'ndgSec' not in session:
39            # There's no handle to a security session
40            log.error("logout called but no 'ndgSec' key in session object")
41            return self._redirect()
42       
43        try:
44            smClnt = WSGISessionManagerClient(uri=session['ndgSec']['h'],
45                        environ=request.environ,
46                        tracefile=cfg.tracefile,
47                        sslCACertFilePathList=cfg.sslCACertFilePathList,
48                        **cfg.wss)       
49        except Exception, e:
50            log.error("logout - creating Session Manager client: %s" % e)
51            return self._cleanupAndRedirect() 
52       
53        # Disconnect from Session Manager
54        log.info('Calling Session Manager "%s" disconnect for logout...' %
55                 session['ndgSec']['h'])
56        try:
57            smClnt.disconnect(sessID=session['ndgSec']['sid'])
58        except Exception, e:
59            log.error("Error with Session Manager logout: %s" % e)
60            # don't exit here - instead proceed to delete session and
61            # redirect ...
62
63        return self._cleanupAndRedirect()
64
65
66    def _cleanupAndRedirect(self):
67        """Remove security session and call _redirect"""
68        try:
69            # easy to kill our cookie
70            SecuritySession.delete()
71            if 'ndgCleared' in session: del session['ndgCleared']
72            session.save()
73           
74        except Exception, e:   
75            log.error("logout - clearing security session: %s" % e)
76
77        return self._redirect()
78   
79   
80    def _redirect(self):
81        """Handle redirect back to previous page"""
82       
83        # Redirect URL is held in 'r' URL arg of this request
84        b64encReturnTo = str(request.params.get('r', ''))
85
86        if b64encReturnTo:
87            # Decode the return to address
88            try:
89                b64decReturnTo = base64.urlsafe_b64decode(b64encReturnTo)
90            except Exception, e:
91                log.error("logout - decoding return URL: %s" % e) 
92                c.xml = "Error carrying out browser redirect following logout"
93                return render('ndg.security.kid', 'ndg.security.error')
94           
95            # Check for 'getCredentials' - avoid in case username/password
96            # contained in the URL!
97            getCredentialsIdx = b64decReturnTo.rfind('/getCredentials')
98            if getCredentialsIdx != -1:
99                log.debug("Reverting request URL from getCredentials to "
100                          "login...")
101                b64decReturnTo = b64decReturnTo[:getCredentialsIdx] + '/login'
102           
103            # Add flag indicating to caller that logout succeeded.  The caller
104            # can use this to remove any security cookie present in their
105            # domain - See:
106            # ndg.security.client.ssoclient.ssoclient.lib.base.BaseController
107            if '?' in b64decReturnTo:
108                b64decReturnTo += '&logout=1'
109            else:
110                b64decReturnTo += '?logout=1'
111
112            # and now go back to whence we had come
113            log.debug("LogoutController._redirect: redirect to %s" %
114                                                              b64decReturnTo)
115            h.redirect_to(b64decReturnTo)
116        else:
117            log.debug("LogoutController._redirect: no redirect URL set.")
118            return render('ndg.security.kid', 'ndg.security.error')
Note: See TracBrowser for help on using the repository browser.