Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
migrations: Subscription.is_user_active denormalization - step one.
Mateusz Manderaf32987837647
diff --git a/analytics/management/commands/populate_analytics_db.py b/analytics/management/commands/populate_analytics_db.pyindex adce7205470..98a079bbb07 100644--- a/analytics/management/commands/populate_analytics_db.py+++ b/analytics/management/commands/populate_analytics_db.py@@ -95,7 +95,10 @@ class Command(BaseCommand):# TODO: This should use subscribe_users_to_streams from populate_db.subs = [Subscription(- recipient=recipient, user_profile=shylock, color=STREAM_ASSIGNMENT_COLORS[0]+ recipient=recipient,+ user_profile=shylock,+ is_user_active=shylock.is_active,+ color=STREAM_ASSIGNMENT_COLORS[0],),]Subscription.objects.bulk_create(subs)diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.pyindex 27d37fb1af5..28797d6ec47 100644--- a/corporate/tests/test_stripe.py+++ b/corporate/tests/test_stripe.py@@ -341,9 +341,10 @@ class StripeTestCase(ZulipTestCase):]# Deactivate all users in our realm that aren't in our whitelist.- UserProfile.objects.filter(realm_id=realm.id).exclude(email__in=active_emails).update(- is_active=False- )+ for user_profile in UserProfile.objects.filter(realm_id=realm.id).exclude(+ email__in=active_emails+ ):+ do_deactivate_user(user_profile, acting_user=None)# sanity check our 8 expected users are activeself.assertEqual(diff --git a/tools/semgrep.yml b/tools/semgrep.ymlindex a85457a09e8..d10583472af 100644--- a/tools/semgrep.yml+++ b/tools/semgrep.yml@@ -139,3 +139,17 @@ rules:pattern: typing.Textseverity: ERRORmessage: "Use str instead of typing.Text"++ - id: change-user-is-active+ languages: [python]+ patterns:+ - pattern-either:+ - pattern: |+ $X.is_active = ...+ - pattern: |+ setattr($X, 'is_active', ...)+ - pattern-not-inside: |+ def change_user_is_active(...):+ ...+ message: "Use change_user_is_active to mutate user_profile.is_active"+ severity: ERRORdiff --git a/zerver/lib/actions.py b/zerver/lib/actions.pyindex c84d10901bb..366eafcfa92 100644--- a/zerver/lib/actions.py+++ b/zerver/lib/actions.py@@ -695,13 +695,13 @@ def do_create_user(def do_activate_user(user_profile: UserProfile, *, acting_user: Optional[UserProfile]) -> None:with transaction.atomic():- user_profile.is_active = True+ change_user_is_active(user_profile, True)user_profile.is_mirror_dummy = Falseuser_profile.set_unusable_password()user_profile.date_joined = timezone_now()user_profile.tos_version = settings.TOS_VERSIONuser_profile.save(- update_fields=["is_active", "date_joined", "password", "is_mirror_dummy", "tos_version"]+ update_fields=["date_joined", "password", "is_mirror_dummy", "tos_version"])event_time = user_profile.date_joined@@ -733,8 +733,7 @@ def do_reactivate_user(user_profile: UserProfile, *, acting_user: Optional[UserP# Unlike do_activate_user, this is meant for re-activating existing users,# so it doesn't reset their password, etc.with transaction.atomic():- user_profile.is_active = True- user_profile.save(update_fields=["is_active"])+ change_user_is_active(user_profile, True)event_time = timezone_now()RealmAuditLog.objects.create(@@ -1118,30 +1117,47 @@ def do_delete_user(user_profile: UserProfile) -> None:is_mirror_dummy=True,)subs_to_recreate = [- Subscription(user_profile=replacement_user, recipient=recipient)+ Subscription(+ user_profile=replacement_user,+ recipient=recipient,+ is_user_active=replacement_user.is_active,+ )for recipient in Recipient.objects.filter(id__in=subscribed_huddle_recipient_ids)]Subscription.objects.bulk_create(subs_to_recreate)+def change_user_is_active(user_profile: UserProfile, value: bool) -> None:+ """+ Helper function for changing the .is_active field. Not meant as a standalone function+ in production code as properly activating/deactivating users requires more steps.+ This changes the is_active value and saves it, while ensuring+ Subscription.is_user_active values are updated in the same db transaction.+ """+ with transaction.atomic(savepoint=False):+ user_profile.is_active = value+ user_profile.save(update_fields=["is_active"])+ Subscription.objects.filter(user_profile=user_profile).update(is_user_active=value)++def do_deactivate_user(user_profile: UserProfile, _cascade: bool = True, *, acting_user: Optional[UserProfile]) -> None:if not user_profile.is_active:return- if user_profile.realm.is_zephyr_mirror_realm: # nocoverage- # For zephyr mirror users, we need to make them a mirror dummy- # again; otherwise, other users won't get the correct behavior- # when trying to send messages to this person inside Zulip.- #- # Ideally, we need to also ensure their zephyr mirroring bot- # isn't running, but that's a separate issue.- user_profile.is_mirror_dummy = True-with transaction.atomic():- user_profile.is_active = False- user_profile.save(update_fields=["is_active", "is_mirror_dummy"])+ if user_profile.realm.is_zephyr_mirror_realm: # nocoverage+ # For zephyr mirror users, we need to make them a mirror dummy+ # again; otherwise, other users won't get the correct behavior+ # when trying to send messages to this person inside Zulip.+ #+ # Ideally, we need to also ensure their zephyr mirroring bot+ # isn't running, but that's a separate issue.+ user_profile.is_mirror_dummy = True+ user_profile.save(update_fields=["is_mirror_dummy"])++ change_user_is_active(user_profile, False)delete_user_sessions(user_profile)clear_scheduled_emails([user_profile.id])@@ -3295,7 +3311,11 @@ def bulk_add_subscriptions(used_colors.add(color)sub = Subscription(- user_profile=user_profile, active=True, color=color, recipient_id=recipient_id+ user_profile=user_profile,+ is_user_active=user_profile.is_active,+ active=True,+ color=color,+ recipient_id=recipient_id,)sub_info = SubInfo(user_profile, sub, stream)subs_to_add.append(sub_info)diff --git a/zerver/lib/bulk_create.py b/zerver/lib/bulk_create.pyindex 3c51265f6b3..1a1840e55c6 100644--- a/zerver/lib/bulk_create.py+++ b/zerver/lib/bulk_create.py@@ -84,9 +84,13 @@ def bulk_create_users(recipients_by_user_id[recipient.type_id] = recipientsubscriptions_to_create: List[Subscription] = []- for user_id in user_ids:- recipient = recipients_by_user_id[user_id]- subscription = Subscription(user_profile_id=user_id, recipient=recipient)+ for user_profile in profiles_to_create:+ recipient = recipients_by_user_id[user_profile.id]+ subscription = Subscription(+ user_profile_id=user_profile.id,+ recipient=recipient,+ is_user_active=user_profile.is_active,+ )subscriptions_to_create.append(subscription)Subscription.objects.bulk_create(subscriptions_to_create)diff --git a/zerver/lib/create_user.py b/zerver/lib/create_user.pyindex a5135084bb5..69a24ea30fd 100644--- a/zerver/lib/create_user.py+++ b/zerver/lib/create_user.py@@ -192,5 +192,7 @@ def create_user(user_profile.recipient = recipientuser_profile.save(update_fields=["recipient"])- Subscription.objects.create(user_profile=user_profile, recipient=recipient)+ Subscription.objects.create(+ user_profile=user_profile, recipient=recipient, is_user_active=user_profile.is_active+ )return user_profilediff --git a/zerver/lib/import_realm.py b/zerver/lib/import_realm.pyindex 89e1d72025b..fad9e40374f 100644--- a/zerver/lib/import_realm.py+++ b/zerver/lib/import_realm.py@@ -655,6 +655,15 @@ def bulk_import_client(data: TableData, model: Any, table: TableName) -> None:update_id_map(table="client", old_id=item["id"], new_id=client.id)+def fix_subscriptions_is_user_active_column(+ data: TableData, user_profiles: List[UserProfile]+) -> None:+ table = get_db_table(Subscription)+ user_id_to_active_status = {user.id: user.is_active for user in user_profiles}+ for sub in data[table]:+ sub["is_user_active"] = user_id_to_active_status[sub["user_profile_id"]]++def process_avatars(record: Dict[str, Any]) -> None:from zerver.lib.upload import upload_backend@@ -1008,6 +1017,7 @@ def do_import_realm(import_dir: Path, subdomain: str, processes: int = 1) -> Reaget_huddles_from_subscription(data, "zerver_subscription")re_map_foreign_keys(data, "zerver_subscription", "recipient", related_table="recipient")update_model_ids(Subscription, data, "subscription")+ fix_subscriptions_is_user_active_column(data, user_profiles)bulk_import_model(data, Subscription)if "zerver_realmauditlog" in data:diff --git a/zerver/migrations/0312_subscription_is_user_active.py b/zerver/migrations/0312_subscription_is_user_active.pynew file mode 100644index 00000000000..decdc144358--- /dev/null+++ b/zerver/migrations/0312_subscription_is_user_active.py@@ -0,0 +1,18 @@+# Generated by Django 3.1.5 on 2021-01-31 15:17++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("zerver", "0311_userprofile_default_view"),+ ]++ operations = [+ migrations.AddField(+ model_name="subscription",+ name="is_user_active",+ field=models.BooleanField(null=True),+ ),+ ]diff --git a/zerver/models.py b/zerver/models.pyindex a9319b55048..64be1654dac 100644--- a/zerver/models.py+++ b/zerver/models.py@@ -2564,6 +2564,13 @@ class Subscription(models.Model):# notification settings, stream color, etc., if the user later# resubscribes.active: bool = models.BooleanField(default=True)+ # This is a denormalization designed to improve the performance of+ # bulk queries of Subscription objects, Whether the subscribed user+ # is active tends to be a key condition in those queries.+ # We intentionally don't specify a default value to promote thinking+ # about this explicitly, as in some special cases, such as data import,+ # we may be creating Subscription objects for a user that's deactivated.+ is_user_active: Optional[bool] = models.BooleanField(null=True)ROLE_STREAM_ADMINISTRATOR = 20ROLE_MEMBER = 50@@ -2846,8 +2853,14 @@ def get_huddle_backend(huddle_hash: str, id_list: List[int]) -> Huddle:huddle.recipient = recipienthuddle.save(update_fields=["recipient"])subs_to_create = [- Subscription(recipient=recipient, user_profile_id=user_profile_id)- for user_profile_id in id_list+ Subscription(+ recipient=recipient,+ user_profile_id=user_profile_id,+ is_user_active=is_active,+ )+ for user_profile_id, is_active in UserProfile.objects.filter(id__in=id_list)+ .distinct("id")+ .values_list("id", "is_active")]Subscription.objects.bulk_create(subs_to_create)return huddlediff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.pyindex ce17e27a9d9..7af6eb92839 100644--- a/zerver/tests/test_auth_backends.py+++ b/zerver/tests/test_auth_backends.py@@ -35,6 +35,7 @@ from social_django.strategy import DjangoStrategyfrom confirmation.models import Confirmation, create_confirmation_linkfrom zerver.lib.actions import (+ change_user_is_active,do_create_realm,do_create_user,do_deactivate_realm,@@ -5872,8 +5873,7 @@ class EmailValidatorTestCase(ZulipTestCase):self.assertEqual(False, is_deactivated)self.assertEqual(error, "Already has an account.")- cordelia.is_active = False- cordelia.save()+ change_user_is_active(cordelia, False)errors = get_existing_user_errors(realm, {cordelia_email})error, is_deactivated = errors[cordelia_email]diff --git a/zerver/tests/test_decorators.py b/zerver/tests/test_decorators.pyindex 528b792a10e..ff26cfce222 100644--- a/zerver/tests/test_decorators.py+++ b/zerver/tests/test_decorators.py@@ -29,6 +29,7 @@ from zerver.decorator import ()from zerver.forms import OurAuthenticationFormfrom zerver.lib.actions import (+ change_user_is_active,do_deactivate_realm,do_deactivate_user,do_reactivate_realm,@@ -390,14 +391,12 @@ class DecoratorTestCase(ZulipTestCase):self.assertEqual(api_result, webhook_bot_email)# Now deactivate the user- webhook_bot.is_active = False- webhook_bot.save()+ change_user_is_active(webhook_bot, False)with self.assertRaisesRegex(JsonableError, "Account is deactivated"):my_webhook(request)# Reactive the user, but deactivate their realm.- webhook_bot.is_active = True- webhook_bot.save()+ change_user_is_active(webhook_bot, True)webhook_bot.realm.deactivated = Truewebhook_bot.realm.save()with self.assertRaisesRegex(JsonableError, "This organization has been deactivated"):@@ -1128,8 +1127,7 @@ class LoginRequiredTest(ZulipTestCase):self.assert_in_response("I agree to the", result)# Verify fails if user deactivated (with session still valid)- user_profile.is_active = False- user_profile.save()+ change_user_is_active(user_profile, False)result = self.client_get("/accounts/accept_terms/")self.assertEqual(result.status_code, 302)@@ -1200,8 +1198,7 @@ class InactiveUserTest(ZulipTestCase):# Even if a logged-in session was leaked, it still wouldn't workdo_reactivate_user(user_profile, acting_user=None)self.login_user(user_profile)- user_profile.is_active = False- user_profile.save()+ change_user_is_active(user_profile, False)result = self.client_post("/json/messages",@@ -1238,8 +1235,8 @@ class InactiveUserTest(ZulipTestCase):user_profile.save()self.login_by_email(email, password=test_password)- user_profile.is_active = False- user_profile.save()+ change_user_is_active(user_profile, False)+result = self.client_post("/json/fetch_api_key", {"password": test_password})self.assert_json_error_contains(result, "Account is deactivated", status_code=400)@@ -1366,11 +1363,11 @@ class TestValidateApiKey(ZulipTestCase):validate_api_key(HostRequestMock(), self.webhook_bot.email, api_key)def test_validate_api_key_if_profile_is_not_active(self) -> None:- self._change_is_active_field(self.default_bot, False)+ change_user_is_active(self.default_bot, False)with self.assertRaises(JsonableError):api_key = get_api_key(self.default_bot)validate_api_key(HostRequestMock(), self.default_bot.email, api_key)- self._change_is_active_field(self.default_bot, True)+ change_user_is_active(self.default_bot, True)def test_validate_api_key_if_profile_is_incoming_webhook_and_is_webhook_is_unset(self) -> None:with self.assertRaises(JsonableError), self.assertLogs(level="WARNING") as root_warn_log:@@ -1439,10 +1436,6 @@ class TestValidateApiKey(ZulipTestCase):],)- def _change_is_active_field(self, profile: UserProfile, value: bool) -> None:- profile.is_active = value- profile.save()-class TestInternalNotifyView(ZulipTestCase):BORING_RESULT = "boring"@@ -1653,8 +1646,7 @@ class TestAuthenticatedJsonPostViewDecorator(ZulipTestCase):user_profile = self.example_user("hamlet")self.login_user(user_profile)# we deactivate user manually because do_deactivate_user removes user session- user_profile.is_active = False- user_profile.save()+ change_user_is_active(user_profile, False)self.assert_json_error_contains(self._do_test(user_profile), "Account is deactivated")do_reactivate_user(user_profile, acting_user=None)diff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.pyindex 6bd46fac50f..a0eae9f6227 100644--- a/zerver/tests/test_home.py+++ b/zerver/tests/test_home.py@@ -10,7 +10,12 @@ from django.http import HttpResponsefrom django.utils.timezone import now as timezone_nowfrom corporate.models import Customer, CustomerPlan-from zerver.lib.actions import do_change_logo_source, do_change_plan_type, do_create_user+from zerver.lib.actions import (+ change_user_is_active,+ do_change_logo_source,+ do_change_plan_type,+ do_create_user,+)from zerver.lib.events import add_realm_logo_fieldsfrom zerver.lib.home import get_furthest_read_timefrom zerver.lib.soft_deactivation import do_soft_deactivate_users@@ -500,8 +505,7 @@ class HomeTest(ZulipTestCase):# Doing a full-stack deactivation would be expensive here,# and we really only need to flip the flag to get a valid# test.- user.is_active = False- user.save()+ change_user_is_active(user, False)return userdef test_signup_notifications_stream(self) -> None:diff --git a/zerver/tests/test_import_export.py b/zerver/tests/test_import_export.pyindex 2c0b0555876..6787a946f70 100644--- a/zerver/tests/test_import_export.py+++ b/zerver/tests/test_import_export.py@@ -14,6 +14,7 @@ from zerver.lib.actions import (do_change_logo_source,do_change_plan_type,do_create_user,+ do_deactivate_user,do_update_user_presence,)from zerver.lib.avatar_hash import user_avatar_path@@ -766,6 +767,9 @@ class ImportExportTest(ZulipTestCase):original_realm = Realm.objects.get(string_id="zulip")RealmEmoji.objects.get(realm=original_realm).delete()++ # Deactivate a user to ensure such a case is covered.+ do_deactivate_user(self.example_user("aaron"), acting_user=None)# data to test import of huddleshuddle = [self.example_user("hamlet"),@@ -1123,6 +1127,18 @@ class ImportExportTest(ZulipTestCase):Recipient.objects.get(type=Recipient.HUDDLE, type_id=huddle_object.id).id,)+ for user_profile in UserProfile.objects.filter(realm=imported_realm):+ # Check that all Subscriptions have the correct is_user_active set.+ self.assertEqual(+ Subscription.objects.filter(+ user_profile=user_profile, is_user_active=user_profile.is_active+ ).count(),+ Subscription.objects.filter(user_profile=user_profile).count(),+ )+ # Verify that we've actually tested something meaningful instead of a blind import+ # with is_user_active=True used for everything.+ self.assertTrue(Subscription.objects.filter(is_user_active=False).exists())+def test_import_files_from_local(self) -> None:realm = Realm.objects.get(string_id="zulip")self._setup_export_files(realm)diff --git a/zerver/tests/test_markdown.py b/zerver/tests/test_markdown.pyindex f7be9b03ad8..b5b7be79e2e 100644--- a/zerver/tests/test_markdown.py+++ b/zerver/tests/test_markdown.py@@ -11,6 +11,7 @@ from django.test import override_settingsfrom markdown import Markdownfrom zerver.lib.actions import (+ change_user_is_active,do_add_alert_words,do_create_realm,do_remove_realm_emoji,@@ -218,14 +219,12 @@ class MarkdownMiscTest(ZulipTestCase):)fred1 = make_user("[email protected]", "Fred Flintstone")- fred1.is_active = False- fred1.save()+ change_user_is_active(fred1, False)fred2 = make_user("[email protected]", "Fred Flintstone")fred3 = make_user("[email protected]", "Fred Flintstone")- fred3.is_active = False- fred3.save()+ change_user_is_active(fred3, False)fred4 = make_user("[email protected]", "Fred Flintstone")diff --git a/zerver/tests/test_message_send.py b/zerver/tests/test_message_send.pyindex b360594c6d4..fbe03e043d0 100644--- a/zerver/tests/test_message_send.py+++ b/zerver/tests/test_message_send.py@@ -1497,6 +1497,7 @@ class StreamMessagesTest(ZulipTestCase):)Subscription.objects.create(user_profile=user,+ is_user_active=user.is_active,recipient=recipient,)diff --git a/zerver/tests/test_sessions.py b/zerver/tests/test_sessions.pyindex 17e388926a9..ad095bc60e3 100644--- a/zerver/tests/test_sessions.py+++ b/zerver/tests/test_sessions.py@@ -4,6 +4,7 @@ from unittest import mockfrom django.utils.timezone import now as timezone_now+from zerver.lib.actions import change_user_is_activefrom zerver.lib.sessions import (delete_all_deactivated_user_sessions,delete_all_user_sessions,@@ -98,8 +99,7 @@ class TestSessions(ZulipTestCase):user_profile_3 = self.example_user("cordelia")self.login_user(user_profile_3)self.assertIn("_auth_user_id", self.client.session)- user_profile_3.is_active = False- user_profile_3.save()+ change_user_is_active(user_profile_3, False)with self.assertLogs(level="INFO") as info_logs:delete_all_deactivated_user_sessions()self.assertEqual(diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.pyindex 0419e73e4bf..bfff8c8ecd4 100644--- a/zerver/tests/test_signup.py+++ b/zerver/tests/test_signup.py@@ -33,6 +33,7 @@ from zerver.decorator import do_two_factor_loginfrom zerver.forms import HomepageForm, check_subdomain_availablefrom zerver.lib.actions import (add_new_user_history,+ change_user_is_active,do_add_default_stream,do_change_full_name,do_change_realm_subdomain,@@ -1107,8 +1108,8 @@ class InviteUserTest(InviteUserBase):mirror_user = self.example_user("cordelia")mirror_user.is_mirror_dummy = True- mirror_user.is_active = Falsemirror_user.save()+ change_user_is_active(mirror_user, False)self.assertEqual(PreregistrationUser.objects.filter(email=mirror_user.email).count(),@@ -4460,8 +4461,8 @@ class UserSignUpTest(InviteUserBase):user_profile = self.mit_user("sipbtest")email = user_profile.delivery_emailuser_profile.is_mirror_dummy = True- user_profile.is_active = Falseuser_profile.save()+ change_user_is_active(user_profile, False)result = self.client_post("/register/", {"email": email}, subdomain="zephyr")@@ -4487,8 +4488,8 @@ class UserSignUpTest(InviteUserBase):# If the mirror dummy user is already active, attempting to# submit the registration form should raise an AssertionError# (this is an invalid state, so it's a bug we got here):- user_profile.is_active = True- user_profile.save()+ change_user_is_active(user_profile, True)+with self.assertRaisesRegex(AssertionError, "Mirror dummy user is already active!"), self.assertLogs("django.request", "ERROR") as error_log:@@ -4509,8 +4510,7 @@ class UserSignUpTest(InviteUserBase):"AssertionError: Mirror dummy user is already active!" in error_log.output[0])- user_profile.is_active = False- user_profile.save()+ change_user_is_active(user_profile, False)result = self.submit_reg_form_for_user(email,@@ -4537,8 +4537,8 @@ class UserSignUpTest(InviteUserBase):user_profile = self.mit_user("sipbtest")email = user_profile.delivery_emailuser_profile.is_mirror_dummy = True- user_profile.is_active = Trueuser_profile.save()+ change_user_is_active(user_profile, True)with self.assertRaisesRegex(AssertionError, "Mirror dummy user is already active!"@@ -4619,9 +4619,10 @@ class DeactivateUserTest(ZulipTestCase):def test_do_not_deactivate_final_user(self) -> None:realm = get_realm("zulip")- UserProfile.objects.filter(realm=realm).exclude(role=UserProfile.ROLE_REALM_OWNER).update(- is_active=False- )+ for user_profile in UserProfile.objects.filter(realm=realm).exclude(+ role=UserProfile.ROLE_REALM_OWNER+ ):+ do_deactivate_user(user_profile, acting_user=None)user = self.example_user("desdemona")self.login_user(user)result = self.client_delete("/json/users/me")diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.pyindex 02e1b4be6fb..5bffe1f9e82 100644--- a/zerver/tests/test_users.py+++ b/zerver/tests/test_users.py@@ -11,6 +11,7 @@ from django.test import override_settingsfrom django.utils.timezone import now as timezone_nowfrom zerver.lib.actions import (+ change_user_is_active,create_users,do_change_can_create_users,do_change_user_role,@@ -1050,8 +1051,7 @@ class UserProfileTest(ZulipTestCase):check_valid_user_ids(get_realm("zephyr").id, [hamlet.id])# User is not active- hamlet.is_active = False- hamlet.save()+ change_user_is_active(hamlet, False)with self.assertRaisesRegex(ValidationError, rf"User with ID {hamlet.id} is deactivated"):check_valid_user_ids(realm.id, [hamlet.id])check_valid_user_ids(realm.id, [hamlet.id], allow_deactivated=True)@@ -1331,6 +1331,22 @@ class ActivateTest(ZulipTestCase):do_reactivate_user(user, acting_user=None)self.assertTrue(user.is_active)+ def test_subscriptions_is_user_active(self) -> None:+ user = self.example_user("hamlet")+ do_deactivate_user(user, acting_user=None)+ self.assertFalse(user.is_active)+ self.assertTrue(Subscription.objects.filter(user_profile=user).exists())+ self.assertFalse(+ Subscription.objects.filter(user_profile=user, is_user_active=True).exists()+ )++ do_reactivate_user(user, acting_user=None)+ self.assertTrue(user.is_active)+ self.assertTrue(Subscription.objects.filter(user_profile=user).exists())+ self.assertFalse(+ Subscription.objects.filter(user_profile=user, is_user_active=False).exists()+ )+def test_api(self) -> None:admin = self.example_user("othello")do_change_user_role(admin, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None)diff --git a/zerver/views/development/email_log.py b/zerver/views/development/email_log.pyindex 2d5947b4029..d6a845b9c11 100755--- a/zerver/views/development/email_log.py+++ b/zerver/views/development/email_log.py@@ -9,7 +9,11 @@ from django.shortcuts import redirect, renderfrom django.views.decorators.http import require_safefrom confirmation.models import Confirmation, confirmation_url-from zerver.lib.actions import do_change_user_delivery_email, do_send_realm_reactivation_email+from zerver.lib.actions import (+ change_user_is_active,+ do_change_user_delivery_email,+ do_send_realm_reactivation_email,+)from zerver.lib.email_notifications import enqueue_welcome_emailsfrom zerver.lib.response import json_successfrom zerver.models import Realm, get_realm, get_realm_stream, get_user_by_delivery_email@@ -71,12 +75,10 @@ def generate_all_emails(request: HttpRequest) -> HttpResponse:result = client.post("/accounts/password/reset/", {"email": registered_email}, **host_kwargs)assert result.status_code == 302# deactivated user- user.is_active = False- user.save(update_fields=["is_active"])+ change_user_is_active(user, False)result = client.post("/accounts/password/reset/", {"email": registered_email}, **host_kwargs)assert result.status_code == 302- user.is_active = True- user.save(update_fields=["is_active"])+ change_user_is_active(user, True)# account on different realmresult = client.post("/accounts/password/reset/", {"email": registered_email}, HTTP_HOST=other_realm.hostdiff --git a/zilencer/management/commands/populate_db.py b/zilencer/management/commands/populate_db.pyindex 3e8c534647e..6a6c41c9e26 100644--- a/zilencer/management/commands/populate_db.py+++ b/zilencer/management/commands/populate_db.py@@ -134,6 +134,7 @@ def subscribe_users_to_streams(realm: Realm, stream_dict: Dict[str, Dict[str, Ans = Subscription(recipient=recipient,user_profile=profile,+ is_user_active=profile.is_active,color=STREAM_ASSIGNMENT_COLORS[i % len(STREAM_ASSIGNMENT_COLORS)],)subscriptions_to_add.append(s)@@ -569,7 +570,12 @@ class Command(BaseCommand):for profile, recipient in subscriptions_list:i += 1color = STREAM_ASSIGNMENT_COLORS[i % len(STREAM_ASSIGNMENT_COLORS)]- s = Subscription(recipient=recipient, user_profile=profile, color=color)+ s = Subscription(+ recipient=recipient,+ user_profile=profile,+ is_user_active=profile.is_active,+ color=color,+ )subscriptions_to_add.append(s)diff --git a/zproject/computed_settings.py b/zproject/computed_settings.pyindex eb21ef85791..f22f5254dbb 100644--- a/zproject/computed_settings.py+++ b/zproject/computed_settings.py@@ -242,6 +242,9 @@ SILENCED_SYSTEM_CHECKS = [# backends support the username not being unique; and they do.# See: https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#django.contrib.auth.models.CustomUser.USERNAME_FIELD"auth.W004",+ # models.E034 limits index names to 30 characters for Oracle compatibility.+ # We aren't using Oracle.+ "models.E034",]########################################################################