1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/examples/Common/LoginRedirect/__init__.py Thu May 27 22:18:00 2004 +0000
1.3 @@ -0,0 +1,61 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"Login redirection."
1.7 +
1.8 +import md5
1.9 +
1.10 +class LoginRedirectResource:
1.11 +
1.12 + "A resource redirecting to a login URL."
1.13 +
1.14 + def __init__(self, login_url, app_url, resource, authenticator):
1.15 +
1.16 + """
1.17 + Initialise the resource with a 'login_url', an 'app_url' where the
1.18 + 'resource' for the application being protected should be reachable, and
1.19 + an 'authenticator'.
1.20 + """
1.21 +
1.22 + self.login_url = login_url
1.23 + self.app_url = app_url
1.24 + self.resource = resource
1.25 + self.authenticator = authenticator
1.26 +
1.27 + def respond(self, trans):
1.28 +
1.29 + # Check the authentication details with the specified authenticator.
1.30 +
1.31 + if self.authenticator.authenticate(trans):
1.32 + self.resource.respond(trans)
1.33 + else:
1.34 + # Redirect to the login URL.
1.35 +
1.36 + trans.set_header_value("Location", "%s?redirect=%s%s" % (self.login_url, self.app_url, trans.get_path()))
1.37 + trans.set_response_code(307)
1.38 +
1.39 +class LoginRedirectAuthenticator:
1.40 +
1.41 + """
1.42 + An authenticator which verifies the credentials provided in a special login cookie.
1.43 + """
1.44 +
1.45 + def __init__(self, secret_key):
1.46 +
1.47 + "Initialise the authenticator with a 'secret_key'."
1.48 +
1.49 + self.secret_key = secret_key
1.50 +
1.51 + def authenticate(self, trans):
1.52 + cookie = trans.get_cookie("LoginAuthenticator")
1.53 + if cookie is None:
1.54 + return 0
1.55 +
1.56 + # Test the token from the cookie against a recreated token using the
1.57 + # given information.
1.58 + # NOTE: This should be moved into a common library.
1.59 +
1.60 + username, code = cookie.value.split(":")
1.61 + print "*", username, code
1.62 + return code == md5.md5(username + self.secret_key).hexdigest()
1.63 +
1.64 +# vim: tabstop=4 expandtab shiftwidth=4