Skip to content

Commit

Permalink
Merge pull request #2796 from modoboa/fix-logger-api-v2
Browse files Browse the repository at this point in the history
log message on failed auth on api v2
  • Loading branch information
tonioo committed Feb 21, 2023
2 parents 6c7a8d2 + ac78cbb commit b0c4528
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
19 changes: 19 additions & 0 deletions modoboa/core/api/v2/tests.py
Expand Up @@ -204,6 +204,25 @@ def test_api_token(self):
resp = self.client.post(url)
self.assertEqual(resp.status_code, 201)

def test_failed_api_token(self):
"""Simulate a failed login attempt and check that it is logged."""

url = reverse("v2:token_obtain_pair")
data = {
"username": "clearly_non_existent_user",
"password": "password"
}

with self.assertLogs(logger='modoboa.auth', level='WARNING') as log:

resp = self.client.post(url, data, format="json")
self.assertEqual(resp.status_code, 401)
self.assertIn(
"WARNING:modoboa.auth:Failed connection attempt from '127.0.0.1'"
" as user 'clearly_non_existent_user'",
log.output
)


class PasswordResetTestCase(AccountViewSetTestCase):
def __init__(self, *args, **kwargs):
Expand Down
11 changes: 6 additions & 5 deletions modoboa/core/api/v2/views.py
Expand Up @@ -10,8 +10,9 @@

from drf_spectacular.utils import extend_schema
from rest_framework import response, status
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_simplejwt import views as jwt_views
from rest_framework_simplejwt.exceptions import InvalidToken, TokenError
from rest_framework_simplejwt.exceptions import InvalidToken
from rest_framework.views import APIView

from modoboa.core.password_hashers import get_password_hasher
Expand All @@ -28,7 +29,7 @@

def delete_cache_key(class_target, throttles, request):
"""Attempt to delete cache key from throttling on login/password reset success."""

for throttle in throttles:
if type(throttle) == class_target:
throttle.reset_cache(request)
Expand All @@ -44,11 +45,11 @@ def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
try:
serializer.is_valid(raise_exception=True)
except TokenError as e:
except AuthenticationFailed as e:
logger.warning(
_("Failed connection attempt from '%s' as user '%s'"),
request.META["REMOTE_ADDR"],
escape(serializer.data["username"])
escape(serializer.initial_data["username"])
)
raise InvalidToken(e.args[0])

Expand Down Expand Up @@ -133,7 +134,7 @@ def post(self, request, *args, **kwargs):
serializer.is_valid(raise_exception=True)
except serializers.NoSMSAvailable:
return super().post(request, *args, **kwargs)

# SMS response
return response.Response({"type": "sms"}, 200)

Expand Down

0 comments on commit b0c4528

Please sign in to comment.