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. if __name__ == '__main__':
  25. print(ldap_hash('coin'))
  26. def send_templated_email(subject, to, template_to_use, context, attachements, from_email=None):
  27. """
  28. Send a multialternative email based on html and optional txt template.
  29. """
  30. # Get default sender if not specified
  31. from_email = from_email if from_email else 'coin@illyse.org'
  32. # Ensure arrays when needed
  33. if not isinstance(to, list):
  34. to = [to]
  35. if not isinstance(attachements, list):
  36. attachements = [attachements]
  37. # If .html is specified in template name remove it
  38. if template_to_use.endswith('.html'):
  39. template_to_use = template_to_use[:-5]
  40. # Get html template, fail if not exists
  41. template_html = get_template('%s.html' % (template_to_use,))
  42. html_content = template_html.render(Context(context))
  43. # Try to get a txt version, convert from html to markdown style
  44. # (using html2text) if fail
  45. try:
  46. template_txt = get_template('%s.txt' % (template_to_use,))
  47. text_content = template_txt.render_to_string(Context(context))
  48. except TemplateDoesNotExist:
  49. text_content = html2text.html2text(html_content)
  50. # make multipart email default : text, alternative : html
  51. msg = EmailMultiAlternatives(subject, text_content, from_email, to)
  52. msg.attach_alternative(html_content, "text/html")
  53. # Set attachements
  54. for attachement in attachements:
  55. msg.attach_file(attachement)
  56. #Send email
  57. msg.send()
  58. def delete_selected(modeladmin, request, queryset):
  59. """Overrides QuerySet's delete() function to remove objects one by one
  60. so, that they are deleted in the LDAP (Redmine issue #195)."""
  61. for obj in queryset:
  62. obj.delete()
  63. delete_selected.short_description = "Supprimer tous les objets sélectionnés."