source: TI03-DataExtractor/branches/old_stuff/latest_dx/dx/pydxs/SecurityManager.py @ 793

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI03-DataExtractor/branches/old_stuff/latest_dx/dx/pydxs/SecurityManager.py@793
Revision 793, 4.1 KB checked in by astephen, 13 years ago (diff)

Put all the old code in the old_stuff branch.

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"""
6SecurityManager.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 SecurityManager class provides a hook
13to do this with.
14
15"""
16
17# Import python standard library modules
18import sys, os, string, time
19
20# Import local modules
21from serverConfig import TOKEN_VALID_LIFETIME
22
23class SecurityManager:
24    """
25    Security manager class - requires your code for implementation.
26    The basic version only gives an example of the types of
27    calls that might be used. Any real solution needs to hide
28    and encode/decode passwords and secure tokens.
29    The "secureToken" takes the form "username:role1,role2,role3...:expiryTime".
30    This can be used as the cookieString with the CGI client.
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
41    def validateUser(self):
42        """
43        Returns either an error string or  a tuple of (secureToken, knownRoles).
44        """
45        # First check if the user is valid via the secure token.
46        tokenCheck=self._checkSecureToken()
47
48        if type(tokenCheck)==type(""):
49            # Return an error string to report to main application
50            return tokenCheck
51        elif type(tokenCheck)==type([]):
52            # Return the valid secure token and user roles
53            (secureToken, userRoles)=tokenCheck
54            return [secureToken, userRoles]
55                       
56        # If no valid token then check if there is a valid username, password provided
57        knownUserPasswords={"rod":"rod1", "jane":"jane1", "freddie":"freddie1",
58                            "zippy":"zippy1"}
59        knownUserRoles={"rod":["dset1"],
60                    "jane":["dset1", "dset2", "dset3"],
61                    "freddie":["dset3"],
62                    "zippy":[]}
63        users=knownUserPasswords.keys()
64           
65        # Check if password given
66        if self.password==None:   return "Invalid login - no password given."
67
68        if self.username in users:
69            if self.password==knownUserPasswords[self.username]:
70                userRoles=knownUserRoles[self.username]
71                secureToken=self._createSecureToken(self.username, userRoles)
72                return [secureToken, userRoles]
73            else:
74                return "Invalid login."
75        else:
76            return "Username '%s' unknown." % self.username
77
78
79    def _createSecureToken(self, username, userRoles):
80        """
81        Creates the secure token string.
82        """
83        secureToken="%s:%s:%s" % (username, string.join(userRoles, ","), time.time()+TOKEN_VALID_LIFETIME)
84        return secureToken
85       
86    def _getUsername(self, secureToken):
87        """
88        Returns username.
89        """
90        return secureToken.split(":")[0]
91       
92    def _getUserRoles(self, secureToken):
93        """
94        Returns user roles as a list.
95        """
96        return secureToken.split(":")[1].split(",") 
97
98    def _getExpiryTime(self, secureToken):
99        """
100        Returns expiry time as a float.
101        """
102        return float(secureToken.split(":")[-1])
103       
104    def _checkSecureToken(self):
105        """
106        Checks for a secure token and returns the cookie string if valid.
107        """
108        if self.secureToken!=None:
109            expiryTime=self._getExpiryTime(self.secureToken)
110            now=time.time()
111           
112            if expiryTime>now:
113                # Update the secure token's expiry time
114                self.username=self._getUsername(self.secureToken)
115                userRoles=self._getUserRoles(self.secureToken)
116                secureToken=self._createSecureToken(self.username, userRoles)
117                return [secureToken, userRoles]
118            else:
119                return "Your log in has expired. Please log in again."
120   
Note: See TracBrowser for help on using the repository browser.