From 5d17c9df90d2d3296f9108df6965c41dac17b459 Mon Sep 17 00:00:00 2001 From: David Cooke Date: Mon, 18 Oct 2021 19:23:31 +0100 Subject: [PATCH] Handle duplicate bot usernames with an error message instead of a 500 --- src/authentication/tests.py | 22 ++++++++++++++++++++++ src/authentication/views.py | 8 ++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/authentication/tests.py b/src/authentication/tests.py index ca8b47c5..7a01c78c 100644 --- a/src/authentication/tests.py +++ b/src/authentication/tests.py @@ -918,3 +918,25 @@ def test_issues_token(self): }, ) self.assertTrue("token" in response.data["d"]) + + def test_duplicate_username(self): + self.client.force_authenticate(self.user) + self.client.post( + reverse("create-bot"), + data={ + "username": "bottest", + "is_visible": False, + "is_staff": True, + "is_superuser": True, + }, + ) + response = self.client.post( + reverse("create-bot"), + data={ + "username": "bottest", + "is_visible": False, + "is_staff": True, + "is_superuser": True, + }, + ) + self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST) diff --git a/src/authentication/views.py b/src/authentication/views.py index d0a6ee57..a8fbd5d4 100644 --- a/src/authentication/views.py +++ b/src/authentication/views.py @@ -5,7 +5,7 @@ from django.conf import settings from django.contrib.auth import get_user_model from django.core.validators import EmailValidator -from django.db import transaction +from django.db import transaction, IntegrityError from django.utils.decorators import method_decorator from django.views.decorators.debug import sensitive_post_parameters from django_filters.rest_framework import DjangoFilterBackend @@ -361,7 +361,11 @@ def post(self, request): is_bot=True, email=serializer.data["username"] + "@bot.ractf", ) - bot.save() + + try: + bot.save() + except IntegrityError: + return FormattedResponse(m="username_already_exists", status=HTTP_400_BAD_REQUEST) return FormattedResponse(d={"token": bot.issue_token()}, status=HTTP_201_CREATED)