source: TI03-DataExtractor/branches/titania_install/pydxc/SecurityViaCGI.py @ 1520

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

This is the live version on titania - changes have been made so safest to SVN it.

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
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
83    def _createCookie(self, username, userRoles, expiryTime=None):
84        """
85        Writes a cookie to the user's browser cookie cache.
86        """
87        # NOTE: This should be brought up to date with W3C spec on Cookies
88        endTime=time.time()+TOKEN_VALID_LIFETIME
89        endTimeString=time.strftime("%d/%m/%y %H:%M%S", time.localtime(endTime))
90        cookieString="%s:%s:%s" % (username, string.join(userRoles, ","), endTime)
91        cookieMaker=Cookie.SimpleCookie()
92        cookieMaker[COOKIE_NAME]=cookieString
93        #cookieMaker[COOKIE_NAME]["domain"]=TOKEN_DOMAIN
94        cookieMaker[COOKIE_NAME]["path"]="/"
95
96        # Use expiry time of zero to delete a cookie, or other time if used
97        if expiryTime==None:
98            expiryTime=endTimeString
99               
100        cookieMaker[COOKIE_NAME]["expires"]=expiryTime
101
102        # Set the cookie
103        print cookieMaker
104       
105        return cookieString
106       
107    def _getUsername(self, cookieString):
108        """
109        Returns username.
110        """
111        return cookieString.split(":")[0]
112       
113    def _getUserRoles(self, cookieString):
114        """
115        Returns user roles as a list.
116        """
117        return cookieString.split(":")[1].split(",") 
118
119    def _getExpiryTime(self, cookieString):
120        """
121        Returns expiry time as a float.
122        """
123        return float(cookieString.split(":")[-1])
124       
125    def _checkCookie(self):
126        """
127        Checks for a security cookie and returns the cookie string if valid.
128        """
129        cookieString=self._readCookie()
130        if cookieString:
131            expiryTime=self._getExpiryTime(cookieString)
132            now=time.time()
133           
134            if expiryTime>now:
135                # Update the cookie's expiry time
136                username=self._getUsername(cookieString)
137                userRoles=self._getUserRoles(cookieString)
138                cookieString=self._createCookie(username, userRoles)
139                return [cookieString, username, userRoles]
140            else:
141                return "Your log in has expired. Please log in again."
142           
143    def _readCookie(self):
144        """
145        Reads the content of current cookie.
146        """
147        cookieReader=Cookie.SimpleCookie()
148        if not os.environ.has_key("HTTP_COOKIE"):
149            cookieString=None
150        else:
151            cookieReader.load(os.environ["HTTP_COOKIE"])
152            try:
153                cookieString=cookieReader[COOKIE_NAME].value       
154            except:
155                cookieString=None
156        return cookieString   
157       
158    def logout(self):
159        """
160        Logs user out by destroying cookie (setting expiry time to ZERO!).
161        """
162        cookieDestroyer=Cookie.SimpleCookie()
163        expiryTime=0
164        self._createCookie("rubbish", ["non", "sense"], expiryTime)
165
166   
Note: See TracBrowser for help on using the repository browser.