source: TI04-geosplat/trunk/pygsc/SecurityViaCGI.py @ 1210

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI04-geosplat/trunk/pygsc/SecurityViaCGI.py@1210
Revision 1210, 5.9 KB checked in by astephen, 15 years ago (diff)

Updated lots of stuff to get zsi working with version 2.0 or lower.

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"""
6SecurityViaCGI.py
7=================
8
9Security module for the CGI client.
10
11Note that there is no standard security implementation.
12You must implement your own but the SecurityViaCGI class provides a hook
13to do this with.
14
15"""
16
17# Import python standard library modules
18import sys, os, time, Cookie, string
19
20# Import local modules
21from clientConfig import COOKIE_NAME, TOKEN_VALID_LIFETIME, TOKEN_DOMAIN
22
23class SecurityViaCGI:
24    """
25    Security class - requires your code for implementation. The basic version only
26    gives an example of the types of calls that might be used. Any real solution
27    needs to hide and encode/decode passwords and cookies.
28    The "cookieString" takes the form "username:role1,role2,role3...:expiryTime".
29    This acts as the secure token as well here. Obviously this is not secure.
30    Just a demostrator with hooks to include your own security implementation.
31    """
32    def __init__(self, username=None, password=None, secureToken=None):
33        """
34        Initialises the instance defining instance variables
35        """
36        self.username=username
37        self.password=password
38        # Note secureToken is not used by browser client which gets input from
39        # os.environ["HTTP_COOKIE"]
40        self.secureToken=secureToken
41
42    def validate(self):
43        """
44        Returns either a None type meaning that the user is not
45        valid, or a tuple of (secureToken, knownRoles).
46        """
47        # First check if the user is valid via a cookie
48        cookieCheck=self._checkCookie()
49        #o=open('/tmp/tmp/cook.txt','w'); o.write(str(cookieCheck)) ; o.close()
50
51        if type(cookieCheck)==type(""):
52            # Return an error string to report to main application
53            return cookieCheck
54        elif type(cookieCheck)==type([]):
55            # Return the valid secure token and user roles
56            (cookieString, username, userRoles)=cookieCheck
57            return (cookieString, username, userRoles)
58           
59        # If no cookie then check if there is a valid username, password provided
60        knownUserPasswords={"rod":"rod1", "jane":"jane1", "freddie":"freddie1",
61                            "zippy":"zippy1"}
62        knownUserRoles={"rod":["dset1"],
63                    "jane":["dset1", "dset2", "dset3"],
64                    "freddie":["dset3"],
65                    "zippy":[]}
66        users=knownUserPasswords.keys()
67
68        # Check if username and password given
69        if self.username==None or self.password==None:
70            return "Please login with username and password."
71       
72        if self.username in users:
73            if self.password==knownUserPasswords[self.username]:
74                userRoles=knownUserRoles[self.username]
75                #cookieString=":".join(userRoles)
76                cookieString=self._createCookie(self.username, userRoles)
77                return (cookieString, self.username, userRoles)
78            else:
79                return "Invalid login."
80        else:
81            return "Username '%s' unknown." % self.username
82 
83
84    def _createCookie(self, username, userRoles, expiryTime=None):
85        """
86        Writes a cookie to the user's browser cookie cache.
87        """
88        # NOTE: This should be brought up to date with W3C spec on Cookies
89        endTime=time.time()+TOKEN_VALID_LIFETIME
90        endTimeString=time.strftime("%d/%m/%y %H:%M%S", time.localtime(endTime))
91        cookieString="%s:%s:%s" % (username, string.join(userRoles, ","), endTime)
92        cookieMaker=Cookie.SimpleCookie()
93        cookieMaker[COOKIE_NAME]=cookieString
94        #cookieMaker[COOKIE_NAME]["domain"]=TOKEN_DOMAIN
95        cookieMaker[COOKIE_NAME]["path"]="/"
96
97        # Use expiry time of zero to delete a cookie, or other time if used
98        if expiryTime==None:
99            expiryTime=endTimeString
100               
101        cookieMaker[COOKIE_NAME]["expires"]=expiryTime
102
103        # Set the cookie
104        print cookieMaker
105        #o=open('/tmp/tmp/out.txt', 'w'); o.write("%s" % (cookieString+"\n"+TOKEN_DOMAIN)) ; o.close()
106       
107        return cookieString
108       
109    def _getUsername(self, cookieString):
110        """
111        Returns username.
112        """
113        return cookieString.split(":")[0]
114       
115    def _getUserRoles(self, cookieString):
116        """
117        Returns user roles as a list.
118        """
119        return cookieString.split(":")[1].split(",") 
120
121    def _getExpiryTime(self, cookieString):
122        """
123        Returns expiry time as a float.
124        """
125        return float(cookieString.split(":")[-1])
126       
127    def _checkCookie(self):
128        """
129        Checks for a security cookie and returns the cookie string if valid.
130        """
131        cookieString=self._readCookie()
132        if cookieString:
133            expiryTime=self._getExpiryTime(cookieString)
134            now=time.time()
135           
136            if expiryTime>now:
137                # Update the cookie's expiry time
138                username=self._getUsername(cookieString)
139                userRoles=self._getUserRoles(cookieString)
140                cookieString=self._createCookie(username, userRoles)
141                return [cookieString, username, userRoles]
142            else:
143                return "Your log in has expired. Please log in again."
144           
145    def _readCookie(self):
146        """
147        Reads the content of current cookie.
148        """
149        cookieReader=Cookie.SimpleCookie()
150        if not os.environ.has_key("HTTP_COOKIE"):
151            cookieString=None
152            #out=open("/tmp/tmp/iscookie.txt","w");out.write("%s" % cookieString); out.close()
153        else:
154            cookieReader.load(os.environ["HTTP_COOKIE"])
155            try:
156                cookieString=cookieReader[COOKIE_NAME].value       
157            except:
158                cookieString=None
159        return cookieString   
160       
161    def logout(self):
162        """
163        Logs user out by destroying cookie (setting expiry time to ZERO!).
164        """
165        cookieDestroyer=Cookie.SimpleCookie()
166        expiryTime=0
167        self._createCookie("rubbish", ["non", "sense"], expiryTime)
168
169   
Note: See TracBrowser for help on using the repository browser.