source: TI12-security/tags/ndg-security-1.5/Tests/xDomainCredsTransfer.py @ 4855

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/tags/ndg-security-1.5/Tests/xDomainCredsTransfer.py@6610
Revision 4855, 9.9 KB checked in by pjkersha, 11 years ago (diff)
  • Got rid of additional refs to Q Public licence in headers
  • Added ndg.security.server.wsgi.openid.relyingparty package and started OpenIDRelyingPartyMiddleware wrapper to AuthKit?
  • fixed classfactory import bug
  • tested Attribute Authority over SSL with mod_wsgi with AA and SM client unit tests
  • Property svn:executable set to *
Line 
1#!/usr/bin/env python
2
3"""NDG Security CGI test program for passing cookie info between domains
4
5NERC Data Grid Project
6
7P J Kershaw 23/05/06
8
9Copyright (C) 2009 Science and Technology Facilities Council
10
11"""
12
13from Cookie import SimpleCookie
14
15import sys
16import cgi
17import os
18import base64
19
20returnURI = 'https://glue.badc.rl.ac.uk/cgi-bin/xDomainCredsTransfer.py'
21__authorisationMethod = None
22
23def main(form=None):
24    if form is None:
25        form = cgi.FieldStorage()
26
27
28    if 'requestURI' in form:
29        # Request credentials from user's home site
30        requestCreds(form['requestURI'].value,
31                     returnURI,
32                     pageTitle='Going to user home site...',
33                     delayTime=3,
34                     redirectMsg=\
35        'Re-directing to home site to retrieve credentials...')
36
37    elif 'NDG-ID1' in form and 'NDG-ID2' in form:
38        # Receive credentials back from home site
39        receiveCredsResponse(form['NDG-ID1'].value, form['NDG-ID2'].value)
40
41    elif 'setCookie' in form and 'returnURI' in form:
42        # User has logged on at home site and a cookie is now to be set - next
43        # step is processCredsRequest() below
44        setCookie(returnURI=form['returnURI'].value)
45
46    elif 'returnURI' in form:
47        # Home site receives request from remote site for credentials and
48        # returns them
49        processCredsRequest(form['returnURI'].value,
50                            pageTitle='Home Site',
51                            delayTime=3,
52                            redirectMsg='Processing request from remote site...')
53    else:
54        showIdPsiteSelect()
55
56
57def requestCreds(requestURI,
58                 returnURI,
59                 pageTitle='',
60                 delayTime=0,
61                 redirectMsg=''):
62    """Request credentials from user's home site"""
63    output = """Content-type: text/html
64
65<html>
66<head>
67<title>%s</title>
68<meta http-equiv="REFRESH" content="%d; url=%s?returnURI=%s">
69</head>
70<body>
71%s
72</body>
73</html>""" % (pageTitle, delayTime, requestURI, returnURI, redirectMsg)
74    #sys.stderr.write(output)
75    print output
76
77
78def receiveCredsResponse(sessID, sessMgrURI):
79    """Remote site receives returned credentials and creates a new cookie for
80    its domain"""
81    setCookie(sessID, sessMgrURI)
82
83
84def processCredsRequest(returnURI, **returnCredsKwArgs):
85    """Receive request from remote site for credentials.  Process and return via
86    a redirect"""
87   
88    # Check for cookie in environment
89    if 'HTTP_COOKIE' in os.environ:
90        # Cookie is set - check for NDG cookie
91
92        # Get session ID from existing cookie
93        cookie = SimpleCookie(os.environ['HTTP_COOKIE'])
94        if "NDG-ID1" not in cookie:
95            raise Exception, 'Expecting "NDG-ID1" ID for session cookie'
96
97        if "NDG-ID2" not in cookie:
98            raise Exception, 'Expecting "NDG-ID2" ID for session cookie'
99
100        returnCreds(returnURI,
101                    cookie["NDG-ID1"].value,
102                    cookie["NDG-ID2"].value,
103                    **returnCredsKwArgs)
104    else:
105        # No cookie present - display login.  Submit must redirect back to
106        # sender
107        print """Content-type: text/html
108
109"""
110        showLogin(returnURI,
111                  setCookie=True,
112                  heading="Login",
113                  htmlTag=True,
114                  bodyTag=True)
115
116def returnCreds(returnURI,
117                sessID,
118                sessMgrURI,
119                pageTitle='',
120                delayTime=0,
121                redirectMsg=''):
122    """User's home site returns credentials to requestor"""
123
124    print """Content-type: text/html
125
126<html>
127<head>
128<title>%s</title>
129<meta http-equiv="REFRESH" content="%d; url=%s?NDG-ID1=%s&NDG-ID2=%s">
130</head>
131<body>
132%s
133</body>
134</html>""" % (pageTitle, delayTime, returnURI, sessID, sessMgrURI, redirectMsg)
135
136
137def setCookie(sessID=None, sessMgrURI=None, returnURI=None):
138    """Make NDG cookie"""
139
140    cookie = SimpleCookie()
141    if not sessID: sessID = base64.urlsafe_b64encode(os.urandom(128))
142    if not sessMgrURI: sessMgrURI = base64.urlsafe_b64encode(os.urandom(32))
143
144    cookie['NDG-ID1'] = sessID
145    cookie['NDG-ID1']['expires'] = "Tue, 13-12-2006 12:00:00 GMT"
146    cookie['NDG-ID2'] = sessMgrURI
147    cookie['NDG-ID2']['expires'] = "Tue, 13-12-2006 12:00:00 GMT"
148
149    if returnURI:
150        returnURIfield = """<meta http-equiv=\"REFRESH\"
151        content=\"0;url=./xDomainCredsTransfer.py?returnURI=%s\">""" % returnURI
152    else:
153        returnURIfield = ''
154
155    print "Content-type: text/html"
156    print cookie.output() + os.linesep + os.linesep
157    print """<html>
158<head>
159<title>Set Cookie</title>
160%s
161</head>
162
163<body>
164    <h1>Cookie set!</h1>
165</body>
166</html>""" % returnURIfield
167
168
169def showLogin(returnURI=None,
170              setCookie=False,
171              htmlTag=False,
172              heading=None,
173              bodyTag=False):
174    """Display initial NDG login form"""
175
176    if htmlTag: print "<html>"
177
178    if isinstance(heading, basestring):
179        print """<head>
180    <title>%s</title>
181    <style type=\"text/css\">
182    <!--
183    .al {
184    text-align: justify
185    }
186    a{
187    text-decoration:none;
188    }
189    a:hover{
190    color:#0000FF;
191    }
192        body { font-family: Verdana, sans-serif; font-size: 11}
193        table { font-family: Verdana, sans-serif; font-size: 11}
194    -->
195    </style>
196</head>""" % heading
197
198
199    if bodyTag: print "<body>"
200
201    if returnURI:
202        returnURIfield = "<input type=hidden name=returnURI value=\"%s\">" % \
203                                                                    returnURI
204    else:
205        returnURIfield = ''
206
207
208    if setCookie:
209        setCookieField = "<input type=hidden name=setCookie value=\"1\">"
210    else:
211        setCookieField = ''
212
213
214    bAuthorise=False
215    if bAuthorise:
216        authoriseArg = "<input type=hidden name=authorise value=\"1\">"
217    else:
218        authoriseArg = ""
219
220
221    # Set authorisation method default
222    authorisationMethodChk = { "allowMapping":              '',
223                            "allowMappingWithPrompt" :   '',
224                            "noMapping":                 ''}
225
226    if __authorisationMethod is None:
227        # Default to safest option for user
228        authorisationMethodChk["allowMappingWithPrompt"] = ' checked'
229    else:
230        authorisationMethodChk[__authorisationMethod] = ' checked'
231
232    print \
233"""<script language="javascript">
234<!--
235    function toggleLayer(layerId)
236    {
237        if (document.getElementById)
238        {
239            // Standard
240            var style = document.getElementById(layerId).style;
241        }
242        else if (document.all)
243        {
244            // Old msie versions
245            var style = document.all[whichLayer].style;
246        }
247        else if (document.layers)
248        {
249            // nn4
250            var style = document.layers[whichLayer].style;
251        }
252        style.visibility = style.visibility == "visible" ? "hidden":"visible";
253    }
254//-->
255</script>
256<h3>NERC Data Grid Site Login (Test)<BR clear=all></h3>
257<hr>
258
259<form action="./xDomainCredsTransfer.py" method="POST">
260
261<table bgcolor=#ADD8E6 cellspacing=0 border=0 cellpadding=5>
262<tbody>
263<tr><td>User Name:</td> <td><input type=text name=userName value="">
264</td></tr>
265<tr>
266    <td>Password:</td>
267    <td><input type=password name=passPhrase></td>
268</tr>
269<tr>
270    <td colspan="2" align="right">
271        <a href="javascript:toggleLayer('advSettings');">Advanced Settings</a>
272        <input type=submit value="Login">
273    </td>
274</tr>
275%s
276%s"""  % (returnURIfield, setCookieField)
277
278    print \
279"""</tbody></table>
280<br>
281<div id="advSettings" style="position: relative; visibility: hidden;">
282    <h4>Role Mapping for access to other trusted sites</h4>
283    <p>Your account has roles or <i>privileges</i> which determine what data you have access to.  If you access data at another NDG trusted site, these roles can be mapped to local roles at that site to help you gain access:
284    </p>
285    <table bgcolor=#ADD8E6 cellspacing=0 border=0 cellpadding=5>
286    <tbody>
287    <tr>
288    <td>
289        <input type="radio" name="authorisationMethod" value="allowMapping"%s>
290    </td>
291        <td>
292            Allow my roles to be mapped to local roles at other NDG trusted sites.
293        </td>
294    </tr>
295    <tr>
296        <td>
297            <input type="radio" name="authorisationMethod" value="allowMappingWithPrompt"%s>
298        </td>
299    <td>
300        Allow my roles to be mapped, but prompt me so that I may choose which roles to map before gaining access.
301    </td>
302    <tr>
303    <td>
304        <input type="radio" name="authorisationMethod" value="noMapping"%s>
305    </td>
306    <td>
307        Don't allow mapping of my roles.
308    </td>
309    </tr>
310    </tbody>
311    </table>
312</div>
313</form>
314""" % (authorisationMethodChk['allowMapping'], \
315       authorisationMethodChk['allowMappingWithPrompt'], \
316       authorisationMethodChk['noMapping'])
317
318    if bodyTag: print "</body>"
319    if htmlTag: print "</html>"
320
321    # end of showLogin()
322
323
324def showIdPsiteSelect(heading="NDG Home Site Select..."):
325
326    print """Content-type: text/html
327
328<html>
329<head>
330    <title>%s</title>
331    <style type=\"text/css\">
332    <!--
333    .al {
334    text-align: justify
335    }
336    a{
337    text-decoration:none;
338    }
339    a:hover{
340    color:#0000FF;
341    }
342        body { font-family: Verdana, sans-serif; font-size: 11}
343        table { font-family: Verdana, sans-serif; font-size: 11}
344    -->
345    </style>
346</head>""" % heading
347
348
349    print "<body>"
350    print \
351"""<h3>NERC Data Grid Home Site Select (Test)<BR clear=all></h3>
352<hr>
353
354<form action="./xDomainCredsTransfer.py" method="POST">
355<table bgcolor=#ADD8E6 cellspacing=0 border=0 cellpadding=5>
356<tbody>
357<tr>
358  <td>
359    <select name="requestURI">
360      <option value="">Select your home site...
361      <option value="https://glue.badc.rl.ac.uk/cgi-bin/xDomainCredsTransfer.py">BADC
362      <option value="https://gabriel.bnsc.rl.ac.uk/cgi-bin/xDomainCredsTransfer.py">Gabriel
363    </select>
364  </td>
365  <td align="right">
366    <input type=submit value="Go">
367  </td>
368</tr>
369</tbody>
370</table>
371</form>
372</body>
373</html>"""
374
375    # end of showIdPsiteSelect()
376
377if __name__ == "__main__":
378    main()
Note: See TracBrowser for help on using the repository browser.