コード例 #1
0
    def authorize(self, client_address: tuple[str, int],
                  client_request: HTTPParser) -> Optional[HTTPResponse]:
        path = client_request.request_path
        secret = self.protected_paths[path]["secret"]
        timeout = self.protected_paths[path]["timeout"]
        prefix: str = self.protected_paths[path]["prefix"]
        if secret:
            # This path is token-protected
            if not path.startswith(prefix):
                # Incorrect prefix
                # FIXME: note that something is probably wrong with
                # the configuration here, we should probably log /
                # warn the admin
                return AUTH_FAILURE
            else:
                # Get rid of prefix and slashes
                path = path[len(prefix):].strip("/")
                if path.count("/") < 2:
                    # Not enough components to be a tokenised path
                    return AUTH_FAILURE
                # Split into token, timestamp, and path
                token, timestamp, path = path.split("/", 2)
                # Check the token is valid
                if token != hashlib.md5(secret + "/" + path +
                                        timestamp).hexdigest():
                    # Invalid token
                    return AUTH_FAILURE
                # Check the timeout is not expired, if needed
                if timeout and (int(time.time()) - timeout) > int(
                        timestamp, 16):
                    return AUTH_FAILURE

                # We have to remove the token and timestamp from the original
                # path or else the server won't find the correct handler
                # afterwards
                client_request.request_path = "/".join([prefix, path])
                return AUTH_SUCCESS

        return None