utils.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import hashlib
  4. import binascii
  5. import base64
  6. import html2text
  7. from django.core.mail import EmailMultiAlternatives
  8. from django.template import TemplateDoesNotExist
  9. def str_or_none(obj):
  10. return str(obj) if obj else None
  11. def ldap_hash(password):
  12. """Hash a password for use with LDAP. If the password is already hashed,
  13. do nothing."""
  14. if password and not password.startswith('{SSHA}'):
  15. salt = binascii.hexlify(os.urandom(8))
  16. digest = hashlib.sha1(password.encode() + salt).digest()
  17. return '{SSHA}' + base64.b64encode(digest + salt).decode()
  18. else:
  19. return password
  20. if __name__ == '__main__':
  21. print(ldap_hash('coin'))
  22. def send_templated_email(subject, to, template_to_use, context, attachements, from_email=None):
  23. """
  24. Send a multialternative email based on html and optional txt template.
  25. """
  26. # Get default sender if not specified
  27. from_email = from_email if from_email else 'coin@illyse.org'
  28. # Ensure arrays when needed
  29. if not isinstance(to, list):
  30. to = [to]
  31. if not isinstance(attachements, list):
  32. attachements = [attachements]
  33. # If .html is specified in template name remove it
  34. if template_to_use.endswith('.html'):
  35. template_to_use = template_to_use[:-5]
  36. # Get html template, fail if not exists
  37. template_html = get_template('%s.html' % (template_to_use,))
  38. html_content = template_html.render(Context(context))
  39. # Try to get a txt version, convert from html to markdown style
  40. # (using html2text) if fail
  41. try:
  42. template_txt = get_template('%s.txt' % (template_to_use,))
  43. text_content = template_txt.render_to_string(Context(context))
  44. except TemplateDoesNotExist:
  45. text_content = html2text.html2text(html_content)
  46. # make multipart email default : text, alternative : html
  47. msg = EmailMultiAlternatives(subject, text_content, from_email, to)
  48. msg.attach_alternative(html_content, "text/html")
  49. # Set attachements
  50. for attachement in attachements:
  51. msg.attach_file(attachement)
  52. #Send email
  53. msg.send()
  54. def delete_atomic(modeladmin, request, queryset):
  55. """Overrides QuerySet's delete() function to remove objects one by one
  56. so, that they are deleted in the LDAP (Redmine issue #195)."""
  57. for obj in queryset:
  58. obj.delete()