feat: Add preset shift templates, admin SMTP settings, test email dispatch, and email verification opt-out option
This commit is contained in:
Binary file not shown.
@@ -374,9 +374,14 @@ class EventTemplateViewSet(viewsets.ModelViewSet):
|
||||
max_participants=shift_data.get('max_participants', 1)
|
||||
)
|
||||
|
||||
skill_ids = shift_data.get('required_skill_ids', [])
|
||||
skill_names = shift_data.get('required_skill_names', [])
|
||||
if skill_names:
|
||||
matching_skills = Skill.objects.filter(name__in=skill_names)
|
||||
shift.required_skills.set(matching_skills)
|
||||
if skill_ids:
|
||||
shift.required_skills.set(Skill.objects.filter(id__in=skill_ids))
|
||||
elif skill_names:
|
||||
shift.required_skills.set(Skill.objects.filter(name__in=skill_names))
|
||||
|
||||
return Response(EventSerializer(event).data, status=status.HTTP_201_CREATED)
|
||||
return Response({
|
||||
'message': f'Veranstaltung "{event.title}" wurde erfolgreich aus der Vorlage erstellt.',
|
||||
'event_id': event.id
|
||||
}, status=status.HTTP_201_CREATED)
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,27 @@
|
||||
# Generated by Django 6.0.7 on 2026-07-31 08:22
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('users', '0004_user_is_email_verified_alter_user_is_approved_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='SMTPSetting',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('is_active', models.BooleanField(default=False, help_text='SMTP-Versand aktivieren')),
|
||||
('host', models.CharField(default='smtp.example.com', max_length=255)),
|
||||
('port', models.IntegerField(default=587)),
|
||||
('username', models.CharField(blank=True, default='', max_length=255)),
|
||||
('password', models.CharField(blank=True, default='', max_length=255)),
|
||||
('use_tls', models.BooleanField(default=True)),
|
||||
('use_ssl', models.BooleanField(default=False)),
|
||||
('from_email', models.EmailField(default='noreply@schichtplaner.local', max_length=254)),
|
||||
],
|
||||
),
|
||||
]
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 6.0.7 on 2026-07-31 08:23
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('users', '0005_smtpsetting'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='registrationrestrictionsetting',
|
||||
name='require_email_verification',
|
||||
field=models.BooleanField(default=True, help_text='E-Mail Bestätigungslink für neue Konten erforderlich'),
|
||||
),
|
||||
]
|
||||
BIN
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
@@ -39,6 +39,7 @@ class RegistrationDomainRule(models.Model):
|
||||
class RegistrationRestrictionSetting(models.Model):
|
||||
is_restriction_enabled = models.BooleanField(default=False)
|
||||
require_admin_approval = models.BooleanField(default=False, help_text="Neue Registrierungen müssen von einem Admin freigeschaltet werden")
|
||||
require_email_verification = models.BooleanField(default=True, help_text="E-Mail Bestätigungslink für neue Konten erforderlich")
|
||||
|
||||
@classmethod
|
||||
def get_solo(cls):
|
||||
@@ -46,7 +47,25 @@ class RegistrationRestrictionSetting(models.Model):
|
||||
return obj
|
||||
|
||||
def __str__(self):
|
||||
return f"Domain-Einschränkung: {self.is_restriction_enabled}, Admin-Freischaltung: {self.require_admin_approval}"
|
||||
return f"Domain-Einschränkung: {self.is_restriction_enabled}, Admin-Freischaltung: {self.require_admin_approval}, E-Mail-Pflicht: {self.require_email_verification}"
|
||||
|
||||
class SMTPSetting(models.Model):
|
||||
is_active = models.BooleanField(default=False, help_text="SMTP-Versand aktivieren")
|
||||
host = models.CharField(max_length=255, default="smtp.example.com")
|
||||
port = models.IntegerField(default=587)
|
||||
username = models.CharField(max_length=255, blank=True, default="")
|
||||
password = models.CharField(max_length=255, blank=True, default="")
|
||||
use_tls = models.BooleanField(default=True)
|
||||
use_ssl = models.BooleanField(default=False)
|
||||
from_email = models.EmailField(default="noreply@schichtplaner.local")
|
||||
|
||||
@classmethod
|
||||
def get_solo(cls):
|
||||
obj, _ = cls.objects.get_or_create(pk=1)
|
||||
return obj
|
||||
|
||||
def __str__(self):
|
||||
return f"SMTP {self.host}:{self.port} ({'Aktiv' if self.is_active else 'Inaktiv'})"
|
||||
|
||||
class EmailVerificationToken(models.Model):
|
||||
token = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from rest_framework import serializers
|
||||
from django.contrib.auth import get_user_model
|
||||
from .models import RegistrationDomainRule, RegistrationRestrictionSetting
|
||||
from .models import RegistrationDomainRule, RegistrationRestrictionSetting, SMTPSetting
|
||||
from apps.events.models import Skill
|
||||
|
||||
User = get_user_model()
|
||||
@@ -77,4 +77,9 @@ class RegistrationDomainRuleSerializer(serializers.ModelSerializer):
|
||||
class RegistrationRestrictionSettingSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = RegistrationRestrictionSetting
|
||||
fields = ['is_restriction_enabled', 'require_admin_approval']
|
||||
fields = ['is_restriction_enabled', 'require_admin_approval', 'require_email_verification']
|
||||
|
||||
class SMTPSettingSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = SMTPSetting
|
||||
fields = ['is_active', 'host', 'port', 'username', 'password', 'use_tls', 'use_ssl', 'from_email']
|
||||
|
||||
@@ -2,7 +2,7 @@ from django.test import TestCase
|
||||
from django.contrib.auth import get_user_model
|
||||
from rest_framework.test import APIClient
|
||||
from rest_framework import status
|
||||
from .models import RegistrationDomainRule, RegistrationRestrictionSetting, EmailVerificationToken
|
||||
from .models import RegistrationDomainRule, RegistrationRestrictionSetting, EmailVerificationToken, SMTPSetting
|
||||
from apps.events.models import Event, TaskArea, Shift, ShiftSignup
|
||||
|
||||
User = get_user_model()
|
||||
@@ -74,6 +74,30 @@ class UserRegistrationTests(TestCase):
|
||||
self.assertEqual(res_login_ok.status_code, status.HTTP_200_OK)
|
||||
self.assertIn('token', res_login_ok.data)
|
||||
|
||||
def test_email_verification_opt_out(self):
|
||||
# Set require_email_verification to False (Opt-Out)
|
||||
setting = RegistrationRestrictionSetting.get_solo()
|
||||
setting.require_email_verification = False
|
||||
setting.save()
|
||||
|
||||
# Register user with Opt-Out
|
||||
res_reg = self.client.post('/api/users/register/', {
|
||||
'username': 'optout_user',
|
||||
'email': 'optout@example.com',
|
||||
'password': 'password123',
|
||||
'display_name': 'Opt-Out User'
|
||||
})
|
||||
self.assertEqual(res_reg.status_code, status.HTTP_201_CREATED)
|
||||
self.assertIn('token', res_reg.data)
|
||||
self.assertFalse(res_reg.data.get('requires_verification'))
|
||||
|
||||
# Immediate login works
|
||||
res_login = self.client.post('/api/users/login/', {
|
||||
'username': 'optout_user',
|
||||
'password': 'password123'
|
||||
})
|
||||
self.assertEqual(res_login.status_code, status.HTTP_200_OK)
|
||||
|
||||
def test_guest_shift_claiming_on_registration(self):
|
||||
# Create event, task area, shift
|
||||
event = Event.objects.create(title="Test Event", start_date="2026-08-01", end_date="2026-08-02")
|
||||
@@ -169,3 +193,25 @@ class UserRegistrationTests(TestCase):
|
||||
self.assertIsNotNone(signup.user)
|
||||
self.assertEqual(signup.user.username, 'erika_muster')
|
||||
self.assertIsNone(signup.guest_name)
|
||||
|
||||
def test_smtp_settings_configuration(self):
|
||||
admin = User.objects.create_superuser(username='smtp_admin', email='smtp@test.com', password='password123')
|
||||
self.client.force_authenticate(user=admin)
|
||||
|
||||
# GET SMTP setting
|
||||
res_get = self.client.get('/api/users/smtp-setting/')
|
||||
self.assertEqual(res_get.status_code, status.HTTP_200_OK)
|
||||
self.assertFalse(res_get.data['is_active'])
|
||||
|
||||
# UPDATE SMTP setting
|
||||
res_post = self.client.post('/api/users/smtp-setting/', {
|
||||
'is_active': True,
|
||||
'host': 'smtp.mailtrap.io',
|
||||
'port': 2525,
|
||||
'username': 'test_user',
|
||||
'password': 'test_password',
|
||||
'from_email': 'noreply@test.de'
|
||||
}, format='json')
|
||||
self.assertEqual(res_post.status_code, status.HTTP_200_OK)
|
||||
self.assertTrue(res_post.data['is_active'])
|
||||
self.assertEqual(res_post.data['host'], 'smtp.mailtrap.io')
|
||||
|
||||
@@ -4,7 +4,8 @@ from .views import (
|
||||
RegisterView, VerifyEmailView, LoginView, MeView,
|
||||
RegistrationDomainRuleViewSet, RegistrationRestrictionSettingView,
|
||||
PendingUsersView, ApproveUserView, AdminUserViewSet,
|
||||
GenerateClaimLinkView, ClaimInfoView
|
||||
GenerateClaimLinkView, ClaimInfoView,
|
||||
SMTPSettingView, TestSMTPEmailView
|
||||
)
|
||||
|
||||
router = DefaultRouter()
|
||||
@@ -17,6 +18,8 @@ urlpatterns = [
|
||||
path('login/', LoginView.as_view(), name='login'),
|
||||
path('me/', MeView.as_view(), name='me'),
|
||||
path('restriction-setting/', RegistrationRestrictionSettingView.as_view(), name='restriction-setting'),
|
||||
path('smtp-setting/', SMTPSettingView.as_view(), name='smtp-setting'),
|
||||
path('smtp-setting/test/', TestSMTPEmailView.as_view(), name='smtp-setting-test'),
|
||||
path('pending/', PendingUsersView.as_view(), name='pending-users'),
|
||||
path('<int:user_id>/approve/', ApproveUserView.as_view(), name='approve-user'),
|
||||
path('signups/<int:signup_id>/generate-claim-link/', GenerateClaimLinkView.as_view(), name='generate-claim-link'),
|
||||
|
||||
+143
-10
@@ -3,15 +3,67 @@ from rest_framework.response import Response
|
||||
from rest_framework.authtoken.models import Token
|
||||
from django.contrib.auth import authenticate, get_user_model
|
||||
from django.shortcuts import get_object_or_404
|
||||
from .models import RegistrationDomainRule, RegistrationRestrictionSetting, GuestClaimToken, EmailVerificationToken
|
||||
from django.core.mail import get_connection, EmailMultiAlternatives
|
||||
from .models import RegistrationDomainRule, RegistrationRestrictionSetting, GuestClaimToken, EmailVerificationToken, SMTPSetting
|
||||
from .serializers import (
|
||||
UserSerializer, AdminUserSerializer, RegisterSerializer,
|
||||
RegistrationDomainRuleSerializer, RegistrationRestrictionSettingSerializer
|
||||
RegistrationDomainRuleSerializer, RegistrationRestrictionSettingSerializer, SMTPSettingSerializer
|
||||
)
|
||||
from apps.events.models import ShiftSignup
|
||||
|
||||
User = get_user_model()
|
||||
|
||||
def send_verification_email_to_user(user, v_token_str, request_host=None):
|
||||
smtp = SMTPSetting.get_solo()
|
||||
host_str = request_host or 'localhost:3000'
|
||||
verify_url = f"http://{host_str}/?verify_email={v_token_str}"
|
||||
|
||||
subject = "E-Mail-Adresse bestätigen — Veranstaltungsschichtplaner"
|
||||
text_content = f"Hallo {user.get_display_name()},\n\nbitte bestätige deine E-Mail-Adresse durch Aufruf des folgenden Links:\n{verify_url}\n\nVielen Dank!"
|
||||
html_content = f"""
|
||||
<div style="font-family: sans-serif; padding: 20px; line-height: 1.6; color: #1f2937;">
|
||||
<h2 style="color: #4f46e5;">Willkommen beim Schichtplaner!</h2>
|
||||
<p>Hallo <strong>{user.get_display_name()}</strong>,</p>
|
||||
<p>vielen Dank für deine Registrierung. Bitte bestätige deine E-Mail-Adresse durch Klick auf den folgenden Button:</p>
|
||||
<p style="margin: 25px 0;">
|
||||
<a href="{verify_url}" style="background: #4f46e5; color: #ffffff; padding: 12px 24px; text-decoration: none; border-radius: 6px; font-weight: bold; display: inline-block;">
|
||||
E-Mail-Adresse Bestätigen
|
||||
</a>
|
||||
</p>
|
||||
<p style="color: #6b7280; font-size: 12px;">Oder kopiere diesen Link in deinen Browser:<br><a href="{verify_url}">{verify_url}</a></p>
|
||||
</div>
|
||||
"""
|
||||
|
||||
print("==================================================")
|
||||
print(f"[E-MAIL BESTÄTIGUNG]: {verify_url}")
|
||||
print("==================================================")
|
||||
|
||||
if smtp.is_active and smtp.host:
|
||||
try:
|
||||
connection = get_connection(
|
||||
host=smtp.host,
|
||||
port=smtp.port,
|
||||
username=smtp.username,
|
||||
password=smtp.password,
|
||||
use_tls=smtp.use_tls,
|
||||
use_ssl=smtp.use_ssl,
|
||||
fail_silently=False,
|
||||
)
|
||||
msg = EmailMultiAlternatives(
|
||||
subject=subject,
|
||||
body=text_content,
|
||||
from_email=smtp.from_email or 'noreply@schichtplaner.local',
|
||||
to=[user.email],
|
||||
connection=connection
|
||||
)
|
||||
msg.attach_alternative(html_content, "text/html")
|
||||
msg.send()
|
||||
return True, "E-Mail erfolgreich versendet."
|
||||
except Exception as e:
|
||||
return False, f"SMTP-Fehler: {str(e)}"
|
||||
|
||||
return True, "Bestätigungslink in Konsole ausgegeben."
|
||||
|
||||
class AdminUserViewSet(viewsets.ModelViewSet):
|
||||
queryset = User.objects.all().order_by('-date_joined')
|
||||
serializer_class = AdminUserSerializer
|
||||
@@ -70,16 +122,47 @@ class RegisterView(views.APIView):
|
||||
signup.save()
|
||||
assigned_count += 1
|
||||
|
||||
v_token = EmailVerificationToken.objects.create(user=user)
|
||||
print("==================================================")
|
||||
print(f"[E-MAIL BESTÄTIGUNG]: http://localhost:3000/?verify_email={v_token.token}")
|
||||
print("==================================================")
|
||||
if setting.require_email_verification:
|
||||
user.is_approved = False
|
||||
user.is_email_verified = False
|
||||
user.is_active = True
|
||||
user.save()
|
||||
|
||||
v_token = EmailVerificationToken.objects.create(user=user)
|
||||
req_host = request.get_host()
|
||||
send_verification_email_to_user(user, str(v_token.token), request_host=req_host)
|
||||
|
||||
return Response({
|
||||
'requires_verification': True,
|
||||
'verification_token': str(v_token.token),
|
||||
'claimed_shifts_count': assigned_count,
|
||||
'message': 'Konto erfolgreich erstellt! Bitte bestätige deine E-Mail-Adresse über den Link in der Bestätigungs-E-Mail oder warte auf die Admin-Freischaltung.'
|
||||
}, status=status.HTTP_201_CREATED)
|
||||
|
||||
# Opt-Out: Email verification not required!
|
||||
user.is_email_verified = True
|
||||
|
||||
if setting.require_admin_approval:
|
||||
user.is_approved = False
|
||||
user.is_active = False
|
||||
user.save()
|
||||
return Response({
|
||||
'requires_approval': True,
|
||||
'claimed_shifts_count': assigned_count,
|
||||
'message': 'Konto erfolgreich registriert! Ein Administrator muss dein Konto vor der ersten Anmeldung freischalten.'
|
||||
}, status=status.HTTP_201_CREATED)
|
||||
|
||||
user.is_approved = True
|
||||
user.is_active = True
|
||||
user.save()
|
||||
|
||||
token, _ = Token.objects.get_or_create(user=user)
|
||||
user_data = UserSerializer(user).data
|
||||
return Response({
|
||||
'requires_verification': True,
|
||||
'verification_token': str(v_token.token),
|
||||
'token': token.key,
|
||||
'user': user_data,
|
||||
'claimed_shifts_count': assigned_count,
|
||||
'message': 'Konto erfolgreich erstellt! Bitte bestätige deine E-Mail-Adresse über den Link in der Bestätigungs-E-Mail oder warte auf die Admin-Freischaltung.'
|
||||
'message': f'Konto erfolgreich erstellt! {assigned_count} Gast-Schichten wurden deinem Konto zugewiesen.' if assigned_count > 0 else 'Konto erfolgreich erstellt!'
|
||||
}, status=status.HTTP_201_CREATED)
|
||||
|
||||
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
@@ -218,6 +301,7 @@ class RegistrationRestrictionSettingView(views.APIView):
|
||||
return Response({
|
||||
'is_restriction_enabled': setting.is_restriction_enabled,
|
||||
'require_admin_approval': setting.require_admin_approval,
|
||||
'require_email_verification': setting.require_email_verification,
|
||||
'active_domains': active_domains
|
||||
})
|
||||
|
||||
@@ -227,12 +311,61 @@ class RegistrationRestrictionSettingView(views.APIView):
|
||||
setting.is_restriction_enabled = request.data['is_restriction_enabled']
|
||||
if 'require_admin_approval' in request.data:
|
||||
setting.require_admin_approval = request.data['require_admin_approval']
|
||||
if 'require_email_verification' in request.data:
|
||||
setting.require_email_verification = request.data['require_email_verification']
|
||||
setting.save()
|
||||
return Response({
|
||||
'is_restriction_enabled': setting.is_restriction_enabled,
|
||||
'require_admin_approval': setting.require_admin_approval
|
||||
'require_admin_approval': setting.require_admin_approval,
|
||||
'require_email_verification': setting.require_email_verification
|
||||
})
|
||||
|
||||
class SMTPSettingView(views.APIView):
|
||||
permission_classes = [permissions.IsAdminUser]
|
||||
|
||||
def get(self, request):
|
||||
setting = SMTPSetting.get_solo()
|
||||
return Response(SMTPSettingSerializer(setting).data)
|
||||
|
||||
def post(self, request):
|
||||
setting = SMTPSetting.get_solo()
|
||||
serializer = SMTPSettingSerializer(setting, data=request.data, partial=True)
|
||||
if serializer.is_valid():
|
||||
serializer.save()
|
||||
return Response(serializer.data)
|
||||
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
class TestSMTPEmailView(views.APIView):
|
||||
permission_classes = [permissions.IsAdminUser]
|
||||
|
||||
def post(self, request):
|
||||
smtp = SMTPSetting.get_solo()
|
||||
target_email = request.data.get('email') or request.user.email
|
||||
if not target_email:
|
||||
return Response({'error': 'E-Mail-Adresse erforderlich.'}, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
try:
|
||||
connection = get_connection(
|
||||
host=smtp.host,
|
||||
port=smtp.port,
|
||||
username=smtp.username,
|
||||
password=smtp.password,
|
||||
use_tls=smtp.use_tls,
|
||||
use_ssl=smtp.use_ssl,
|
||||
fail_silently=False,
|
||||
)
|
||||
msg = EmailMultiAlternatives(
|
||||
subject="Test E-Mail — SMTP Konfiguration",
|
||||
body=f"Hallo,\n\ndies ist eine Test-E-Mail zur Überprüfung der SMTP-Einstellungen für {request.user.get_display_name()}.",
|
||||
from_email=smtp.from_email or 'noreply@schichtplaner.local',
|
||||
to=[target_email],
|
||||
connection=connection
|
||||
)
|
||||
msg.send()
|
||||
return Response({'message': f'Test E-Mail erfolgreich an {target_email} gesendet!'})
|
||||
except Exception as e:
|
||||
return Response({'error': f'SMTP-Verbindungsfehler: {str(e)}'}, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
class PendingUsersView(views.APIView):
|
||||
permission_classes = [permissions.IsAdminUser]
|
||||
|
||||
|
||||
Reference in New Issue
Block a user