diff --git a/openwisp_users/base/models.py b/openwisp_users/base/models.py index 2876014c..b654c173 100644 --- a/openwisp_users/base/models.py +++ b/openwisp_users/base/models.py @@ -93,7 +93,7 @@ def set_password(self, *args, **kwargs): return super().set_password(*args, **kwargs) def has_password_expired(self): - if not self.has_usable_password(): + if not self.has_usable_password() or self.password_updated is None: return False if self.is_staff and app_settings.STAFF_USER_PASSWORD_EXPIRATION: expiry_date = self.password_updated + timezone.timedelta( diff --git a/openwisp_users/tests/test_models.py b/openwisp_users/tests/test_models.py index c9523415..31cfa9a3 100644 --- a/openwisp_users/tests/test_models.py +++ b/openwisp_users/tests/test_models.py @@ -358,25 +358,21 @@ def test_has_password_expired(self): staff_user.refresh_from_db() end_user.refresh_from_db() - with self.subTest('Test password expiration disabled'): + with self.subTest('Test password expiration feature disabled'): with patch.object( app_settings, 'USER_PASSWORD_EXPIRATION', 0 ), patch.object(app_settings, 'STAFF_USER_PASSWORD_EXPIRATION', 0): self.assertEqual(staff_user.has_password_expired(), False) self.assertEqual(end_user.has_password_expired(), False) - with self.subTest( - 'Test password expiration enabled, but user password not expired' - ): + with self.subTest('Test password is not expired'): with patch.object( app_settings, 'USER_PASSWORD_EXPIRATION', 10 ), patch.object(app_settings, 'STAFF_USER_PASSWORD_EXPIRATION', 10): self.assertEqual(staff_user.has_password_expired(), False) self.assertEqual(end_user.has_password_expired(), False) - with self.subTest( - 'Test password expiration enabled, but user password is expired' - ): + with self.subTest('Test password is expired'): User.objects.update(password_updated=now().date() - timedelta(days=180)) staff_user.refresh_from_db() end_user.refresh_from_db() @@ -386,6 +382,14 @@ def test_has_password_expired(self): self.assertEqual(staff_user.has_password_expired(), True) self.assertEqual(end_user.has_password_expired(), True) + with self.subTest('Test password_updated is None'): + User.objects.update(password_updated=None) + end_user.refresh_from_db() + with patch.object( + app_settings, 'USER_PASSWORD_EXPIRATION', 10 + ), patch.object(app_settings, 'STAFF_USER_PASSWORD_EXPIRATION', 10): + self.assertEqual(end_user.has_password_expired(), False) + @patch.object(app_settings, 'USER_PASSWORD_EXPIRATION', 30) @patch.object(app_settings, 'STAFF_USER_PASSWORD_EXPIRATION', 90) def test_password_expiration_mail(self):