From 36a07e79f8c82d0cddb597c7af7b0a24abdadb27 Mon Sep 17 00:00:00 2001 From: Tom Mortimer-Jones Date: Thu, 12 Oct 2023 08:55:32 +0100 Subject: [PATCH] Count non expiring tokens when determining if the limit is reached Fixes #280 Thanks to @pablomm for the code in the ticket --- knox/views.py | 5 ++++- tests/tests.py | 4 +++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/knox/views.py b/knox/views.py index 7a6b5719..e94bca83 100644 --- a/knox/views.py +++ b/knox/views.py @@ -1,4 +1,5 @@ from django.contrib.auth.signals import user_logged_in, user_logged_out +from django.db.models import Q from django.utils import timezone from rest_framework import status from rest_framework.permissions import IsAuthenticated @@ -62,7 +63,9 @@ def post(self, request, format=None): token_limit_per_user = self.get_token_limit_per_user() if token_limit_per_user is not None: now = timezone.now() - token = request.user.auth_token_set.filter(expiry__gt=now) + token = request.user.auth_token_set.filter( + Q(expiry__gt=now) | Q(expiry__isnull=True) + ) if token.count() >= token_limit_per_user: return Response( {"error": "Maximum amount of tokens allowed per user exceeded."}, diff --git a/tests/tests.py b/tests/tests.py index 6fa5ca97..c0c62c66 100644 --- a/tests/tests.py +++ b/tests/tests.py @@ -339,8 +339,10 @@ def test_exceed_token_amount_per_user(self): with override_settings(REST_KNOX=token_user_limit_knox): reload(views) - for _ in range(10): + for _ in range(5): AuthToken.objects.create(user=self.user) + for _ in range(5): + AuthToken.objects.create(user=self.user, expiry=None) url = reverse('knox_login') self.client.credentials( HTTP_AUTHORIZATION=get_basic_auth_header(self.username, self.password)