navigation.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. """Canonical page URLs for return navigation and authentication recovery."""
  2. import re
  3. from urllib.parse import parse_qsl, quote, unquote, urlencode, urlsplit
  4. from .dashboard_segment import parse_segment, segment_filters
  5. from .query_filter import import_filter_config
  6. LIST_PATH = "/app/forderungen/liste"
  7. DETAIL_PREFIX = "/app/forderungen/details/"
  8. DETAIL_PAGE = re.compile(r"^/app/forderungen/details/([^/]+)(?:/(?:kommentare|buchungen))?/?$")
  9. ASSIGNEE_MODAL = re.compile(r"^/app/forderungen/(liste|details)/([^/]+)/verursacher/?$")
  10. FOLLOW_UP_MODAL = re.compile(r"^/app/forderungen/liste/([^/]+)/wiedervorlage/?$")
  11. def valid_focus(value: str | None) -> bool:
  12. if not value or any(ord(c) < 32 or ord(c) == 127 or c in "/\\" for c in value):
  13. return False
  14. tenant, separator, number = value.partition("_")
  15. return bool(separator and tenant and number and len(tenant) <= 20 and len(number) <= 100)
  16. def _local_parts(value):
  17. if not isinstance(value, str) or not value.startswith("/") or value.startswith("//"):
  18. return None
  19. if any(ord(c) < 32 or ord(c) == 127 or c == "\\" for c in value):
  20. return None
  21. try:
  22. parts = urlsplit(value)
  23. except ValueError:
  24. return None
  25. decoded = unquote(parts.path)
  26. if parts.scheme or parts.netloc or decoded.startswith("//") or "\\" in decoded:
  27. return None
  28. if any(ord(c) < 32 or ord(c) == 127 for c in decoded):
  29. return None
  30. return parts
  31. def list_url(filters=None, focus: str | None = None) -> str:
  32. filters = filters or {}
  33. config = import_filter_config("forderungen")
  34. multi_fields = {f.name for f in config if f.filter_type in {"select", "text"}}
  35. params = {f.name: filters[f.name] for f in config if f.name in filters and filters[f.name] not in ("", None)}
  36. if filters.get("dashboard_segment"):
  37. try:
  38. params = {**segment_filters(parse_segment(filters["dashboard_segment"])), **params}
  39. except ValueError:
  40. pass # Untrusted return/login URLs must never carry malformed selections.
  41. if valid_focus(focus):
  42. params["focus"] = focus
  43. # Only separators remain literal; encoded commas inside values stay %252C.
  44. query = "&".join(
  45. urlencode({name: value}, safe="," if name in multi_fields else "") for name, value in params.items()
  46. )
  47. return LIST_PATH + ("?" + query if query else "")
  48. def list_return_url(value: str | None, primary_key: str) -> str:
  49. parts = _local_parts(value)
  50. filters = dict(parse_qsl(parts.query)) if parts and parts.path == LIST_PATH else {}
  51. return list_url(filters, primary_key)
  52. def _current_parts(value):
  53. """Extract context, never a redirect origin, from the browser's current URL."""
  54. if not value:
  55. return None
  56. try:
  57. parts = urlsplit(value)
  58. except ValueError:
  59. return None
  60. if parts.scheme and parts.scheme not in ("http", "https"):
  61. return None
  62. return _local_parts(parts.path + ("?" + parts.query if parts.query else ""))
  63. def return_url_for_request(request, primary_key: str, explicit: str | None = None) -> str:
  64. value = explicit if explicit is not None else request.query_params.get("return_to")
  65. if value is None:
  66. current = _current_parts(request.headers.get("HX-Current-URL"))
  67. match = DETAIL_PAGE.fullmatch(unquote(current.path)) if current else None
  68. if match and match[1] == primary_key:
  69. value = dict(parse_qsl(current.query)).get("return_to")
  70. return list_return_url(value, primary_key)
  71. def detail_navigation_context(request, primary_key: str, explicit: str | None = None) -> dict:
  72. return_url = return_url_for_request(request, primary_key, explicit)
  73. return {
  74. "return_url": return_url,
  75. "detail_post_url": DETAIL_PREFIX + quote(primary_key, safe="") + "?" + urlencode({"return_to": return_url}),
  76. }
  77. def normalize_page_url(value: str | None, default="/select", current_url: str | None = None) -> str:
  78. parts = _local_parts(value)
  79. if not parts:
  80. return default
  81. params = dict(parse_qsl(parts.query))
  82. current = _current_parts(current_url)
  83. follow_up = FOLLOW_UP_MODAL.fullmatch(unquote(parts.path))
  84. if follow_up and valid_focus(follow_up[1]):
  85. value = params.get("return_to")
  86. if value is None and current and current.path == LIST_PATH:
  87. value = current.path + ("?" + current.query if current.query else "")
  88. return list_return_url(value, follow_up[1])
  89. modal = ASSIGNEE_MODAL.fullmatch(unquote(parts.path))
  90. if modal and valid_focus(modal[2]):
  91. primary_key = modal[2]
  92. value = params.get("return_to")
  93. if modal[1] == "liste":
  94. if value is None and current and current.path == LIST_PATH:
  95. value = current.path + ("?" + current.query if current.query else "")
  96. return list_return_url(value, primary_key)
  97. if value is None and current:
  98. previous = DETAIL_PAGE.fullmatch(unquote(current.path))
  99. if previous and previous[1] == primary_key:
  100. value = dict(parse_qsl(current.query)).get("return_to")
  101. return (
  102. DETAIL_PREFIX
  103. + quote(primary_key, safe="")
  104. + "?"
  105. + urlencode({"return_to": list_return_url(value, primary_key)})
  106. )
  107. if parts.path == LIST_PATH:
  108. focus = params.get("focus")
  109. if not focus and current and current.path == LIST_PATH:
  110. previous = dict(parse_qsl(current.query))
  111. if list_url(params) == list_url(previous):
  112. focus = previous.get("focus")
  113. return list_url(params, focus)
  114. match = DETAIL_PAGE.fullmatch(unquote(parts.path))
  115. if match and valid_focus(match[1]):
  116. primary_key = match[1]
  117. value = params.get("return_to")
  118. if value is None and current:
  119. previous = DETAIL_PAGE.fullmatch(unquote(current.path))
  120. if previous and previous[1] == primary_key:
  121. value = dict(parse_qsl(current.query)).get("return_to")
  122. detail = DETAIL_PREFIX + quote(primary_key, safe="")
  123. return detail + ("?" + urlencode({"return_to": list_return_url(value, primary_key)}) if value else "")
  124. return parts.path + ("?" + parts.query if parts.query else "") + ("#" + parts.fragment if parts.fragment else "")