source: TI03-DataExtractor/branches/old_stuff/dx_badc/security.py @ 793

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

Put all the old code in the old_stuff branch.

  • Property svn:executable set to *
Line 
1#!/usr/bin/env python
2
3"""
4security.py
5=========
6
7A quick version of the Weblogon.pm perl module used for BADC security.
8
9"""
10
11# Import python standard library modules
12import commands
13import string
14import os, sys, re
15import time
16import cgi
17import Cookie
18import struct
19import random
20import crypt
21
22# Import dx modules
23import accountUtils
24
25# Set global variables
26BADCID_COOKIE_NAME = "badcid"
27BADC_LOGIN_COOKIE_NAME = "BADC"
28expiryTime= 3600.   # expiry time in seconds
29
30log=open('LOG.txt', 'w')
31
32class Security:
33
34    def __init__(self, args={}):
35         self.loginStatus=None
36         self.args=args
37         self.hiddenArgs={}
38         self.cookie=None
39         self.username=None
40         self.password=None
41         for key in args.keys():
42             if key=="_home": 
43                 self.username=args[key]
44             elif key=="_gohome": 
45                 self.password=args[key] 
46             else:
47                 self.hiddenArgs[key]=args[key]
48
49
50    def checkValidUser(self, username=None, password=None):
51        if not username: username=self.username
52        if not password: password=self.password
53        #### NOTE: Does not yet deal with $ or " characters (and others?) in the perl string.
54        #perl_command="""%s ; print  AccountUtils::valid_pw("%s", "%s"); '""" % (perl_string, username, password)
55        #output=commands.getoutput(perl_command)
56        #if output=="": return None
57        #return int(output)
58        return accountUtils.checkPasswd(username, password)
59
60    def _encode(self, cookie_string):
61        remote_addr=os.environ["REMOTE_ADDR"]
62        PERL_ENCODER="/home/tornado/internal/badc/software/perllib/BADC/encode_badc_cookie"
63        encoded_string=commands.getoutput("%s %s %s" % (PERL_ENCODER, cookie_string, remote_addr)).strip() 
64        log.write("REMOTE_ADDR: %s\nCookie string: %s\nEncoded cookie: %s\n" % (remote_addr, cookie_string, encoded_string))
65        log.flush()
66        return encoded_string
67
68    def _decode(self, cookie_string):
69        remote_addr=os.environ["REMOTE_ADDR"]
70        PERL_DECODER="/home/tornado/internal/badc/software/perllib/BADC/decode_badc_cookie"
71        decoded_string=commands.getoutput("%s %s %s" % (PERL_DECODER, cookie_string, remote_addr)).strip()
72        log.write("REMOTE_ADDR: %s\nCookie string: %s\nDecoded cookie: %s\n" % (remote_addr, cookie_string, decoded_string))
73        log.flush()
74        return decoded_string
75       
76    def _readCookie(self):
77        cookie = Cookie.Cookie()
78        return cookie.load(os.environ["HTTP_COOKIE"])
79
80
81    def _setCookie(self, username, groups):
82        cookie_string="%s+%s+%d" % (username, string.join(groups, ","), time.time()+expiryTime)
83        encoded_cookie=self._encode(cookie_string)
84        cookie = Cookie.Cookie()
85        cookie[BADC_LOGIN_COOKIE_NAME]=encoded_cookie
86        cookie[BADC_LOGIN_COOKIE_NAME]["domain"]="titania.badc.rl.ac.uk"
87        cookie[BADC_LOGIN_COOKIE_NAME]["path"]="/"
88        # Set the cookie
89        print cookie
90        log.write("cookie set as: %s\n Encoded cookie: %s\n" % (cookie, encoded_cookie))
91        log.flush()
92        return 1
93
94    def getGroups(self, username=None):
95        if not username: username=self.username
96        perl_command="""%s ; @groups=AccountUtils::get_groups("%s"); printf ("%%s " x @groups, @groups); '""" % (perl_string, username)
97        output=commands.getoutput(perl_command)
98        if output=="": return None
99        groups=string.split(output)
100        return groups
101
102    def login(self, error):
103          return self._printLoginPage(error)
104
105    def makeBADCIDCookie(self):
106        cookie=Cookie.Cookie()
107        cookie[BADC_LOGIN_COOKIE_NAME]=self.username
108        cookie[BADC_LOGIN_COOKIE_NAME]["domain"]="titania.badc.rl.ac.uk"
109        cookie[BADC_LOGIN_COOKIE_NAME]["path"]="/"
110        cookie[BADC_LOGIN_COOKIE_NAME]["expiry"]="20-Sep-2023"
111        print cookie
112        return 1
113
114    def _printLoginPage(self, error=None):
115        if os.environ.has_key("SCRIPT_NAME"):
116            script_name=os.environ["SCRIPT_NAME"]
117        else:
118            script_name=""
119        if os.environ.has_key("PATH_INFO"):
120            path_info=os.environ["PATH_INFO"]
121        else:
122            path_info=""
123
124        script_string=script_name+path_info
125
126        print """Content-Type: text/html
127Pragma: no-cache
128
129<HTML>
130<HEAD>
131<TITLE>BADC Login</TITLE>
132<SCRIPT LANGUAGE="JavaScript1.1">
133<!--
134function isblank(s)
135{
136  for (var i=0; i < s.length; i++){
137    var c=s.charAt(i)
138    if ((c != ' ') && (c = '\\n') && (c != '/t')) return false;
139  }
140  return true;
141}
142
143function check_logon(f)
144{
145  var empty_fields = 0;
146  var e = f._home;
147  if ((e.value == null) || (e.value == "") || isblank(e.value)) {
148      empty_fields ++;
149  }
150  e = f._gohome;
151  if ((e.value == null) || (e.value == "") || isblank(e.value)) {
152      empty_fields ++;
153  }
154  if (!empty_fields) return true;
155
156  alert("\\nLogin Invalid:\\nYou must complete both User name and Password\\n");
157  return false;
158}
159// -->
160</SCRIPT>
161"""
162
163        print """
164</HEAD>
165<BODY BGCOLOR=#FFFFFF onLoad="document.forms[0].elements[0].focus()">
166<H2><IMG SRC="/graphics/logos/badcsmall.gif" WIDTH="32" HEIGHT="32"
167ALIGN="RIGHT" ALT="BADC Logo" BORDER="0">Login to the BADC<BR clear=all></H2>
168<HR>
169<P>
170"""
171
172        if error:
173            print "%s <BR>\n" % error
174            print "<HR>\n"
175
176        cookie=Cookie.Cookie()
177        if cookie==None or not cookie.has_key(BADCID_COOKIE_NAME):
178            username=""
179        else:
180            username=cookie[BADCID_COOKIE_NAME].value
181
182        print """
183<FORM ACTION="%s" METHOD="POST"
184      onSubmit="return check_logon(this);">
185<TABLE BGCOLOR=#ADD8E6 cellspacing=0 border=0 cellpadding=5>
186<TR><TD>User Name:</TD> <TD><INPUT TYPE=text NAME=_home value="%s"> </TD></TR>
187<TR><TD>Password:</TD><TD><INPUT TYPE=password NAME=_gohome> </TD></TR>
188<TR><TD colspan=2> <INPUT TYPE=submit value="Login"></TD></TR>
189</TABLE>
190""" % (script_string, username)
191
192        for key in self.hiddenArgs.keys():
193            print """<INPUT TYPE="hidden" NAME="%s" VALUE="%s">\n""" % (key, self.hiddenArgs[key])
194
195
196        print """
197</FORM>
198<em>
199Problems logging on?
200Contact <a href="http://badc.nerc.ac.uk/help/contact.html">BADC support</a> for help.
201</em>
202<P>
203</body>
204</html>\n
205"""
206        return
207
208    def getUserID(self):
209        user=self.getProfile("username")
210        return user
211
212    def getProfile(self, option=None):
213        # Decode the cookie
214        cookies=Cookie.Cookie()
215        if not os.environ.has_key("HTTP_COOKIE"):
216            cookies=None
217        else:
218            cookies.load(os.environ["HTTP_COOKIE"])
219
220        cookie_validity="GOOD"
221        error_message=""
222
223        if cookies:
224            encoded_cookie_string=cookies[BADC_LOGIN_COOKIE_NAME].value
225            log.write("ENC_INNNNNNNNNN: %s\n" % encoded_cookie_string)
226            cookie_string=self._decode(encoded_cookie_string)
227            log.write("COOKIECCCCCCCCCCC: %s\n" % cookie_string);log.flush()
228            try:
229                (self.username, group_string, valid_time)=string.split(cookie_string, "+")
230                self.groups=group_string.split(",")
231                self._setCookie(self.username, self.groups)
232            except:
233                valid_time="0"
234
235            if (time.time()-int(valid_time))>0:
236                cookie_validity="EXPIRED"
237                error_message="<P>Sorry you have been inactive on a BADC " \
238                     "restricted web resource for too long. " \
239                     "Please login again.</P>\n"
240
241        if cookies==None or not cookies.has_key(BADC_LOGIN_COOKIE_NAME) or cookie_validity=="EXPIRED":
242            if self.username and self.password:
243                rt=self.checkValidUser(self.username, self.password)
244                if rt==None: 
245                    return self.login(error_message)
246                else:
247                    self.groups=accountUtils.getUserGroups(self.username)
248                    log.write("GROUPS info: %s, %s\n" % (self.groups, type(self.groups)))
249                    log.flush()
250                self._setCookie(self.username, self.groups)
251            else:
252                return self.login(error_message)
253
254        if not option:
255             return (self.username, self.groups)
256        elif option=="username":
257             return self.username
258        elif option=="groups":
259             return self.groups
260
261    def getLoginStatus(self):
262        status=self.getProfile()
263        return status
264
265
266    def logout(self):
267        self._resetCookie()
268        self.loginStatus=None
269        if not os.environ.has_key("HTTP_COOKIE"):
270            cookies=None
271        else:
272            cookies.load(os.environ["HTTP_COOKIE"])
273        if cookies and cookies.has_key(BADC_LOGIN_COOKIE_NAME):
274            del cookies[BADC_LOGIN_COOKIE_NAME]
275
276        return 1         
277
278
279    def _resetCookie(self):
280        cookie = Cookie.Cookie()
281        cookie[BADC_LOGIN_COOKIE_NAME]="null"
282        cookie[BADC_LOGIN_COOKIE_NAME]["domain"]="titania.badc.rl.ac.uk"
283        cookie[BADC_LOGIN_COOKIE_NAME]["expires"]="Friday, 1-Jan-1999 00:00:00 GMT;"
284        cookie[BADC_LOGIN_COOKIE_NAME]["path"]="/\n"
285        # Set the cookie
286        print cookie
287        self.cookie=None
288        return 1
289
290
Note: See TracBrowser for help on using the repository browser.