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

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI03-DataExtractor/trunk/pydxc/SecurityViaCGI.py@1184
Revision 1184, 6.1 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"""
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    def dummy(self):
84        c=Cookie.SimpleCookie()
85        c["DX"]="somethingOrother"
86        c["DX"]["domain"]="localhost"
87        c["DX"]["path"]="/"
88        print c
89
90    def _createCookie(self, username, userRoles, expiryTime=None):
91        """
92        Writes a cookie to the user's browser cookie cache.
93        """
94        self.dummy()
95        # NOTE: This should be brought up to date with W3C spec on Cookies
96        endTime=time.time()+TOKEN_VALID_LIFETIME
97        endTimeString=time.strftime("%d/%m/%y %H:%M%S", time.localtime(endTime))
98        cookieString="%s:%s:%s" % (username, string.join(userRoles, ","), endTime)
99        cookieMaker=Cookie.SimpleCookie()
100        cookieMaker[COOKIE_NAME]=cookieString
101        #cookieMaker[COOKIE_NAME]["domain"]=TOKEN_DOMAIN
102        cookieMaker[COOKIE_NAME]["path"]="/"
103
104        # Use expiry time of zero to delete a cookie, or other time if used
105        if expiryTime!=None:
106            expiryTime=endTimeString
107               
108        cookieMaker[COOKIE_NAME]["expires"]=expiryTime
109
110        # Set the cookie
111        print cookieMaker
112        #o=open('/tmp/tmp/out.txt', 'w'); o.write("%s" % (cookieString+"\n"+TOKEN_DOMAIN)) ; o.close()
113       
114        return cookieString
115       
116    def _getUsername(self, cookieString):
117        """
118        Returns username.
119        """
120        return cookieString.split(":")[0]
121       
122    def _getUserRoles(self, cookieString):
123        """
124        Returns user roles as a list.
125        """
126        return cookieString.split(":")[1].split(",") 
127
128    def _getExpiryTime(self, cookieString):
129        """
130        Returns expiry time as a float.
131        """
132        return float(cookieString.split(":")[-1])
133       
134    def _checkCookie(self):
135        """
136        Checks for a security cookie and returns the cookie string if valid.
137        """
138        cookieString=self._readCookie()
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.