import typing from urllib.request import urlopen import urllib.parse as urlparse from urllib.parse import urlencode import tldextract from flask import request, current_app def get_public_key(): """Fetch public key from shared resource on the network.""" public_key = urlopen(current_app.config.get("PUBLIC_KEY_URL")) # nosec public_key = public_key.read() key = public_key.decode() return key def get_allowed_root_domain() -> typing.Optional[str]: """Returns allowed root domain to set cookie or None.""" root_domain = tldextract.extract(request.host).registered_domain if root_domain and request.host in current_app.config.get("ALLOWED_HOSTS"): return f".{root_domain}" return None def add_url_params(url: str, params: dict) -> str: """Extends params in given url.""" url_parts = list(urlparse.urlparse(url)) query = dict(urlparse.parse_qsl(url_parts[4])) query.update(params) url_parts[4] = urlencode(query) return urlparse.urlunparse(url_parts) def get_safe_repr(token: str) -> str: """ Returns 10 chars from signature part of the token string or 10 chars from other string. """ if not token: return "" parts = token.split(".") if len(parts) == 3: return f"{parts[2][:10]}**" return f"{token[:10]}**"