1 #!/usr/bin/env python 2 3 "An example login screen." 4 5 import WebStack.Generic 6 import md5 7 8 class LoginResource: 9 10 "A resource providing a login screen." 11 12 def __init__(self, authenticator): 13 14 "Initialise the resource with an 'authenticator'." 15 16 self.authenticator = authenticator 17 18 def respond(self, trans): 19 20 fields = trans.get_fields_from_body() 21 redirect = "" 22 23 if fields.has_key("redirect"): 24 redirects = fields["redirect"] 25 redirect = redirects[0] 26 if self.authenticator.authenticate(trans): 27 trans.set_header_value("Location", redirect) 28 trans.set_response_code(307) 29 return 30 else: 31 fields = trans.get_fields_from_path() 32 if fields.has_key("redirect"): 33 redirects = fields["redirect"] 34 redirect = redirects[0] 35 36 # When authentication fails or is yet to take place, show the login 37 # screen. 38 39 out = trans.get_response_stream() 40 out.write(""" 41 <html> 42 <head> 43 <title>Login Example</title> 44 </head> 45 <body> 46 <h1>Login</h1> 47 <form method="POST"> 48 <p>Username: <input name="username" type="text" size="12"/></p> 49 <p>Password: <input name="password" type="text" size="12"/></p> 50 <p><input name="login" type="submit" value="Login"/></p> 51 <input name="redirect" type="hidden" value="%s"/> 52 </form> 53 </body> 54 </html> 55 """ % redirect) 56 57 class LoginAuthenticator: 58 59 def __init__(self, secret_key, credentials, cookie_name=None): 60 61 """ 62 Initialise the authenticator with a 'secret_key', the authenticator's registry of 63 'credentials' and an optional 'cookie_name'. 64 65 The 'credentials' must be an object which supports tests of the form 66 '(username, password) in credentials'. 67 """ 68 69 self.secret_key = secret_key 70 self.credentials = credentials 71 self.cookie_name = cookie_name or "LoginAuthenticator" 72 73 def authenticate(self, trans): 74 75 # Process any supplied parameters. 76 77 fields = trans.get_fields_from_body() 78 79 if fields.has_key("username") and fields.has_key("password"): 80 usernames, passwords = fields["username"], fields["password"] 81 82 # Insist on only one username and password. 83 84 if len(usernames) == 1 and len(passwords) == 1: 85 username, password = usernames[0], passwords[0] 86 87 # Check against the class's credentials. 88 89 if (username, password) in self.credentials: 90 91 # Make a special cookie token. 92 # NOTE: This should be moved into a common library. 93 94 trans.set_cookie_value( 95 self.cookie_name, 96 username + ":" + md5.md5(username + self.secret_key).hexdigest() 97 ) 98 99 return 1 100 101 return 0 102 103 # vim: tabstop=4 expandtab shiftwidth=4