Browse Source

add mail notification

subDesTagesMitExtraKaese 2 years ago
parent
commit
390d45351c
4 changed files with 58 additions and 8 deletions
  1. 2 0
      apps.py
  2. 6 6
      forms.py
  3. 36 0
      signals.py
  4. 14 2
      views.py

+ 2 - 0
apps.py

@@ -4,3 +4,5 @@ from django.apps import AppConfig
 class StammbaumConfig(AppConfig):
     default_auto_field = 'django.db.models.BigAutoField'
     name = 'stammbaum'
+    def ready(self):
+        import stammbaum.signals

+ 6 - 6
forms.py

@@ -11,15 +11,15 @@ class UploadImage(forms.ModelForm):
 
  
 class SignUpForm(UserCreationForm):
-    class Meta:
-        model = User
-        fields = ('first_name', 'last_name', 'email', 'username', 'password1', 'password2', )
+  class Meta:
+    model = User
+    fields = ('first_name', 'last_name', 'email', 'username', 'password1', 'password2', )
 
 class PersonChangeForm(forms.ModelForm):
   def __init__(self, instance) -> None:
-      print(instance)
-      super().__init__(instance)
-      #self.fields['partner'].queryset = Person.objects.complex_filter()
+    print(instance)
+    super().__init__(instance)
+    #self.fields['partner'].queryset = Person.objects.complex_filter()
   class Meta:
     model = Person
     fields = '__all__'

+ 36 - 0
signals.py

@@ -0,0 +1,36 @@
+from django.contrib.auth.models import User
+from django.core.mail import send_mail
+from django.db.models import signals
+
+from website.settings import *
+
+def post_user_save(sender, instance: User, *args, **kwargs):
+  #oldUser: User = User.objects.get(id=instance.id)
+  #print(oldUser.get_all_permissions(), args, kwargs)
+  #if instance.get_all_permissions() != oldUser.get_all_permissions():
+    perm_list = []
+    if instance.has_perm("stammbaum.view"):
+      perm_list.append("Du darfst den gesamten Stammbaum ansehen.")
+    if instance.has_perm("stammbaum.upload_image"):
+      perm_list.append("Du darfst Bilder für Personen im Stammbaum hochladen.")
+    if instance.is_staff and instance.has_perm("stammbaum.change_person"):
+      perm_list.append("Du darfst Personen im Stammbaum bearbeiten.")
+    if instance.is_staff and instance.has_perm("stammbaum.add_person"):
+      perm_list.append("Du darfst Personen zum Stammbaum hinzufügen.")
+    if instance.is_staff and instance.has_perm("stammbaum.add_group"):
+      perm_list.append("Du darfst deinen eigenen Stammbaum hinzufügen. (Stammbaum bearbeiten -> Gruppe hinzufügen)")
+
+    send_mail(
+      subject='Deine Berechtigungen wurden geändert',
+      message=f'Hallo {instance.get_full_name()}, \n\n' +
+      "deine Berechtigungen auf der Stammbaum-Webseite wurden gerade angepasst.\n\n" +
+      "Jetzt hast du folgende Berechtigungen:\n" + 
+      '\n'.join([' - ' + p for p in perm_list]) + '\n\n' +
+      "LG\nWebsite-Admins\n\n" +
+      "https://pi.justprojects.de/stammbaum\n" + 
+      f"Login vergessen? Dein Benutzername lautet {instance.username}.",
+      from_email='stammbaum@justprojects.de',
+      recipient_list=[instance.email],
+      fail_silently=False
+    )
+signals.post_save.connect(post_user_save, sender=User, dispatch_uid='post_user_save')

+ 14 - 2
views.py

@@ -3,6 +3,7 @@ from PIL import Image
 from django.shortcuts import redirect, render
 from django.template import loader
 
+from django.core import mail
 from django.http import HttpResponse, FileResponse
 from django.urls import reverse_lazy
 from django.views.generic import UpdateView
@@ -42,8 +43,8 @@ def register(request):
   if request.method == 'POST':
     form = SignUpForm(request.POST)
     if form.is_valid():
-      user = form.save()
-      user.refresh_from_db()  
+      user: User = form.save()
+      user.refresh_from_db()
       # load the profile instance created by the signal
       user.save()
       raw_password = form.cleaned_data.get('password1')
@@ -52,6 +53,17 @@ def register(request):
       user = auth.authenticate(username=user.username, password=raw_password)
       auth.login(request, user)
 
+      # notify admin
+      with mail.get_connection() as connection:
+        mail.mail_admins(
+          f"{user.get_full_name()} has registered to 'Stammbaum'", 
+          f"{user.username} ({user.get_full_name()}) <{user.email}> has registered to 'Stammbaum'.\n" +
+          f"Please update their permissions accordingly.\n" + 
+          f"https://pi.justprojects.de/admin/auth/user/{user.id}/change/",
+          False,
+          connection
+        )
+
       # redirect user to home page
       return redirect('/stammbaum/')
   else: