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