From e59001b1b55824a2c6d807c4aa35db3b0ec223e0 Mon Sep 17 00:00:00 2001
From: Yohann D'ANELLO <yohann.danello@gmail.com>
Date: Sat, 25 Apr 2020 19:29:01 +0200
Subject: [PATCH] Send a mail to webmasters when an error occurs (in production
 mode)

---
 __init__.py |  4 ++++
 apps.py     | 14 ++++++++++++++
 signals.py  | 38 ++++++++++++++++++++++++++++++++++++++
 3 files changed, 56 insertions(+)
 create mode 100644 apps.py
 create mode 100644 signals.py

diff --git a/__init__.py b/__init__.py
index e69de29..94998f0 100644
--- a/__init__.py
+++ b/__init__.py
@@ -0,0 +1,4 @@
+# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+default_app_config = 'scripts.apps.ScriptsConfig'
diff --git a/apps.py b/apps.py
new file mode 100644
index 0000000..1b6a5d5
--- /dev/null
+++ b/apps.py
@@ -0,0 +1,14 @@
+# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+from django.apps import AppConfig
+from django.core.signals import got_request_exception
+
+
+class ScriptsConfig(AppConfig):
+    name = 'scripts'
+
+    def ready(self):
+        from . import signals
+        print("scripts are ready")
+        got_request_exception.connect(signals.send_mail_on_exception)
diff --git a/signals.py b/signals.py
new file mode 100644
index 0000000..124068d
--- /dev/null
+++ b/signals.py
@@ -0,0 +1,38 @@
+# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+import os
+import sys
+
+from django.conf import settings
+from django.core.mail import send_mail
+from django.template.loader import render_to_string
+from django.views.debug import ExceptionReporter
+
+
+def send_mail_on_exception(request, **kwargs):
+    """
+    When an error occurs on the Note Kfet, a mail is automatically sent to the webmasters.
+    """
+
+    if settings.DEBUG:
+        # Don't need to send a mail in debug mode, errors are already displayed in console and in the response view.
+        return
+
+    try:
+        exc_info = sys.exc_info()
+        exc_type = exc_info[0]
+        exc = exc_info[1]
+        tb = exc_info[2]
+        reporter = ExceptionReporter(request=request, exc_type=exc_type, exc_value=exc, tb=tb)
+
+        note_sender = os.getenv("NOTE_MAIL", "notekfet@example.com")
+        webmaster = os.getenv("WEBMASTER_MAIL", "notekfet@example.com")
+
+        message = render_to_string('scripts/mail-error500.txt', context={"error": reporter.get_traceback_text()})
+        message_html = render_to_string('scripts/mail-error500.html', context={"error": reporter.get_traceback_html()})
+
+        send_mail("Erreur dans la Note Kfet", message, note_sender, [webmaster], html_message=message_html)
+    except BaseException as e:
+        sys.stderr.write("Une erreur est survenue lors de l'envoi d'un mail, pour signaler une erreur.")
+        raise e
-- 
GitLab