1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/examples/Common/Login/__init__.py Thu May 27 22:17:15 2004 +0000
1.3 @@ -0,0 +1,100 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"An example login screen."
1.7 +
1.8 +import WebStack.Generic
1.9 +import md5
1.10 +
1.11 +class LoginResource:
1.12 +
1.13 + "A resource providing a login screen."
1.14 +
1.15 + def __init__(self, authenticator):
1.16 +
1.17 + "Initialise the resource with an 'authenticator'."
1.18 +
1.19 + self.authenticator = authenticator
1.20 +
1.21 + def respond(self, trans):
1.22 +
1.23 + fields = trans.get_fields_from_body()
1.24 + redirect = ""
1.25 +
1.26 + if fields.has_key("redirect"):
1.27 + redirects = fields["redirect"]
1.28 + redirect = redirects[0]
1.29 + if self.authenticator.authenticate(trans):
1.30 + trans.set_header_value("Location", redirect)
1.31 + trans.set_response_code(307)
1.32 + return
1.33 + else:
1.34 + fields = trans.get_fields_from_path()
1.35 + if fields.has_key("redirect"):
1.36 + redirects = fields["redirect"]
1.37 + redirect = redirects[0]
1.38 +
1.39 + # When authentication fails or is yet to take place, show the login
1.40 + # screen.
1.41 +
1.42 + out = trans.get_response_stream()
1.43 + out.write("""
1.44 +<html>
1.45 + <head>
1.46 + <title>Login Example</title>
1.47 + </head>
1.48 + <body>
1.49 + <h1>Login</h1>
1.50 + <form method="POST">
1.51 + <p>Username: <input name="username" type="text" size="12"/></p>
1.52 + <p>Password: <input name="password" type="text" size="12"/></p>
1.53 + <p><input name="login" type="submit" value="Login"/></p>
1.54 + <input name="redirect" type="hidden" value="%s"/>
1.55 + </form>
1.56 + </body>
1.57 +</html>
1.58 +""" % redirect)
1.59 +
1.60 +class LoginAuthenticator:
1.61 +
1.62 + credentials = (
1.63 + ("badger", "abc"),
1.64 + ("vole", "xyz"),
1.65 + )
1.66 +
1.67 + def __init__(self, secret_key):
1.68 +
1.69 + "Initialise the authenticator with a 'secret_key'."
1.70 +
1.71 + self.secret_key = secret_key
1.72 +
1.73 + def authenticate(self, trans):
1.74 +
1.75 + # Process any supplied parameters.
1.76 +
1.77 + fields = trans.get_fields_from_body()
1.78 +
1.79 + if fields.has_key("username") and fields.has_key("password"):
1.80 + usernames, passwords = fields["username"], fields["password"]
1.81 +
1.82 + # Insist on only one username and password.
1.83 +
1.84 + if len(usernames) == 1 and len(passwords) == 1:
1.85 + username, password = usernames[0], passwords[0]
1.86 +
1.87 + # Check against the class's credentials.
1.88 +
1.89 + if (username, password) in self.credentials:
1.90 +
1.91 + # Make a special cookie token.
1.92 + # NOTE: This should be moved into a common library.
1.93 +
1.94 + trans.set_cookie_value(
1.95 + "LoginAuthenticator",
1.96 + username + ":" + md5.md5(username + self.secret_key).hexdigest()
1.97 + )
1.98 +
1.99 + return 1
1.100 +
1.101 + return 0
1.102 +
1.103 +# vim: tabstop=4 expandtab shiftwidth=4