From 9e091936a7c2119e17be5266be6240df2ebd0ca4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Martin=20Juh=C3=A1s?= <xjuhas@fi.muni.cz>
Date: Mon, 19 Aug 2024 14:38:46 +0200
Subject: [PATCH] fix: add missing checks for running exercise for email
 actions

No API changes

Closes #245
---
 aai/tests/special_case_tests.py      | 3 +++
 running_exercise/lib/email_client.py | 5 +++++
 running_exercise/schema/mutation.py  | 5 +++++
 3 files changed, 13 insertions(+)

diff --git a/aai/tests/special_case_tests.py b/aai/tests/special_case_tests.py
index b9a27f32..a09ca923 100644
--- a/aai/tests/special_case_tests.py
+++ b/aai/tests/special_case_tests.py
@@ -62,6 +62,9 @@ class SpecialCaseTests(GraphQLApiTestCase):
 
         cls.trainee1.teams.add(cls.exercise.teams.first())
 
+        cls.exercise.running = True
+        cls.exercise.save()
+
         cls.thread = EmailClient.create_thread(
             ["team-1@mail.com", "doe@mail.ex"], "test", cls.exercise.id
         )
diff --git a/running_exercise/lib/email_client.py b/running_exercise/lib/email_client.py
index e58a3fd5..72002bcc 100644
--- a/running_exercise/lib/email_client.py
+++ b/running_exercise/lib/email_client.py
@@ -136,6 +136,11 @@ class EmailClient:
         participant_addresses: List[str], subject: str, exercise_id: str
     ) -> EmailThread:
         exercise = get_model(Exercise, id=exercise_id)
+        if not exercise.running:
+            raise RunningExerciseOperationException(
+                "Cannot create a thread when the exercise is not running"
+            )
+
         participants = _validate_participants(participant_addresses, exercise)
 
         new_thread = EmailThread.objects.create(
diff --git a/running_exercise/schema/mutation.py b/running_exercise/schema/mutation.py
index 45fce9fd..7a524938 100644
--- a/running_exercise/schema/mutation.py
+++ b/running_exercise/schema/mutation.py
@@ -5,6 +5,7 @@ from rest_framework.exceptions import PermissionDenied
 
 from aai.access import user_from_context, team_access, exercise_access
 from aai.decorators import protected
+from common_lib.exceptions import RunningExerciseOperationException
 from common_lib.logger import logger
 from common_lib.schema.types import ExerciseType, EmailThreadType
 from common_lib.utils import get_model
@@ -96,6 +97,10 @@ class SendEmailMutation(graphene.Mutation):
         send_email_input: SendEmailInput,
     ):
         thread = get_model(EmailThread, id=send_email_input.thread_id)
+        if not thread.exercise.running:
+            raise RunningExerciseOperationException(
+                "Cannot send an email when the exercise is not running"
+            )
         participant = get_model(
             EmailParticipant,
             address=send_email_input.sender_address,
-- 
GitLab