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

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

Safe version pre-security installation and zsi versioning.

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
15
16from NDG.SecurityClient import *
17
18# Import local modules
19from clientConfig import COOKIE_NAME, TOKEN_VALID_LIFETIME, TOKEN_DOMAIN
20
21
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        self.cookie=cookie
32        # convert urlArgs into stuff we need
33        self.ndgSec=[]
34        if urlArgs!=None:
35            keys=urlArgs.keys()
36            if "NDG-ID1" in keys and "NDG-ID2" in keys:
37                self.ndgSec[0]=urlArgs.getvalue("NDG-ID1")
38                self.ndgSec[1]=urlArgs.getvalue("NDG-ID2")
39
40
41    def validate(self):
42        """
43        Returns either a None type meaning that the user is not
44        valid, or a tuple of (secureToken, knownRoles).
45        """
46        # First check if the user is valid via a cookie
47        cookieCheck=self._checkCookie()
48        #o=open('/tmp/tmp/cook.txt','w'); o.write(str(cookieCheck)) ; o.close()
49
50        if type(cookieCheck)==type(""):
51            # Return an error string to report to main application
52            return cookieCheck
53        elif type(cookieCheck)==type([]):
54            # Return the valid secure token and user roles
55            (cookieString, username, userRoles)=cookieCheck
56            return (cookieString, username, userRoles)
57           
58        # If no cookie then check if there is a valid username, password provided
59        knownUserPasswords={"rod":"rod1", "jane":"jane1", "freddie":"freddie1",
60                            "zippy":"zippy1"}
61        knownUserRoles={"rod":["dset1"],
62                    "jane":["dset1", "dset2", "dset3"],
63                    "freddie":["dset3"],
64                    "zippy":[]}
65        users=knownUserPasswords.keys()
66
67        # Check if username and password given
68        if self.username==None or self.password==None:
69            return "Please login with username and password."
70       
71        if self.username in users:
72            if self.password==knownUserPasswords[self.username]:
73                userRoles=knownUserRoles[self.username]
74                #cookieString=":".join(userRoles)
75                cookieString=self._createCookie(self.username, userRoles)
76                return (cookieString, self.username, userRoles)
77            else:
78                return "Invalid login."
79        else:
80            return "Username '%s' unknown." % self.username
81
82    def dummy(self):
83        c=Cookie.SimpleCookie()
84        c["DX"]="somethingOrother"
85        c["DX"]["domain"]="localhost"
86        c["DX"]["path"]="/"
87        print c
88
89    def _createCookie(self, username, userRoles, expiryTime=None):
90        """
91        Writes a cookie to the user's browser cookie cache.
92        """
93        self.dummy()
94        # NOTE: This should be brought up to date with W3C spec on Cookies
95        endTime=time.time()+TOKEN_VALID_LIFETIME
96        endTimeString=time.strftime("%d/%m/%y %H:%M%S", time.localtime(endTime))
97        cookieString="%s:%s:%s" % (username, string.join(userRoles, ","), endTime)
98        cookieMaker=Cookie.SimpleCookie()
99        cookieMaker[COOKIE_NAME]=cookieString
100        #cookieMaker[COOKIE_NAME]["domain"]=TOKEN_DOMAIN
101        cookieMaker[COOKIE_NAME]["path"]="/"
102
103        # Use expiry time of zero to delete a cookie, or other time if used
104        if expiryTime!=None:
105            expiryTime=endTimeString
106               
107        cookieMaker[COOKIE_NAME]["expires"]=expiryTime
108
109        # Set the cookie
110        print cookieMaker
111        #o=open('/tmp/tmp/out.txt', 'w'); o.write("%s" % (cookieString+"\n"+TOKEN_DOMAIN)) ; o.close()
112       
113        return cookieString
114       
115    def _getUsername(self, cookieString):
116        """
117        Returns username.
118        """
119        return cookieString.split(":")[0]
120       
121    def _getUserRoles(self, cookieString):
122        """
123        Returns user roles as a list.
124        """
125        return cookieString.split(":")[1].split(",") 
126
127    def _getExpiryTime(self, cookieString):
128        """
129        Returns expiry time as a float.
130        """
131        return float(cookieString.split(":")[-1])
132       
133    def _checkCookie(self):
134        """
135        Checks for a security cookie and returns the cookie string if valid.
136        """
137        cookieString=self._readCookie()
138       
139        if cookieString:
140            expiryTime=self._getExpiryTime(cookieString)
141            now=time.time()
142           
143            if expiryTime>now:
144                # Update the cookie's expiry time
145                username=self._getUsername(cookieString)
146                userRoles=self._getUserRoles(cookieString)
147                cookieString=self._createCookie(username, userRoles)
148                return [cookieString, username, userRoles]
149            else:
150                return "Your log in has expired. Please log in again."
151           
152    def _readCookie(self):
153        """
154        Reads the content of current cookie.
155        """
156        cookieReader=Cookie.SimpleCookie()
157        if not os.environ.has_key("HTTP_COOKIE"):
158            cookieString=None
159            #out=open("/tmp/tmp/iscookie.txt","w");out.write("%s" % cookieString); out.close()
160        else:
161            cookieReader.load(os.environ["HTTP_COOKIE"])
162            try:
163                cookieString=cookieReader[COOKIE_NAME].value       
164            except:
165                cookieString=None
166        return cookieString   
167       
168    def logout(self):
169        """
170        Logs user out by destroying cookie (setting expiry time to ZERO!).
171        """
172        cookieDestroyer=Cookie.SimpleCookie()
173        expiryTime=0
174        self._createCookie("rubbish", ["non", "sense"], expiryTime)
175
176   
Note: See TracBrowser for help on using the repository browser.