utils.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import os
  4. import hashlib
  5. import binascii
  6. import base64
  7. import html2text
  8. import re
  9. from datetime import date, timedelta
  10. from django.core.mail import EmailMultiAlternatives
  11. from django.core.files.storage import FileSystemStorage
  12. from django.conf import settings
  13. from django.template.loader import get_template
  14. from django.template import Context, TemplateDoesNotExist
  15. from django.contrib.sites.models import Site
  16. # Stockage des fichiers privés (comme les factures par exemple)
  17. private_files_storage = FileSystemStorage(location=settings.PRIVATE_FILES_ROOT)
  18. # regexp which matches for ex irc://irc.example.tld/#channel
  19. re_chat_url = re.compile(r'(?P<protocol>\w+://)(?P<server>[\w\.]+)/(?P<channel>.*)')
  20. def str_or_none(obj):
  21. return str(obj) if obj else None
  22. def ldap_hash(password):
  23. """Hash a password for use with LDAP. If the password is already hashed,
  24. do nothing."""
  25. if password and not password.startswith('{SSHA}'):
  26. salt = binascii.hexlify(os.urandom(8))
  27. digest = hashlib.sha1(password.encode() + salt).digest()
  28. return '{SSHA}' + base64.b64encode(digest + salt).decode()
  29. else:
  30. return password
  31. def send_templated_email(to, subject_template, body_template, context={}, attachements=[]):
  32. """
  33. Send a multialternative email based on html and optional txt template.
  34. """
  35. # Ensure arrays when needed
  36. if not isinstance(to, list):
  37. to = [to]
  38. if not isinstance(attachements, list):
  39. attachements = [attachements]
  40. # Add domain in context
  41. context['domain'] = Site.objects.get_current()
  42. # If .html/.txt is specified in template name remove it
  43. body_template = body_template.split('.')[0]
  44. subject_template = subject_template.split('.')[0]
  45. # Get html template for body, fail if not exists
  46. template_html = get_template('%s.html' % (body_template,))
  47. html_content = template_html.render(Context(context))
  48. # Get txt template for subject, fail if not exists
  49. subject_template = get_template('%s.txt' % (subject_template,))
  50. subject = subject_template.render(Context(context))
  51. # Get rid of newlines
  52. subject = subject.strip().replace('\n', '')
  53. # Try to get a txt version, convert from html to markdown style
  54. # (using html2text) if fail
  55. try:
  56. template_txt = get_template('%s.txt' % (body_template,))
  57. text_content = template_txt.render_to_string(Context(context))
  58. except TemplateDoesNotExist:
  59. text_content = html2text.html2text(html_content)
  60. # make multipart email default : text, alternative : html
  61. msg = EmailMultiAlternatives(subject=subject, body=text_content, to=to)
  62. msg.attach_alternative(html_content, "text/html")
  63. # Set attachements
  64. for attachement in attachements:
  65. msg.attach_file(attachement)
  66. # Send email
  67. msg.send()
  68. def delete_selected(modeladmin, request, queryset):
  69. """Overrides QuerySet's delete() function to remove objects one by one
  70. so, that they are deleted in the LDAP (Redmine issue #195)."""
  71. for obj in queryset:
  72. obj.delete()
  73. delete_selected.short_description = "Supprimer tous les objets sélectionnés."
  74. # Time-related functions
  75. def in_one_year():
  76. return date.today() + timedelta(365)
  77. def start_of_month():
  78. return date(date.today().year, date.today().month, 1)
  79. def end_of_month():
  80. today = date.today()
  81. if today.month == 12:
  82. return date(today.year + 1, 1, 1) - timedelta(days=1)
  83. else:
  84. return date(today.year, today.month + 1, 1) - timedelta(days=1)
  85. if __name__ == '__main__':
  86. print(ldap_hash('coin'))