Self hosted FLOSS fitness/workout, nutrition and weight tracker
Properly handle case where user was deleted
Roland Geider06f77fbac17f
diff --git a/wger/core/tests/test_headless.py b/wger/core/tests/test_headless.pyindex e721bfebc..d657df047 100644--- a/wger/core/tests/test_headless.py+++ b/wger/core/tests/test_headless.py@@ -109,6 +109,33 @@ class HeadlessSmokeTestCase(WgerTestCase):self.assertEqual(response.status_code, 200, response.content)self.assertEqual(User.objects.count(), count_before + 1)+ def test_access_token_for_deleted_user_is_rejected(self):+ """+ A JWT access token stays cryptographically valid after its user is+ deleted, so allauth's lazy user lookup would otherwise raise+ DoesNotExist on first access and surface as a 500 later on. The auth+ layer rejects it here cleanly instead, with the same outcome as an+ expired token.+ """+ response = self.client.post(+ reverse('headless:app:account:login'),+ data=json.dumps({'username': 'test', 'password': 'testtest'}),+ content_type='application/json',+ )+ self.assertEqual(response.status_code, 200, response.content)+ access_token = response.json()['meta']['access_token']++ # Drop the session cookie the login set, then delete the user so the+ # still-valid token points at a row that no longer exists.+ self.client.logout()+ User.objects.get(username='test').delete()++ response = self.client.get(+ '/api/v2/workoutsession/',+ HTTP_AUTHORIZATION=f'Bearer {access_token}',+ )+ self.assertIn(response.status_code, (401, 403))+def test_invalid_jwt_does_not_break_auth_chain(self):"""A malformed Bearer token must not raise AuthenticationFailed in ourdiff --git a/wger/utils/headless_auth.py b/wger/utils/headless_auth.pyindex 93c549aad..a56addb8a 100644--- a/wger/utils/headless_auth.py+++ b/wger/utils/headless_auth.py@@ -15,6 +15,9 @@# You should have received a copy of the GNU Affero General Public License# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.+# Django+from django.contrib.auth import get_user_model+# Third Partyfrom allauth.headless.contrib.rest_framework.authentication import JWTTokenAuthenticationfrom allauth.headless.tokens.strategies.jwt import internal@@ -38,6 +41,18 @@ class HeadlessJWTAuthentication(JWTTokenAuthentication):except AuthenticationFailed:return None+ def authenticate_credentials(self, key):+ user, payload = super().authenticate_credentials(key)+ # validate_access_token hands back a SimpleLazyObject that only hits the+ # DB on first access. Force the lookup now so an access token whose user+ # was deleted fails as a clean 401 here, instead of raising DoesNotExist+ # later on and raising an uncaught 500.+ try:+ _ = user.pk+ except get_user_model().DoesNotExist as exc:+ raise AuthenticationFailed('Invalid token') from exc+ return user, payload+class WgerJWTTokenStrategy(JWTTokenStrategy):"""