def test_delete_all_deactivated_user_sessions(self) -> None: # Test that no exception is thrown with a logged-out session self.login("othello") self.assertIn("_auth_user_id", self.client.session) self.client_post("/accounts/logout/") delete_all_deactivated_user_sessions() result = self.client_get("/") self.assertEqual(result.status_code, 200) self.assertTrue('is_spectator":true' in str(result.content)) # Test nothing happens to an active user's session self.login("othello") self.assertIn("_auth_user_id", self.client.session) delete_all_deactivated_user_sessions() self.assertIn("_auth_user_id", self.client.session) # Test that a deactivated session gets logged out user_profile_3 = self.example_user("cordelia") self.login_user(user_profile_3) self.assertIn("_auth_user_id", self.client.session) change_user_is_active(user_profile_3, False) with self.assertLogs(level="INFO") as info_logs: delete_all_deactivated_user_sessions() self.assertEqual( info_logs.output, [f"INFO:root:Deactivating session for deactivated user {user_profile_3.id}"], ) result = self.client_get("/") self.assertEqual(result.status_code, 200) self.assertTrue('is_spectator":true' in str(result.content))
def do_reactivate_user(user_profile: UserProfile, *, acting_user: Optional[UserProfile]) -> None: """Reactivate a user that had previously been deactivated""" with transaction.atomic(): change_user_is_active(user_profile, True) event_time = timezone_now() RealmAuditLog.objects.create( realm=user_profile.realm, modified_user=user_profile, acting_user=acting_user, event_type=RealmAuditLog.USER_REACTIVATED, event_time=event_time, extra_data=orjson.dumps({ RealmAuditLog.ROLE_COUNT: realm_user_count_by_role(user_profile.realm), }).decode(), ) do_increment_logging_stat( user_profile.realm, COUNT_STATS["active_users_log:is_bot:day"], user_profile.is_bot, event_time, ) if settings.BILLING_ENABLED: update_license_ledger_if_needed(user_profile.realm, event_time) notify_created_user(user_profile) if user_profile.is_bot: notify_created_bot(user_profile) subscribed_recipient_ids = Subscription.objects.filter( user_profile_id=user_profile.id, active=True, recipient__type=Recipient.STREAM).values_list("recipient__type_id", flat=True) subscribed_streams = Stream.objects.filter(id__in=subscribed_recipient_ids, deactivated=False) subscriber_peer_info = bulk_get_subscriber_peer_info( realm=user_profile.realm, streams=subscribed_streams, ) altered_user_dict: Dict[int, Set[int]] = defaultdict(set) for stream in subscribed_streams: altered_user_dict[stream.id] = {user_profile.id} stream_dict = {stream.id: stream for stream in subscribed_streams} send_peer_subscriber_events( op="peer_add", realm=user_profile.realm, altered_user_dict=altered_user_dict, stream_dict=stream_dict, private_peer_dict=subscriber_peer_info.private_peer_dict, )
def create_non_active_user(self, realm: Realm, email: str, name: str) -> UserProfile: user = do_create_user( email=email, password="******", realm=realm, full_name=name, acting_user=None ) # Doing a full-stack deactivation would be expensive here, # and we really only need to flip the flag to get a valid # test. change_user_is_active(user, False) return user
def do_activate_mirror_dummy_user(user_profile: UserProfile, *, acting_user: Optional[UserProfile]) -> None: """Called to have a user "take over" a "mirror dummy" user (i.e. is_mirror_dummy=True) account when they sign up with the same email address. Essentially, the result should be as though we had created the UserProfile just now with do_create_user, except that the mirror dummy user may appear as the recipient or sender of messages from before their account was fully created. TODO: This function likely has bugs resulting from this being a parallel code path to do_create_user; e.g. it likely does not handle preferences or default streams properly. """ with transaction.atomic(): change_user_is_active(user_profile, True) user_profile.is_mirror_dummy = False user_profile.set_unusable_password() user_profile.date_joined = timezone_now() user_profile.tos_version = settings.TERMS_OF_SERVICE_VERSION user_profile.save(update_fields=[ "date_joined", "password", "is_mirror_dummy", "tos_version" ]) event_time = user_profile.date_joined RealmAuditLog.objects.create( realm=user_profile.realm, modified_user=user_profile, acting_user=acting_user, event_type=RealmAuditLog.USER_ACTIVATED, event_time=event_time, extra_data=orjson.dumps({ RealmAuditLog.ROLE_COUNT: realm_user_count_by_role(user_profile.realm), }).decode(), ) do_increment_logging_stat( user_profile.realm, COUNT_STATS["active_users_log:is_bot:day"], user_profile.is_bot, event_time, ) if settings.BILLING_ENABLED: update_license_ledger_if_needed(user_profile.realm, event_time) notify_created_user(user_profile)
def generate_all_emails(request: HttpRequest) -> HttpResponse: if not settings.TEST_SUITE: # nocoverage # It's really convenient to automatically inline the email CSS # here, since that saves a step when testing out changes to # the email CSS. But we don't run this inside the test suite, # because by role, the tests shouldn't be doing a provision-like thing. subprocess.check_call(["./scripts/setup/inline_email_css.py"]) # We import the Django test client inside the view function, # because it isn't needed in production elsewhere, and not # importing it saves ~50ms of unnecessary manage.py startup time. from django.test import Client client = Client() # write fake data for all variables registered_email = "*****@*****.**" unregistered_email_1 = "*****@*****.**" unregistered_email_2 = "*****@*****.**" invite_expires_in_minutes = settings.INVITATION_LINK_VALIDITY_MINUTES realm = get_realm("zulip") other_realm = Realm.objects.exclude(string_id="zulip").first() user = get_user_by_delivery_email(registered_email, realm) host_kwargs = {"HTTP_HOST": realm.host} # Password reset emails # active account in realm result = client.post("/accounts/password/reset/", {"email": registered_email}, **host_kwargs) assert result.status_code == 302 # deactivated user change_user_is_active(user, False) result = client.post("/accounts/password/reset/", {"email": registered_email}, **host_kwargs) assert result.status_code == 302 change_user_is_active(user, True) # account on different realm assert other_realm is not None result = client.post( "/accounts/password/reset/", {"email": registered_email}, HTTP_HOST=other_realm.host ) assert result.status_code == 302 # no account anywhere result = client.post( "/accounts/password/reset/", {"email": unregistered_email_1}, **host_kwargs ) assert result.status_code == 302 # Confirm account email result = client.post("/accounts/home/", {"email": unregistered_email_1}, **host_kwargs) assert result.status_code == 302 # Find account email result = client.post("/accounts/find/", {"emails": registered_email}, **host_kwargs) assert result.status_code == 302 # New login email logged_in = client.login(dev_auth_username=registered_email, realm=realm) assert logged_in # New user invite and reminder emails stream = get_realm_stream("Denmark", user.realm.id) result = client.post( "/json/invites", { "invitee_emails": unregistered_email_2, "invite_expires_in_minutes": invite_expires_in_minutes, "stream_ids": orjson.dumps([stream.id]).decode(), }, **host_kwargs, ) assert result.status_code == 200 # Verification for new email result = client.patch( "/json/settings", urllib.parse.urlencode({"email": "*****@*****.**"}), **host_kwargs ) assert result.status_code == 200 # Email change successful key = Confirmation.objects.filter(type=Confirmation.EMAIL_CHANGE).latest("id").confirmation_key url = confirmation_url(key, realm, Confirmation.EMAIL_CHANGE) user_profile = get_user_by_delivery_email(registered_email, realm) result = client.get(url) assert result.status_code == 200 # Reset the email value so we can run this again do_change_user_delivery_email(user_profile, registered_email) # Follow up day1 day2 emails for normal user enqueue_welcome_emails(user_profile) # Follow up day1 day2 emails for admin user enqueue_welcome_emails(get_user_by_delivery_email("*****@*****.**", realm), realm_creation=True) # Realm reactivation email do_send_realm_reactivation_email(realm, acting_user=None) return redirect(email_page)