paulb@127 | 1 | #!/usr/bin/env python |
paulb@127 | 2 | |
paulb@127 | 3 | "Login redirection." |
paulb@127 | 4 | |
paulb@127 | 5 | import md5 |
paulb@127 | 6 | |
paulb@127 | 7 | class LoginRedirectResource: |
paulb@127 | 8 | |
paulb@127 | 9 | "A resource redirecting to a login URL." |
paulb@127 | 10 | |
paulb@127 | 11 | def __init__(self, login_url, app_url, resource, authenticator): |
paulb@127 | 12 | |
paulb@127 | 13 | """ |
paulb@127 | 14 | Initialise the resource with a 'login_url', an 'app_url' where the |
paulb@127 | 15 | 'resource' for the application being protected should be reachable, and |
paulb@127 | 16 | an 'authenticator'. |
paulb@127 | 17 | """ |
paulb@127 | 18 | |
paulb@127 | 19 | self.login_url = login_url |
paulb@127 | 20 | self.app_url = app_url |
paulb@127 | 21 | self.resource = resource |
paulb@127 | 22 | self.authenticator = authenticator |
paulb@127 | 23 | |
paulb@127 | 24 | def respond(self, trans): |
paulb@127 | 25 | |
paulb@127 | 26 | # Check the authentication details with the specified authenticator. |
paulb@127 | 27 | |
paulb@127 | 28 | if self.authenticator.authenticate(trans): |
paulb@127 | 29 | self.resource.respond(trans) |
paulb@127 | 30 | else: |
paulb@127 | 31 | # Redirect to the login URL. |
paulb@127 | 32 | |
paulb@127 | 33 | trans.set_header_value("Location", "%s?redirect=%s%s" % (self.login_url, self.app_url, trans.get_path())) |
paulb@127 | 34 | trans.set_response_code(307) |
paulb@127 | 35 | |
paulb@127 | 36 | class LoginRedirectAuthenticator: |
paulb@127 | 37 | |
paulb@127 | 38 | """ |
paulb@127 | 39 | An authenticator which verifies the credentials provided in a special login cookie. |
paulb@127 | 40 | """ |
paulb@127 | 41 | |
paulb@127 | 42 | def __init__(self, secret_key): |
paulb@127 | 43 | |
paulb@127 | 44 | "Initialise the authenticator with a 'secret_key'." |
paulb@127 | 45 | |
paulb@127 | 46 | self.secret_key = secret_key |
paulb@127 | 47 | |
paulb@127 | 48 | def authenticate(self, trans): |
paulb@127 | 49 | cookie = trans.get_cookie("LoginAuthenticator") |
paulb@127 | 50 | if cookie is None: |
paulb@127 | 51 | return 0 |
paulb@127 | 52 | |
paulb@127 | 53 | # Test the token from the cookie against a recreated token using the |
paulb@127 | 54 | # given information. |
paulb@127 | 55 | # NOTE: This should be moved into a common library. |
paulb@127 | 56 | |
paulb@127 | 57 | username, code = cookie.value.split(":") |
paulb@127 | 58 | print "*", username, code |
paulb@127 | 59 | return code == md5.md5(username + self.secret_key).hexdigest() |
paulb@127 | 60 | |
paulb@127 | 61 | # vim: tabstop=4 expandtab shiftwidth=4 |