utils.py 4.4 KB

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