# HG changeset patch # User paulb # Date 1085696235 0 # Node ID 27406c9d5d813d5443c917ae0dddd014b82988be # Parent bd9989852fcc677ea801b8d49f5c038c4f3e7435 [project @ 2004-05-27 22:17:15 by paulb] Added an example login server. diff -r bd9989852fcc -r 27406c9d5d81 examples/Common/Login/__init__.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/Common/Login/__init__.py Thu May 27 22:17:15 2004 +0000 @@ -0,0 +1,100 @@ +#!/usr/bin/env python + +"An example login screen." + +import WebStack.Generic +import md5 + +class LoginResource: + + "A resource providing a login screen." + + def __init__(self, authenticator): + + "Initialise the resource with an 'authenticator'." + + self.authenticator = authenticator + + def respond(self, trans): + + fields = trans.get_fields_from_body() + redirect = "" + + if fields.has_key("redirect"): + redirects = fields["redirect"] + redirect = redirects[0] + if self.authenticator.authenticate(trans): + trans.set_header_value("Location", redirect) + trans.set_response_code(307) + return + else: + fields = trans.get_fields_from_path() + if fields.has_key("redirect"): + redirects = fields["redirect"] + redirect = redirects[0] + + # When authentication fails or is yet to take place, show the login + # screen. + + out = trans.get_response_stream() + out.write(""" + + + Login Example + + +

Login

+
+

Username:

+

Password:

+

+ +
+ + +""" % redirect) + +class LoginAuthenticator: + + credentials = ( + ("badger", "abc"), + ("vole", "xyz"), + ) + + def __init__(self, secret_key): + + "Initialise the authenticator with a 'secret_key'." + + self.secret_key = secret_key + + def authenticate(self, trans): + + # Process any supplied parameters. + + fields = trans.get_fields_from_body() + + if fields.has_key("username") and fields.has_key("password"): + usernames, passwords = fields["username"], fields["password"] + + # Insist on only one username and password. + + if len(usernames) == 1 and len(passwords) == 1: + username, password = usernames[0], passwords[0] + + # Check against the class's credentials. + + if (username, password) in self.credentials: + + # Make a special cookie token. + # NOTE: This should be moved into a common library. + + trans.set_cookie_value( + "LoginAuthenticator", + username + ":" + md5.md5(username + self.secret_key).hexdigest() + ) + + return 1 + + return 0 + +# vim: tabstop=4 expandtab shiftwidth=4