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

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

Latest working version with install method.
Can accept more than one file but doesn't combine variables yet.

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