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 credentials = ( 60 ("badger", "abc"), 61 ("vole", "xyz"), 62 ) 63 64 def __init__(self, secret_key): 65 66 "Initialise the authenticator with a 'secret_key'." 67 68 self.secret_key = secret_key 69 70 def authenticate(self, trans): 71 72 # Process any supplied parameters. 73 74 fields = trans.get_fields_from_body() 75 76 if fields.has_key("username") and fields.has_key("password"): 77 usernames, passwords = fields["username"], fields["password"] 78 79 # Insist on only one username and password. 80 81 if len(usernames) == 1 and len(passwords) == 1: 82 username, password = usernames[0], passwords[0] 83 84 # Check against the class's credentials. 85 86 if (username, password) in self.credentials: 87 88 # Make a special cookie token. 89 # NOTE: This should be moved into a common library. 90 91 trans.set_cookie_value( 92 "LoginAuthenticator", 93 username + ":" + md5.md5(username + self.secret_key).hexdigest() 94 ) 95 96 return 1 97 98 return 0 99 100 # vim: tabstop=4 expandtab shiftwidth=4