source: TI03-DataExtractor/trunk/pydxc/NDGSecurityViaCGI.py @ 1244

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI03-DataExtractor/trunk/pydxc/NDGSecurityViaCGI.py@1244
Revision 1244, 6.8 KB checked in by astephen, 14 years ago (diff)

Close to alpha version.

Line 
1#   Copyright (C) 2004 CCLRC & NERC( Natural Environment Research Council ).
2#   This software may be distributed under the terms of the
3#   Q Public License, version 1.0 or later. http://ndg.nerc.ac.uk/public_docs/QPublic_license.txt
4
5"""
6NDGSecurityViaCGI.py
7=================
8
9Security module for the CGI client that uses NDG Security.
10
11"""
12
13# Import python standard library modules
14import sys, os, time, Cookie, string, re
15
16from NDG.SecurityClient import *
17
18# Import local modules
19from clientConfig import COOKIE_NAME, TOKEN_VALID_LIFETIME, TOKEN_DOMAIN
20
21ct="Content-type: text/html\n\n"
22class NDGSecurityViaCGI:
23    """
24    NDG Security hooks for CGI client.
25    """
26   
27    def __init__(self, cookie=None, urlArgs=None):
28        """
29        Initialises the instance defining instance variables
30        """
31        sys.path.append("/disks/glue1/astephens")
32        import stuff
33        self.username=None
34        self.roles=None
35        self.conf=stuff
36        self.cookie=cookie
37        self.ndgcookie=None
38        self.urlArgs=urlArgs
39        self.ndgSec=[]
40
41    def getUsernameAndRolesFromNDGLogin(self):
42        found=0
43        storedCookies=os.environ.get("HTTP_COOKIE")
44        if storedCookies:
45            if storedCookies.find("NDG-ID1")>-1 and storedCookies.find("NDG-ID2")>-1:
46                #print ct #,"Coooooooooook", storedCookies
47                ndgID1=self._readCookie("NDG-ID1")
48                ndgID2=self._readCookie("NDG-ID2")
49                self.ndgSec.append(ndgID1)
50                self.ndgSec.append(ndgID2)
51                found=1
52        elif self.urlArgs!=None:
53            keys=self.urlArgs.keys()
54            if "NDG-ID1" in keys and "NDG-ID2" in keys:
55                self.ndgSec.append(self.urlArgs["NDG-ID1"].value)
56                self.ndgSec.append(self.urlArgs["NDG-ID2"].value)
57                found=1
58
59        if found==1:
60                self.smClient = SessionClient(smWSDL=self.conf.sessionMgrURL,
61                        smPubKeyFilePath=self.conf.localSessionManagerPublicKey,
62                        clntPubKeyFilePath=self.conf.thisCGIpublicKey,
63                        clntPriKeyFilePath=self.conf.thisCGIprivateKey)
64                resp=self.smClient.reqAuthorisation(sessID=self.ndgSec[0], encrSessMgrWSDLuri=self.ndgSec[1],
65                        reqRole="coapec", aaWSDL=self.conf.aaWSDL,
66                        mapFromTrustedHosts=True, clntPriKeyPwd=None)
67
68                try:
69                    ac=resp["attCert"]
70                    self.roles=ac.getRoles()
71                    holder=ac.getHolder()
72                    realHolder=re.match("/CN=(\w+)/O", holder).group(1)
73                    self.username=realHolder
74                except:
75                    if type(resp)!=type("hi"): resp=repr(resp)
76                    if resp.find("is before Attribute Certificate's not before time")>-1: return "Attribute Certificate 'not before time' error detected."
77
78
79
80
81    def getTrustedHostList(self):
82        self.aa=AttAuthorityClient(aaWSDL=self.conf.aaWSDL)
83        #print ct, dir(self.aa), self.conf.aaWSDL
84        thd=self.aa.getTrustedHostInfo(role="university")
85        self.loginHosts=[]
86        for key in thd.keys():
87            self.loginHosts.append((key, thd[key]["loginURI"])) 
88        return self.loginHosts
89
90    def validate(self):
91        """
92        Returns either a string with a message meaning that the user is not
93        valid, or a tuple of (secureToken, username, userRoles).
94        """
95        # First check if the user is valid via a cookie
96        cookieCheck=self._checkCookie()
97        #o=open('/tmp/cook.txt','w'); o.write(str(cookieCheck)) ; o.close()
98 
99        if type(cookieCheck)==type("") or cookieCheck==None:
100            # Didn't get a local cookie, so try and get NDG cookie
101            self.getUsernameAndRolesFromNDGLogin()
102            #o=open('/tmp/co.txt','w'); o.write(str(self.username)) ; o.close()
103            if self.username!=None and self.roles!=None:
104                # Now we have username and roles, make local cookie
105                cookieString=self._createCookie(self.username, self.roles)
106                return (cookieString, self.username, self.roles)
107            else:
108                # If string error then need to try and login again locally
109                return cookieCheck
110
111        elif type(cookieCheck)==type([]):
112            # Return the valid secure token and user roles
113            (cookieString, username, userRoles)=cookieCheck
114            return (cookieString, username, userRoles)
115           
116
117
118    def _createCookie(self, username, userRoles, expiryTime=None):
119        """
120        Writes a cookie to the user's browser cookie cache.
121        """
122        # NOTE: This should be brought up to date with W3C spec on Cookies
123        endTime=time.time()+TOKEN_VALID_LIFETIME
124        endTimeString=time.strftime("%d/%m/%y %H:%M%S", time.localtime(endTime))
125        cookieString="%s:%s:%s" % (username, string.join(userRoles, ","), endTime)
126        cookieMaker=Cookie.SimpleCookie()
127        cookieMaker[COOKIE_NAME]=cookieString
128        #cookieMaker[COOKIE_NAME]["domain"]=TOKEN_DOMAIN
129        cookieMaker[COOKIE_NAME]["path"]="/"
130
131        # Use expiry time of zero to delete a cookie, or other time if used
132        if expiryTime==None:
133            expiryTime=endTimeString
134               
135        cookieMaker[COOKIE_NAME]["expires"]=expiryTime
136
137        # Set the cookie
138        print cookieMaker
139        #o=open('/tmp/tmp/out.txt', 'w'); o.write("%s" % (cookieString+"\n"+TOKEN_DOMAIN)) ; o.close()
140       
141        return cookieString
142       
143    def _getUsername(self, cookieString):
144        """
145        Returns username.
146        """
147        return cookieString.split(":")[0]
148       
149    def _getUserRoles(self, cookieString):
150        """
151        Returns user roles as a list.
152        """
153        return cookieString.split(":")[1].split(",") 
154
155    def _getExpiryTime(self, cookieString):
156        """
157        Returns expiry time as a float.
158        """
159        return float(cookieString.split(":")[-1])
160       
161    def _checkCookie(self):
162        """
163        Checks for a security cookie and returns the cookie string if valid.
164        """
165        cookieString=self._readCookie()
166       
167        if cookieString:
168            expiryTime=self._getExpiryTime(cookieString)
169            now=time.time()
170           
171            if expiryTime>now:
172                # Update the cookie's expiry time
173                username=self._getUsername(cookieString)
174                userRoles=self._getUserRoles(cookieString)
175                cookieString=self._createCookie(username, userRoles)
176                return [cookieString, username, userRoles]
177            else:
178                return "Your log in has expired. Please log in again."
179       
180        return "You are not logged in with local login."
181   
182    def _readCookie(self, cookie_name=COOKIE_NAME):
183        """
184        Reads the content of a specified cookie.
185        """
186        cookieReader=Cookie.SimpleCookie()
187        if not os.environ.has_key("HTTP_COOKIE"):
188            cookieString=None
189            #out=open("/tmp/tmp/iscookie.txt","w");out.write("%s" % cookieString); out.close()
190        else:
191            cookieReader.load(os.environ["HTTP_COOKIE"])
192            try:
193                cookieString=cookieReader[cookie_name].value       
194            except:
195                cookieString=None
196        return cookieString   
197       
198    def logout(self):
199        """
200        Logs user out by destroying cookie (setting expiry time to ZERO!).
201        """
202        cookieDestroyer=Cookie.SimpleCookie()
203        expiryTime=0
204        self._createCookie("rubbish", ["non", "sense"], expiryTime)
205
206   
Note: See TracBrowser for help on using the repository browser.