utils.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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 = ("%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M:%S.%f", )
  27. def parse_iso8601_string(value):
  28. value = force_text(value, strings_only=True).rstrip('Z')
  29. for format in ISO8601_FORMATS:
  30. try:
  31. parsed_value = datetime.strptime(value, format)
  32. break
  33. except ValueError:
  34. try:
  35. parsed_value = datetime.strptime(value[:-6], format)
  36. break
  37. except ValueError:
  38. pass
  39. else:
  40. raise ValueError('failed to hydrate the %s timestamp' % value)
  41. offset_str = value[-6:]
  42. if offset_str and offset_str[0] in ('-', '+'):
  43. tz_offset = timedelta(hours=int(offset_str[1:3]), minutes=int(offset_str[4:6]))
  44. tz_offset = tz_offset.seconds // 60
  45. if offset_str[0] == '-':
  46. tz_offset *= -1
  47. else:
  48. tz_offset = 0
  49. tz_correction = timezone.get_fixed_timezone(tz_offset)
  50. return timezone.make_aware(parsed_value, tz_correction)
  51. """
  52. Mark request as having sensitive parameters
  53. We can't use decorator because of DRF uses custom HttpRequest
  54. that is incompatibile with Django's decorator
  55. """
  56. def hide_post_parameters(request):
  57. request.sensitive_post_parameters = '__ALL__'
  58. """
  59. Return path utility
  60. """
  61. def clean_return_path(request):
  62. if request.method == 'POST' and 'return_path' in request.POST:
  63. return _get_return_path_from_post(request)
  64. else:
  65. return _get_return_path_from_referer(request)
  66. def _get_return_path_from_post(request):
  67. return_path = request.POST.get('return_path')
  68. try:
  69. if not return_path:
  70. raise ValueError()
  71. if not return_path.startswith('/'):
  72. raise ValueError()
  73. resolve(return_path)
  74. return return_path
  75. except (Http404, ValueError):
  76. return None
  77. def _get_return_path_from_referer(request):
  78. referer = request.META.get('HTTP_REFERER')
  79. try:
  80. if not referer:
  81. raise ValueError()
  82. if not referer.startswith(request.scheme):
  83. raise ValueError()
  84. referer = referer[len(request.scheme) + 3:]
  85. if not referer.startswith(request.META['HTTP_HOST']):
  86. raise ValueError()
  87. referer = referer[len(request.META['HTTP_HOST'].rstrip('/')):]
  88. if not referer.startswith('/'):
  89. raise ValueError()
  90. resolve(referer)
  91. return referer
  92. except (Http404, KeyError, ValueError):
  93. return None
  94. """
  95. Utils for resolving requests destination
  96. """
  97. def _is_request_path_under_misago(request):
  98. # We are assuming that forum_index link is root of all Misago links
  99. forum_index = reverse('misago:index')
  100. path_info = request.path_info
  101. if len(forum_index) > len(path_info):
  102. return False
  103. return path_info[:len(forum_index)] == forum_index
  104. def is_request_to_misago(request):
  105. try:
  106. return request._request_to_misago
  107. except AttributeError:
  108. request._request_to_misago = _is_request_path_under_misago(request)
  109. return request._request_to_misago
  110. def is_referer_local(request):
  111. referer = request.META.get('HTTP_REFERER')
  112. if not referer:
  113. return False
  114. if not referer.startswith(request.scheme):
  115. return False
  116. referer = referer[len(request.scheme) + 3:]
  117. if not referer.startswith(request.META['HTTP_HOST']):
  118. return False
  119. referer = referer[len(request.META['HTTP_HOST'].rstrip('/')):]
  120. if not referer.startswith('/'):
  121. return False
  122. return True