navigation.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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 .query_filter import import_filter_config
  5. from .dashboard_segment import parse_segment, pack_segment
  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. params = {f.name: filters[f.name] for f in import_filter_config('forderungen')
  34. if f.name in filters and filters[f.name] not in ('', None)}
  35. if filters.get('dashboard_segment'):
  36. try:
  37. params['dashboard_segment'] = pack_segment(parse_segment(filters['dashboard_segment']))
  38. except ValueError:
  39. pass # Untrusted return/login URLs must never carry malformed selections.
  40. if valid_focus(focus):
  41. params['focus'] = focus
  42. return LIST_PATH + ('?' + urlencode(params) if params else '')
  43. def list_return_url(value: str | None, primary_key: str) -> str:
  44. parts = _local_parts(value)
  45. filters = dict(parse_qsl(parts.query)) if parts and parts.path == LIST_PATH else {}
  46. return list_url(filters, primary_key)
  47. def _current_parts(value):
  48. """Extract context, never a redirect origin, from the browser's current URL."""
  49. if not value:
  50. return None
  51. try:
  52. parts = urlsplit(value)
  53. except ValueError:
  54. return None
  55. if parts.scheme and parts.scheme not in ('http', 'https'):
  56. return None
  57. return _local_parts(parts.path + ('?' + parts.query if parts.query else ''))
  58. def return_url_for_request(request, primary_key: str, explicit: str | None = None) -> str:
  59. value = explicit if explicit is not None else request.query_params.get('return_to')
  60. if value is None:
  61. current = _current_parts(request.headers.get('HX-Current-URL'))
  62. match = DETAIL_PAGE.fullmatch(unquote(current.path)) if current else None
  63. if match and match[1] == primary_key:
  64. value = dict(parse_qsl(current.query)).get('return_to')
  65. return list_return_url(value, primary_key)
  66. def detail_navigation_context(request, primary_key: str, explicit: str | None = None) -> dict:
  67. return_url = return_url_for_request(request, primary_key, explicit)
  68. return {
  69. 'return_url': return_url,
  70. 'detail_post_url': DETAIL_PREFIX + quote(primary_key, safe='') + '?' + urlencode({'return_to': return_url}),
  71. }
  72. def normalize_page_url(value: str | None, default='/select', current_url: str | None = None) -> str:
  73. parts = _local_parts(value)
  74. if not parts:
  75. return default
  76. params = dict(parse_qsl(parts.query))
  77. current = _current_parts(current_url)
  78. follow_up = FOLLOW_UP_MODAL.fullmatch(unquote(parts.path))
  79. if follow_up and valid_focus(follow_up[1]):
  80. value = params.get('return_to')
  81. if value is None and current and current.path == LIST_PATH:
  82. value = current.path + ('?' + current.query if current.query else '')
  83. return list_return_url(value, follow_up[1])
  84. modal = ASSIGNEE_MODAL.fullmatch(unquote(parts.path))
  85. if modal and valid_focus(modal[2]):
  86. primary_key = modal[2]
  87. value = params.get('return_to')
  88. if modal[1] == 'liste':
  89. if value is None and current and current.path == LIST_PATH:
  90. value = current.path + ('?' + current.query if current.query else '')
  91. return list_return_url(value, primary_key)
  92. if value is None and current:
  93. previous = DETAIL_PAGE.fullmatch(unquote(current.path))
  94. if previous and previous[1] == primary_key:
  95. value = dict(parse_qsl(current.query)).get('return_to')
  96. return DETAIL_PREFIX + quote(primary_key, safe='') + '?' + urlencode({'return_to': list_return_url(value, primary_key)})
  97. if parts.path == LIST_PATH:
  98. focus = params.get('focus')
  99. if not focus and current and current.path == LIST_PATH:
  100. previous = dict(parse_qsl(current.query))
  101. if list_url(params) == list_url(previous):
  102. focus = previous.get('focus')
  103. return list_url(params, focus)
  104. match = DETAIL_PAGE.fullmatch(unquote(parts.path))
  105. if match and valid_focus(match[1]):
  106. primary_key = match[1]
  107. value = params.get('return_to')
  108. if value is None and current:
  109. previous = DETAIL_PAGE.fullmatch(unquote(current.path))
  110. if previous and previous[1] == primary_key:
  111. value = dict(parse_qsl(current.query)).get('return_to')
  112. detail = DETAIL_PREFIX + quote(primary_key, safe='')
  113. return detail + ('?' + urlencode({'return_to': list_return_url(value, primary_key)}) if value else '')
  114. return parts.path + ('?' + parts.query if parts.query else '') + ('#' + parts.fragment if parts.fragment else '')