X-Git-Url: https://git.mar77i.info/?a=blobdiff_plain;f=hub%2Futils.py;h=d888f1588a19b74a65559a6869b54c3162762b7c;hb=f591748910835b1a11c3765723d9d30193a5bd26;hp=ae1fd1242684f692ccec08e4293fcaba6807214e;hpb=6128e895bc2a5da5fe645cc9a7ad74ac75af4f6b;p=hublib diff --git a/hub/utils.py b/hub/utils.py index ae1fd12..d888f15 100644 --- a/hub/utils.py +++ b/hub/utils.py @@ -1,36 +1,47 @@ -from base64 import urlsafe_b64encode -from hashlib import pbkdf2_hmac -from pathlib import Path - from jinja2_simple_tags import StandaloneTag +from .static import StaticTemplateFile, TreeFileApp class StaticTag(StandaloneTag): tags = {"static"} - def render(self, filename="/", hubapp=None): - if not hubapp: - hubapp = self.context["hubapp"] + @staticmethod + def get_hubapp( + static_file: StaticTemplateFile, hubapp: str | TreeFileApp | None + ) -> TreeFileApp: + h = static_file.hubapp + if hubapp == "root": + return h.root elif isinstance(hubapp, str): - hubapp = self.context["hubapp"].app.get_hubapp_by_name(hubapp) - return hubapp.uri_from(Path(filename)) - - -def scramble(secret, value): - if isinstance(value, str): - value = value.encode() - if isinstance(secret, str): - secret = secret.encode() - return urlsafe_b64encode( - pbkdf2_hmac("sha512", value, secret, 221100) - ).rstrip(b"=").decode("ascii") - - -def get_redis_pass(redis_conf): + return h.root.hubapps[hubapp] + elif isinstance(hubapp, TreeFileApp): + return hubapp + return static_file.hubapp + + def render( + self, filename: str = "", hubapp: str | TreeFileApp | None = None + ) -> str: + """ + If filename starts with '/', interpret the path as relative to hubapp.base_dir, + otherwise assume the path is relative to the current file. + """ + static_file = self.context["static_file"] + hubapp = self.get_hubapp(static_file, hubapp) + if filename.startswith("/") or hubapp != static_file.hubapp: + path = hubapp.base_dir / filename.lstrip("/") + else: + path = static_file.path.parent / filename + return hubapp.uri(path) + + +def get_redis_pass(redis_conf: str) -> str: + """ + Poor man's redis credentials: read the password from redis_conf. + Requires redis being configured with a `requirepass` password set. + """ prefix = "requirepass " with open(redis_conf, "rt") as fh: for line in fh: - if not line.startswith(prefix): - continue - return line[len(prefix) :].rstrip() - return None + if line.startswith(prefix): + return line[len(prefix) :].rstrip() + raise ValueError("No redis password found")