diff --git a/server/oauth/tests/test_login.py b/server/oauth/tests/test_login.py index d8f22199..4715fbdd 100644 --- a/server/oauth/tests/test_login.py +++ b/server/oauth/tests/test_login.py @@ -218,3 +218,36 @@ class LoginTests(TestCase): self.fail('LoginTests.test_teacher_can_login_with_valid_license: Userdata should not exist') except: pass + + @patch.object(HepClient, "fetch_eorders", return_value=VALID_TEACHERS_ORDERS) + @patch.object(DjangoOAuth2App, "authorize_access_token", return_value=TOKEN) + @patch.object(HepClient, "user_details", return_value=ME_DATA) + def test_update_of_duration_in_code_MS768( + self, user_mock, authorize_mock, orders_mock + ): + """ + https://iterativ.atlassian.net/browse/MS-768 + """ + response = self._login("/api/oauth/authorize?code=1234") + + user = User.objects.get(email=ME_DATA["email"]) + + # user_role_key = user.user_roles.get(user=user).role.key + + # Create a license that expires in 70 days later than duration... + # (which is special since the expiration date is set to now+ duration) + # This simulates that the duration was changed in the code after the license was created + + current_license: License = ( + License.objects.filter(licensee=user).order_by("-expire_date").first() + ) + current_license.expire_date = current_license.expire_date + timedelta(days=700) + current_license.save() + for _ in range(5): + response = self._login("/api/oauth/authorize?code=1234") + + # Check that only one new licesnse was created and not one for each login + self.assertEqual(License.objects.all().count(), 2) + + self.assertEqual(response.url, f"/{OAUTH_REDIRECT}?state=success") + self.assertTrue(self.user.is_authenticated) diff --git a/server/oauth/user_signup_login_handler.py b/server/oauth/user_signup_login_handler.py index fa3758c4..cb29c045 100644 --- a/server/oauth/user_signup_login_handler.py +++ b/server/oauth/user_signup_login_handler.py @@ -29,7 +29,7 @@ def handle_user_and_verify_products(user_data, token): create_role_for_user(user, license.for_role.key) - if not license.is_valid(): + if license and not license.is_valid(): return user, NO_VALID_LICENSE return user, None diff --git a/server/users/managers.py b/server/users/managers.py index 1a99c36e..10c958d8 100644 --- a/server/users/managers.py +++ b/server/users/managers.py @@ -160,7 +160,10 @@ class LicenseManager(models.Manager): isbn=isbn, hep_created_at=activation_date) def get_active_license_for_user(self, user): - licenses = self.filter(licensee=user, expire_date__gte=timezone.now()).order_by('-expire_date') + licenses = self.filter(licensee=user, expire_date__gte=timezone.now()).order_by( + "-expire_date" + ) + licenses = [license for license in licenses if license.is_valid()] if len(licenses) == 0: return None