Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle duplicate bot usernames with an error message instead of a 500 #206

Merged
merged 1 commit into from
Oct 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/authentication/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
8 changes: 6 additions & 2 deletions src/authentication/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)


Expand Down