diff --git a/modoboa/core/api/v2/tests.py b/modoboa/core/api/v2/tests.py index ed6bdd5e4..4caae77f7 100644 --- a/modoboa/core/api/v2/tests.py +++ b/modoboa/core/api/v2/tests.py @@ -204,6 +204,25 @@ class AccountViewSetTestCase(ModoAPITestCase): 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): diff --git a/modoboa/core/api/v2/views.py b/modoboa/core/api/v2/views.py index ecfdc75f1..c8c7ac8d8 100644 --- a/modoboa/core/api/v2/views.py +++ b/modoboa/core/api/v2/views.py @@ -49,7 +49,7 @@ class TokenObtainPairView(jwt_views.TokenObtainPairView): 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])