utils.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. from datetime import datetime, timedelta
  2. from importlib import import_module
  3. from django.conf import settings
  4. from django.http import Http404
  5. from django.urls import resolve, reverse
  6. from django.utils import html, timezone
  7. from django.utils.encoding import force_text
  8. MISAGO_SLUGIFY = getattr(settings, 'MISAGO_SLUGIFY', 'misago.core.slugify.default')
  9. def resolve_slugify(path):
  10. path_bits = path.split('.')
  11. module, name = '.'.join(path_bits[:-1]), path_bits[-1]
  12. try:
  13. return getattr(import_module(module), name)
  14. except AttributeError:
  15. raise ImportError("name {} not found in {} module".format(name, module))
  16. except ImportError:
  17. raise ImportError("module {} does not exist".format(module))
  18. slugify = resolve_slugify(MISAGO_SLUGIFY)
  19. def format_plaintext_for_html(string):
  20. return html.linebreaks(html.urlize(html.escape(string)))
  21. def encode_json_html(string):
  22. return string.replace('<', r'\u003C')
  23. """
  24. Turn ISO 8601 string into datetime object
  25. """
  26. ISO8601_FORMATS = (
  27. "%Y-%m-%dT%H:%M:%S",
  28. "%Y-%m-%dT%H:%M:%S.%f",
  29. )
  30. def parse_iso8601_string(value):
  31. value = force_text(value, strings_only=True).rstrip('Z')
  32. for format in ISO8601_FORMATS:
  33. try:
  34. parsed_value = datetime.strptime(value, format)
  35. break
  36. except ValueError:
  37. try:
  38. parsed_value = datetime.strptime(value[:-6], format)
  39. break
  40. except ValueError:
  41. pass
  42. else:
  43. raise ValueError('failed to hydrate the %s timestamp' % value)
  44. offset_str = value[-6:]
  45. if offset_str and offset_str[0] in ('-', '+'):
  46. tz_offset = timedelta(hours=int(offset_str[1:3]), minutes=int(offset_str[4:6]))
  47. tz_offset = tz_offset.seconds // 60
  48. if offset_str[0] == '-':
  49. tz_offset *= -1
  50. else:
  51. tz_offset = 0
  52. tz_correction = timezone.get_fixed_timezone(tz_offset)
  53. return timezone.make_aware(parsed_value, tz_correction)
  54. """
  55. Mark request as having sensitive parameters
  56. We can't use decorator because of DRF uses custom HttpRequest
  57. that is incompatibile with Django's decorator
  58. """
  59. def hide_post_parameters(request):
  60. request.sensitive_post_parameters = '__ALL__'
  61. """
  62. Return path utility
  63. """
  64. def clean_return_path(request):
  65. if request.method == 'POST' and 'return_path' in request.POST:
  66. return _get_return_path_from_post(request)
  67. else:
  68. return _get_return_path_from_referer(request)
  69. def _get_return_path_from_post(request):
  70. return_path = request.POST.get('return_path')
  71. try:
  72. if not return_path:
  73. raise ValueError()
  74. if not return_path.startswith('/'):
  75. raise ValueError()
  76. resolve(return_path)
  77. return return_path
  78. except (Http404, ValueError):
  79. return None
  80. def _get_return_path_from_referer(request):
  81. referer = request.META.get('HTTP_REFERER')
  82. try:
  83. if not referer:
  84. raise ValueError()
  85. if not referer.startswith(request.scheme):
  86. raise ValueError()
  87. referer = referer[len(request.scheme) + 3:]
  88. if not referer.startswith(request.META['HTTP_HOST']):
  89. raise ValueError()
  90. referer = referer[len(request.META['HTTP_HOST'].rstrip('/')):]
  91. if not referer.startswith('/'):
  92. raise ValueError()
  93. resolve(referer)
  94. return referer
  95. except (Http404, KeyError, ValueError):
  96. return None
  97. """
  98. Utils for resolving requests destination
  99. """
  100. def _is_request_path_under_misago(request):
  101. # We are assuming that forum_index link is root of all Misago links
  102. forum_index = reverse('misago:index')
  103. path_info = request.path_info
  104. if len(forum_index) > len(path_info):
  105. return False
  106. return path_info[:len(forum_index)] == forum_index
  107. def is_request_to_misago(request):
  108. try:
  109. return request._request_to_misago
  110. except AttributeError:
  111. request._request_to_misago = _is_request_path_under_misago(request)
  112. return request._request_to_misago
  113. def is_referer_local(request):
  114. referer = request.META.get('HTTP_REFERER')
  115. if not referer:
  116. return False
  117. if not referer.startswith(request.scheme):
  118. return False
  119. referer = referer[len(request.scheme) + 3:]
  120. if not referer.startswith(request.META['HTTP_HOST']):
  121. return False
  122. referer = referer[len(request.META['HTTP_HOST'].rstrip('/')):]
  123. if not referer.startswith('/'):
  124. return False
  125. return True