utils.py 2.7 KB

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