def handle(self, *args: Any, **options: str) -> None:
     realm = self.get_realm(options)
     assert realm is not None
     if not realm.deactivated:
         raise CommandError("The realm %s is already active." % (realm.name,))
     print('Sending email to admins')
     do_send_realm_reactivation_email(realm)
     print('Done!')
Beispiel #2
0
 def test_do_send_realm_reactivation_email(self) -> None:
     realm = get_realm('zulip')
     do_send_realm_reactivation_email(realm)
     from django.core.mail import outbox
     self.assertEqual(len(outbox), 1)
     from_email = outbox[0].from_email
     tokenized_no_reply_email = parseaddr(from_email)[1]
     self.assertIn("Zulip Account Security", from_email)
     self.assertTrue(re.search(self.TOKENIZED_NOREPLY_REGEX, tokenized_no_reply_email))
     self.assertIn('Reactivate your Zulip organization', outbox[0].subject)
     self.assertIn('Dear former administrators', outbox[0].body)
     admins = realm.get_admin_users()
     confirmation_url = self.get_confirmation_url_from_outbox(admins[0].email)
     response = self.client_get(confirmation_url)
     self.assert_in_success_response(['Your organization has been successfully reactivated'], response)
     realm = get_realm('zulip')
     self.assertFalse(realm.deactivated)
Beispiel #3
0
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(["./tools/inline-email-css"])

    # 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 = "*****@*****.**"
    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
    user.is_active = False
    user.save(update_fields=['is_active'])
    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'])
    # account on different realm
    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
    result = client.post("/json/invites",
                         {"invitee_emails": unregistered_email_2, "stream": ["Denmark"]},
                         **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.host, 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)

    return redirect(email_page)
Beispiel #4
0
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(["./tools/inline-email-css"])

    # 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 = "*****@*****.**"
    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
    user.is_active = False
    user.save(update_fields=['is_active'])
    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'])
    # account on different realm
    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", get_realm("zulip"))
    result = client.post(
        "/json/invites", {
            "invitee_emails": unregistered_email_2,
            "stream_ids": ujson.dumps([stream.id])
        }, **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.host, 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)

    return redirect(email_page)
Beispiel #5
0
    def test_search(self) -> None:
        reset_emails_in_zulip_realm()

        def check_hamlet_user_query_result(result: HttpResponse) -> None:
            self.assert_in_success_response([
                '<span class="label">user</span>\n',
                '<h3>King Hamlet</h3>',
                '<b>Email</b>: [email protected]',
                '<b>Is active</b>: True<br>',
                '<b>Admins</b>: [email protected], [email protected]\n',
                'class="copy-button" data-copytext="[email protected], [email protected]"',
            ], result)

        def check_zulip_realm_query_result(result: HttpResponse) -> None:
            zulip_realm = get_realm("zulip")
            self.assert_in_success_response([
                f'<input type="hidden" name="realm_id" value="{zulip_realm.id}"',
                'Zulip Dev</h3>',
                '<option value="1" selected>Self hosted</option>',
                '<option value="2" >Limited</option>',
                'input type="number" name="discount" value="None"',
                '<option value="active" selected>Active</option>',
                '<option value="deactivated" >Deactivated</option>',
                'scrub-realm-button">', 'data-string-id="zulip"'
            ], result)

        def check_lear_realm_query_result(result: HttpResponse) -> None:
            lear_realm = get_realm("lear")
            self.assert_in_success_response([
                f'<input type="hidden" name="realm_id" value="{lear_realm.id}"',
                'Lear &amp; Co.</h3>',
                '<option value="1" selected>Self hosted</option>',
                '<option value="2" >Limited</option>',
                'input type="number" name="discount" value="None"',
                '<option value="active" selected>Active</option>',
                '<option value="deactivated" >Deactivated</option>',
                'scrub-realm-button">', 'data-string-id="lear"',
                '<b>Name</b>: Zulip Standard', '<b>Status</b>: Active',
                '<b>Billing schedule</b>: Annual',
                '<b>Licenses</b>: 2/10 (Manual)',
                '<b>Price per license</b>: $80.0',
                '<b>Next invoice date</b>: 02 January 2017',
                '<option value="send_invoice" selected>',
                '<option value="charge_automatically" >'
            ], result)

        def check_preregistration_user_query_result(
                result: HttpResponse,
                email: str,
                invite: bool = False) -> None:
            self.assert_in_success_response([
                '<span class="label">preregistration user</span>\n',
                f'<b>Email</b>: {email}',
            ], result)
            if invite:
                self.assert_in_success_response(
                    ['<span class="label">invite</span>'], result)
                self.assert_in_success_response([
                    '<b>Expires in</b>: 1\xa0week, 3',
                    '<b>Status</b>: Link has never been clicked'
                ], result)
                self.assert_in_success_response([], result)
            else:
                self.assert_not_in_success_response(
                    ['<span class="label">invite</span>'], result)
                self.assert_in_success_response([
                    '<b>Expires in</b>: 1\xa0day',
                    '<b>Status</b>: Link has never been clicked'
                ], result)

        def check_realm_creation_query_result(result: HttpResponse,
                                              email: str) -> None:
            self.assert_in_success_response([
                '<span class="label">preregistration user</span>\n',
                '<span class="label">realm creation</span>\n',
                '<b>Link</b>: http://testserver/accounts/do_confirm/',
                '<b>Expires in</b>: 1\xa0day<br>\n',
            ], result)

        def check_multiuse_invite_link_query_result(
                result: HttpResponse) -> None:
            self.assert_in_success_response([
                '<span class="label">multiuse invite</span>\n',
                '<b>Link</b>: http://zulip.testserver/join/',
                '<b>Expires in</b>: 1\xa0week, 3',
            ], result)

        def check_realm_reactivation_link_query_result(
                result: HttpResponse) -> None:
            self.assert_in_success_response([
                '<span class="label">realm reactivation</span>\n',
                '<b>Link</b>: http://zulip.testserver/reactivate/',
                '<b>Expires in</b>: 1\xa0day',
            ], result)

        self.login('cordelia')

        result = self.client_get("/activity/support")
        self.assertEqual(result.status_code, 302)
        self.assertEqual(result["Location"], "/login/")

        self.login('iago')

        customer = Customer.objects.create(realm=get_realm("lear"),
                                           stripe_customer_id='cus_123')
        now = datetime(2016, 1, 2, tzinfo=timezone.utc)
        plan = CustomerPlan.objects.create(
            customer=customer,
            billing_cycle_anchor=now,
            billing_schedule=CustomerPlan.ANNUAL,
            tier=CustomerPlan.STANDARD,
            price_per_license=8000,
            next_invoice_date=add_months(now, 12))
        LicenseLedger.objects.create(licenses=10,
                                     licenses_at_next_renewal=10,
                                     event_time=timezone_now(),
                                     is_renewal=True,
                                     plan=plan)

        result = self.client_get("/activity/support")
        self.assert_in_success_response(
            ['<input type="text" name="q" class="input-xxlarge search-query"'],
            result)

        result = self.client_get("/activity/support",
                                 {"q": "*****@*****.**"})
        check_hamlet_user_query_result(result)
        check_zulip_realm_query_result(result)

        result = self.client_get("/activity/support", {"q": "lear"})
        check_lear_realm_query_result(result)

        result = self.client_get("/activity/support",
                                 {"q": "http://lear.testserver"})
        check_lear_realm_query_result(result)

        with self.settings(REALM_HOSTS={'zulip': 'localhost'}):
            result = self.client_get("/activity/support",
                                     {"q": "http://localhost"})
            check_zulip_realm_query_result(result)

        result = self.client_get("/activity/support",
                                 {"q": "[email protected], lear"})
        check_hamlet_user_query_result(result)
        check_zulip_realm_query_result(result)
        check_lear_realm_query_result(result)

        result = self.client_get("/activity/support",
                                 {"q": "lear, Hamlet <*****@*****.**>"})
        check_hamlet_user_query_result(result)
        check_zulip_realm_query_result(result)
        check_lear_realm_query_result(result)

        self.client_post('/accounts/home/',
                         {'email': self.nonreg_email("test")})
        self.login('iago')
        result = self.client_get("/activity/support",
                                 {"q": self.nonreg_email("test")})
        check_preregistration_user_query_result(result,
                                                self.nonreg_email("test"))
        check_zulip_realm_query_result(result)

        stream_ids = [self.get_stream_id("Denmark")]
        invitee_emails = [self.nonreg_email("test1")]
        self.client_post(
            "/json/invites", {
                "invitee_emails": invitee_emails,
                "stream_ids": orjson.dumps(stream_ids).decode(),
                "invite_as": PreregistrationUser.INVITE_AS['MEMBER']
            })
        result = self.client_get("/activity/support",
                                 {"q": self.nonreg_email("test1")})
        check_preregistration_user_query_result(result,
                                                self.nonreg_email("test1"),
                                                invite=True)
        check_zulip_realm_query_result(result)

        email = self.nonreg_email('alice')
        self.client_post('/new/', {'email': email})
        result = self.client_get("/activity/support", {"q": email})
        check_realm_creation_query_result(result, email)

        do_create_multiuse_invite_link(self.example_user("hamlet"),
                                       invited_as=1)
        result = self.client_get("/activity/support", {"q": "zulip"})
        check_multiuse_invite_link_query_result(result)
        check_zulip_realm_query_result(result)
        MultiuseInvite.objects.all().delete()

        do_send_realm_reactivation_email(get_realm("zulip"))
        result = self.client_get("/activity/support", {"q": "zulip"})
        check_realm_reactivation_link_query_result(result)
        check_zulip_realm_query_result(result)
Beispiel #6
0
    def test_search(self) -> None:
        reset_emails_in_zulip_realm()

        def assert_user_details_in_html_response(
            html_response: HttpResponse, full_name: str, email: str, role: str
        ) -> None:
            self.assert_in_success_response(
                [
                    '<span class="label">user</span>\n',
                    f"<h3>{full_name}</h3>",
                    f"<b>Email</b>: {email}",
                    "<b>Is active</b>: True<br />",
                    f"<b>Role</b>: {role}<br />",
                ],
                html_response,
            )

        def check_hamlet_user_query_result(result: HttpResponse) -> None:
            assert_user_details_in_html_response(
                result, "King Hamlet", self.example_email("hamlet"), "Member"
            )
            self.assert_in_success_response(
                [
                    f"<b>Admins</b>: {self.example_email('iago')}\n",
                    f"<b>Owners</b>: {self.example_email('desdemona')}\n",
                    'class="copy-button" data-copytext="{}">'.format(self.example_email("iago")),
                    'class="copy-button" data-copytext="{}">'.format(
                        self.example_email("desdemona")
                    ),
                ],
                result,
            )

        def check_othello_user_query_result(result: HttpResponse) -> None:
            assert_user_details_in_html_response(
                result, "Othello, the Moor of Venice", self.example_email("othello"), "Member"
            )

        def check_polonius_user_query_result(result: HttpResponse) -> None:
            assert_user_details_in_html_response(
                result, "Polonius", self.example_email("polonius"), "Guest"
            )

        def check_zulip_realm_query_result(result: HttpResponse) -> None:
            zulip_realm = get_realm("zulip")
            first_human_user = zulip_realm.get_first_human_user()
            assert first_human_user is not None
            self.assert_in_success_response(
                [
                    f"<b>First human user</b>: {first_human_user.delivery_email}\n",
                    f'<input type="hidden" name="realm_id" value="{zulip_realm.id}"',
                    "Zulip Dev</h3>",
                    '<option value="1" selected>Self hosted</option>',
                    '<option value="2" >Limited</option>',
                    'input type="number" name="discount" value="None"',
                    '<option value="active" selected>Active</option>',
                    '<option value="deactivated" >Deactivated</option>',
                    f'<option value="{zulip_realm.org_type}" selected>',
                    'scrub-realm-button">',
                    'data-string-id="zulip"',
                ],
                result,
            )

        def check_lear_realm_query_result(result: HttpResponse) -> None:
            lear_realm = get_realm("lear")
            self.assert_in_success_response(
                [
                    f'<input type="hidden" name="realm_id" value="{lear_realm.id}"',
                    "Lear &amp; Co.</h3>",
                    '<option value="1" selected>Self hosted</option>',
                    '<option value="2" >Limited</option>',
                    'input type="number" name="discount" value="None"',
                    '<option value="active" selected>Active</option>',
                    '<option value="deactivated" >Deactivated</option>',
                    'scrub-realm-button">',
                    'data-string-id="lear"',
                    "<b>Name</b>: Zulip Standard",
                    "<b>Status</b>: Active",
                    "<b>Billing schedule</b>: Annual",
                    "<b>Licenses</b>: 2/10 (Manual)",
                    "<b>Price per license</b>: $80.0",
                    "<b>Next invoice date</b>: 02 January 2017",
                    '<option value="send_invoice" selected>',
                    '<option value="charge_automatically" >',
                ],
                result,
            )

        def check_preregistration_user_query_result(
            result: HttpResponse, email: str, invite: bool = False
        ) -> None:
            self.assert_in_success_response(
                [
                    '<span class="label">preregistration user</span>\n',
                    f"<b>Email</b>: {email}",
                ],
                result,
            )
            if invite:
                self.assert_in_success_response(['<span class="label">invite</span>'], result)
                self.assert_in_success_response(
                    [
                        "<b>Expires in</b>: 1\xa0week, 3\xa0days",
                        "<b>Status</b>: Link has never been clicked",
                    ],
                    result,
                )
                self.assert_in_success_response([], result)
            else:
                self.assert_not_in_success_response(['<span class="label">invite</span>'], result)
                self.assert_in_success_response(
                    [
                        "<b>Expires in</b>: 1\xa0day",
                        "<b>Status</b>: Link has never been clicked",
                    ],
                    result,
                )

        def check_realm_creation_query_result(result: HttpResponse, email: str) -> None:
            self.assert_in_success_response(
                [
                    '<span class="label">preregistration user</span>\n',
                    '<span class="label">realm creation</span>\n',
                    "<b>Link</b>: http://testserver/accounts/do_confirm/",
                    "<b>Expires in</b>: 1\xa0day",
                ],
                result,
            )

        def check_multiuse_invite_link_query_result(result: HttpResponse) -> None:
            self.assert_in_success_response(
                [
                    '<span class="label">multiuse invite</span>\n',
                    "<b>Link</b>: http://zulip.testserver/join/",
                    "<b>Expires in</b>: 1\xa0week, 3\xa0days",
                ],
                result,
            )

        def check_realm_reactivation_link_query_result(result: HttpResponse) -> None:
            self.assert_in_success_response(
                [
                    '<span class="label">realm reactivation</span>\n',
                    "<b>Link</b>: http://zulip.testserver/reactivate/",
                    "<b>Expires in</b>: 1\xa0day",
                ],
                result,
            )

        self.login("cordelia")

        result = self.client_get("/activity/support")
        self.assertEqual(result.status_code, 302)
        self.assertEqual(result["Location"], "/login/")

        self.login("iago")

        do_set_realm_property(
            get_realm("zulip"),
            "email_address_visibility",
            Realm.EMAIL_ADDRESS_VISIBILITY_NOBODY,
            acting_user=None,
        )

        customer = Customer.objects.create(realm=get_realm("lear"), stripe_customer_id="cus_123")
        now = datetime(2016, 1, 2, tzinfo=timezone.utc)
        plan = CustomerPlan.objects.create(
            customer=customer,
            billing_cycle_anchor=now,
            billing_schedule=CustomerPlan.ANNUAL,
            tier=CustomerPlan.STANDARD,
            price_per_license=8000,
            next_invoice_date=add_months(now, 12),
        )
        LicenseLedger.objects.create(
            licenses=10,
            licenses_at_next_renewal=10,
            event_time=timezone_now(),
            is_renewal=True,
            plan=plan,
        )

        result = self.client_get("/activity/support")
        self.assert_in_success_response(
            ['<input type="text" name="q" class="input-xxlarge search-query"'], result
        )

        result = self.client_get("/activity/support", {"q": self.example_email("hamlet")})
        check_hamlet_user_query_result(result)
        check_zulip_realm_query_result(result)

        result = self.client_get("/activity/support", {"q": self.example_email("polonius")})
        check_polonius_user_query_result(result)
        check_zulip_realm_query_result(result)

        result = self.client_get("/activity/support", {"q": "lear"})
        check_lear_realm_query_result(result)

        result = self.client_get("/activity/support", {"q": "http://lear.testserver"})
        check_lear_realm_query_result(result)

        with self.settings(REALM_HOSTS={"zulip": "localhost"}):
            result = self.client_get("/activity/support", {"q": "http://localhost"})
            check_zulip_realm_query_result(result)

        result = self.client_get("/activity/support", {"q": "[email protected], lear"})
        check_hamlet_user_query_result(result)
        check_zulip_realm_query_result(result)
        check_lear_realm_query_result(result)

        result = self.client_get("/activity/support", {"q": "King hamlet,lear"})
        check_hamlet_user_query_result(result)
        check_zulip_realm_query_result(result)
        check_lear_realm_query_result(result)

        result = self.client_get("/activity/support", {"q": "Othello, the Moor of Venice"})
        check_othello_user_query_result(result)
        check_zulip_realm_query_result(result)

        result = self.client_get("/activity/support", {"q": "lear, Hamlet <*****@*****.**>"})
        check_hamlet_user_query_result(result)
        check_zulip_realm_query_result(result)
        check_lear_realm_query_result(result)

        with mock.patch(
            "analytics.views.support.timezone_now",
            return_value=timezone_now() - timedelta(minutes=50),
        ):
            self.client_post("/accounts/home/", {"email": self.nonreg_email("test")})
            self.login("iago")
            result = self.client_get("/activity/support", {"q": self.nonreg_email("test")})
            check_preregistration_user_query_result(result, self.nonreg_email("test"))
            check_zulip_realm_query_result(result)

            invite_expires_in_days = 10
            stream_ids = [self.get_stream_id("Denmark")]
            invitee_emails = [self.nonreg_email("test1")]
            self.client_post(
                "/json/invites",
                {
                    "invitee_emails": invitee_emails,
                    "stream_ids": orjson.dumps(stream_ids).decode(),
                    "invite_expires_in_days": invite_expires_in_days,
                    "invite_as": PreregistrationUser.INVITE_AS["MEMBER"],
                },
            )
            result = self.client_get("/activity/support", {"q": self.nonreg_email("test1")})
            check_preregistration_user_query_result(result, self.nonreg_email("test1"), invite=True)
            check_zulip_realm_query_result(result)

            email = self.nonreg_email("alice")
            self.client_post("/new/", {"email": email})
            result = self.client_get("/activity/support", {"q": email})
            check_realm_creation_query_result(result, email)

            do_create_multiuse_invite_link(
                self.example_user("hamlet"),
                invited_as=1,
                invite_expires_in_days=invite_expires_in_days,
            )
            result = self.client_get("/activity/support", {"q": "zulip"})
            check_multiuse_invite_link_query_result(result)
            check_zulip_realm_query_result(result)
            MultiuseInvite.objects.all().delete()

            do_send_realm_reactivation_email(get_realm("zulip"), acting_user=None)
            result = self.client_get("/activity/support", {"q": "zulip"})
            check_realm_reactivation_link_query_result(result)
            check_zulip_realm_query_result(result)
Beispiel #7
0
def support(
    request: HttpRequest,
    realm_id: Optional[int] = REQ(default=None, converter=to_non_negative_int),
    plan_type: Optional[int] = REQ(default=None,
                                   converter=to_non_negative_int),
    discount: Optional[Decimal] = REQ(default=None, converter=to_decimal),
    new_subdomain: Optional[str] = REQ(default=None),
    status: Optional[str] = REQ(
        default=None, str_validator=check_string_in(VALID_STATUS_VALUES)),
    billing_method: Optional[str] = REQ(
        default=None, str_validator=check_string_in(VALID_BILLING_METHODS)),
    sponsorship_pending: Optional[bool] = REQ(default=None,
                                              json_validator=check_bool),
    approve_sponsorship: Optional[bool] = REQ(default=None,
                                              json_validator=check_bool),
    downgrade_method: Optional[str] = REQ(
        default=None, str_validator=check_string_in(VALID_DOWNGRADE_METHODS)),
    scrub_realm: Optional[bool] = REQ(default=None, json_validator=check_bool),
    query: Optional[str] = REQ("q", default=None),
    org_type: Optional[int] = REQ(default=None, converter=to_non_negative_int),
) -> HttpResponse:
    context: Dict[str, Any] = {}

    if "success_message" in request.session:
        context["success_message"] = request.session["success_message"]
        del request.session["success_message"]

    if settings.BILLING_ENABLED and request.method == "POST":
        # We check that request.POST only has two keys in it: The
        # realm_id and a field to change.
        keys = set(request.POST.keys())
        if "csrfmiddlewaretoken" in keys:
            keys.remove("csrfmiddlewaretoken")
        if len(keys) != 2:
            raise JsonableError(_("Invalid parameters"))

        realm = Realm.objects.get(id=realm_id)

        acting_user = request.user
        assert isinstance(acting_user, UserProfile)
        if plan_type is not None:
            current_plan_type = realm.plan_type
            do_change_realm_plan_type(realm,
                                      plan_type,
                                      acting_user=acting_user)
            msg = f"Plan type of {realm.string_id} changed from {get_plan_name(current_plan_type)} to {get_plan_name(plan_type)} "
            context["success_message"] = msg
        elif org_type is not None:
            current_realm_type = realm.org_type
            do_change_realm_org_type(realm, org_type, acting_user=acting_user)
            msg = f"Org type of {realm.string_id} changed from {get_org_type_display_name(current_realm_type)} to {get_org_type_display_name(org_type)} "
            context["success_message"] = msg
        elif discount is not None:
            current_discount = get_discount_for_realm(realm) or 0
            attach_discount_to_realm(realm, discount, acting_user=acting_user)
            context[
                "success_message"] = f"Discount of {realm.string_id} changed to {discount}% from {current_discount}%."
        elif new_subdomain is not None:
            old_subdomain = realm.string_id
            try:
                check_subdomain_available(new_subdomain)
            except ValidationError as error:
                context["error_message"] = error.message
            else:
                do_change_realm_subdomain(realm,
                                          new_subdomain,
                                          acting_user=acting_user)
                request.session[
                    "success_message"] = f"Subdomain changed from {old_subdomain} to {new_subdomain}"
                return HttpResponseRedirect(
                    reverse("support") + "?" + urlencode({"q": new_subdomain}))
        elif status is not None:
            if status == "active":
                do_send_realm_reactivation_email(realm,
                                                 acting_user=acting_user)
                context[
                    "success_message"] = f"Realm reactivation email sent to admins of {realm.string_id}."
            elif status == "deactivated":
                do_deactivate_realm(realm, acting_user=acting_user)
                context["success_message"] = f"{realm.string_id} deactivated."
        elif billing_method is not None:
            if billing_method == "send_invoice":
                update_billing_method_of_current_plan(
                    realm, charge_automatically=False, acting_user=acting_user)
                context[
                    "success_message"] = f"Billing method of {realm.string_id} updated to pay by invoice."
            elif billing_method == "charge_automatically":
                update_billing_method_of_current_plan(
                    realm, charge_automatically=True, acting_user=acting_user)
                context[
                    "success_message"] = f"Billing method of {realm.string_id} updated to charge automatically."
        elif sponsorship_pending is not None:
            if sponsorship_pending:
                update_sponsorship_status(realm, True, acting_user=acting_user)
                context[
                    "success_message"] = f"{realm.string_id} marked as pending sponsorship."
            else:
                update_sponsorship_status(realm,
                                          False,
                                          acting_user=acting_user)
                context[
                    "success_message"] = f"{realm.string_id} is no longer pending sponsorship."
        elif approve_sponsorship:
            do_approve_sponsorship(realm, acting_user=acting_user)
            context[
                "success_message"] = f"Sponsorship approved for {realm.string_id}"
        elif downgrade_method is not None:
            if downgrade_method == "downgrade_at_billing_cycle_end":
                downgrade_at_the_end_of_billing_cycle(realm)
                context[
                    "success_message"] = f"{realm.string_id} marked for downgrade at the end of billing cycle"
            elif downgrade_method == "downgrade_now_without_additional_licenses":
                downgrade_now_without_creating_additional_invoices(realm)
                context[
                    "success_message"] = f"{realm.string_id} downgraded without creating additional invoices"
            elif downgrade_method == "downgrade_now_void_open_invoices":
                downgrade_now_without_creating_additional_invoices(realm)
                voided_invoices_count = void_all_open_invoices(realm)
                context[
                    "success_message"] = f"{realm.string_id} downgraded and voided {voided_invoices_count} open invoices"
        elif scrub_realm:
            do_scrub_realm(realm, acting_user=acting_user)
            context["success_message"] = f"{realm.string_id} scrubbed."

    if query:
        key_words = get_invitee_emails_set(query)

        users = set(UserProfile.objects.filter(delivery_email__in=key_words))
        realms = set(Realm.objects.filter(string_id__in=key_words))

        for key_word in key_words:
            try:
                URLValidator()(key_word)
                parse_result = urllib.parse.urlparse(key_word)
                hostname = parse_result.hostname
                assert hostname is not None
                if parse_result.port:
                    hostname = f"{hostname}:{parse_result.port}"
                subdomain = get_subdomain_from_hostname(hostname)
                try:
                    realms.add(get_realm(subdomain))
                except Realm.DoesNotExist:
                    pass
            except ValidationError:
                users.update(
                    UserProfile.objects.filter(full_name__iexact=key_word))

        for realm in realms:
            realm.customer = get_customer_by_realm(realm)

            current_plan = get_current_plan_by_realm(realm)
            if current_plan is not None:
                new_plan, last_ledger_entry = make_end_of_cycle_updates_if_needed(
                    current_plan, timezone_now())
                if last_ledger_entry is not None:
                    if new_plan is not None:
                        realm.current_plan = new_plan
                    else:
                        realm.current_plan = current_plan
                    realm.current_plan.licenses = last_ledger_entry.licenses
                    realm.current_plan.licenses_used = get_latest_seat_count(
                        realm)

        # full_names can have , in them
        users.update(UserProfile.objects.filter(full_name__iexact=query))

        context["users"] = users
        context["realms"] = realms

        confirmations: List[Dict[str, Any]] = []

        preregistration_users = PreregistrationUser.objects.filter(
            email__in=key_words)
        confirmations += get_confirmations(
            [
                Confirmation.USER_REGISTRATION, Confirmation.INVITATION,
                Confirmation.REALM_CREATION
            ],
            preregistration_users,
            hostname=request.get_host(),
        )

        multiuse_invites = MultiuseInvite.objects.filter(realm__in=realms)
        confirmations += get_confirmations([Confirmation.MULTIUSE_INVITE],
                                           multiuse_invites)

        confirmations += get_confirmations([Confirmation.REALM_REACTIVATION],
                                           [realm.id for realm in realms])

        context["confirmations"] = confirmations

    def get_realm_owner_emails_as_string(realm: Realm) -> str:
        return ", ".join(realm.get_human_owner_users().order_by(
            "delivery_email").values_list("delivery_email", flat=True))

    def get_realm_admin_emails_as_string(realm: Realm) -> str:
        return ", ".join(
            realm.get_human_admin_users(include_realm_owners=False).order_by(
                "delivery_email").values_list("delivery_email", flat=True))

    context[
        "get_realm_owner_emails_as_string"] = get_realm_owner_emails_as_string
    context[
        "get_realm_admin_emails_as_string"] = get_realm_admin_emails_as_string
    context["get_discount_for_realm"] = get_discount_for_realm
    context["get_org_type_display_name"] = get_org_type_display_name
    context["realm_icon_url"] = realm_icon_url
    context["Confirmation"] = Confirmation
    context["sorted_realm_types"] = sorted(Realm.ORG_TYPES.values(),
                                           key=lambda d: d["display_order"])

    return render(request, "analytics/support.html", context=context)
Beispiel #8
0
    def test_search(self) -> None:
        reset_emails_in_zulip_realm()

        def check_hamlet_user_query_result(result: HttpResponse) -> None:
            self.assert_in_success_response([
                '<span class="label">user</span>\n', '<h3>King Hamlet</h3>',
                '<b>Email</b>: [email protected]', '<b>Is active</b>: True<br>',
                '<b>Admins</b>: [email protected], [email protected]\n',
                'class="copy-button" data-copytext="[email protected], [email protected]"'
            ], result)

        def check_zulip_realm_query_result(result: HttpResponse) -> None:
            zulip_realm = get_realm("zulip")
            self.assert_in_success_response([
                '<input type="hidden" name="realm_id" value="%s"' %
                (zulip_realm.id, ), 'Zulip Dev</h3>',
                '<option value="1" selected>Self Hosted</option>',
                '<option value="2" >Limited</option>',
                'input type="number" name="discount" value="None"',
                '<option value="active" selected>Active</option>',
                '<option value="deactivated" >Deactivated</option>',
                'scrub-realm-button">', 'data-string-id="zulip"'
            ], result)

        def check_lear_realm_query_result(result: HttpResponse) -> None:
            lear_realm = get_realm("lear")
            self.assert_in_success_response([
                '<input type="hidden" name="realm_id" value="%s"' %
                (lear_realm.id, ), 'Lear &amp; Co.</h3>',
                '<option value="1" selected>Self Hosted</option>',
                '<option value="2" >Limited</option>',
                'input type="number" name="discount" value="None"',
                '<option value="active" selected>Active</option>',
                '<option value="deactivated" >Deactivated</option>',
                'scrub-realm-button">', 'data-string-id="lear"'
            ], result)

        def check_preregistration_user_query_result(
                result: HttpResponse,
                email: str,
                invite: Optional[bool] = False) -> None:
            self.assert_in_success_response([
                '<span class="label">preregistration user</span>\n',
                '<b>Email</b>: {}'.format(email),
            ], result)
            if invite:
                self.assert_in_success_response(
                    ['<span class="label">invite</span>'], result)
                self.assert_in_success_response([
                    '<b>Expires in</b>: 1\xa0week, 3',
                    '<b>Status</b>: Link has never been clicked'
                ], result)
                self.assert_in_success_response([], result)
            else:
                self.assert_not_in_success_response(
                    ['<span class="label">invite</span>'], result)
                self.assert_in_success_response([
                    '<b>Expires in</b>: 1\xa0day',
                    '<b>Status</b>: Link has never been clicked'
                ], result)

        def check_realm_creation_query_result(result: HttpResponse,
                                              email: str) -> None:
            self.assert_in_success_response([
                '<span class="label">preregistration user</span>\n',
                '<span class="label">realm creation</span>\n',
                '<b>Link</b>: http://zulip.testserver/accounts/do_confirm/',
                '<b>Expires in</b>: 1\xa0day<br>\n'
            ], result)

        def check_multiuse_invite_link_query_result(
                result: HttpResponse) -> None:
            self.assert_in_success_response([
                '<span class="label">multiuse invite</span>\n',
                '<b>Link</b>: http://zulip.testserver/join/',
                '<b>Expires in</b>: 1\xa0week, 3'
            ], result)

        def check_realm_reactivation_link_query_result(
                result: HttpResponse) -> None:
            self.assert_in_success_response([
                '<span class="label">realm reactivation</span>\n',
                '<b>Link</b>: http://zulip.testserver/reactivate/',
                '<b>Expires in</b>: 1\xa0day'
            ], result)

        self.login('cordelia')

        result = self.client_get("/activity/support")
        self.assertEqual(result.status_code, 302)
        self.assertEqual(result["Location"], "/login/")

        self.login('iago')

        result = self.client_get("/activity/support")
        self.assert_in_success_response(
            ['<input type="text" name="q" class="input-xxlarge search-query"'],
            result)

        result = self.client_get("/activity/support",
                                 {"q": "*****@*****.**"})
        check_hamlet_user_query_result(result)
        check_zulip_realm_query_result(result)

        result = self.client_get("/activity/support", {"q": "lear"})
        check_lear_realm_query_result(result)

        result = self.client_get("/activity/support",
                                 {"q": "http://lear.testserver"})
        check_lear_realm_query_result(result)

        with self.settings(REALM_HOSTS={'zulip': 'localhost'}):
            result = self.client_get("/activity/support",
                                     {"q": "http://localhost"})
            check_zulip_realm_query_result(result)

        result = self.client_get("/activity/support",
                                 {"q": "[email protected], lear"})
        check_hamlet_user_query_result(result)
        check_zulip_realm_query_result(result)
        check_lear_realm_query_result(result)

        result = self.client_get("/activity/support",
                                 {"q": "lear, Hamlet <*****@*****.**>"})
        check_hamlet_user_query_result(result)
        check_zulip_realm_query_result(result)
        check_lear_realm_query_result(result)

        self.client_post('/accounts/home/',
                         {'email': self.nonreg_email("test")})
        self.login('iago')
        result = self.client_get("/activity/support",
                                 {"q": self.nonreg_email("test")})
        check_preregistration_user_query_result(result,
                                                self.nonreg_email("test"))
        check_zulip_realm_query_result(result)

        stream_ids = [self.get_stream_id("Denmark")]
        invitee_emails = [self.nonreg_email("test1")]
        self.client_post(
            "/json/invites", {
                "invitee_emails": invitee_emails,
                "stream_ids": ujson.dumps(stream_ids),
                "invite_as": 1
            })
        result = self.client_get("/activity/support",
                                 {"q": self.nonreg_email("test1")})
        check_preregistration_user_query_result(result,
                                                self.nonreg_email("test1"),
                                                invite=True)
        check_zulip_realm_query_result(result)

        email = self.nonreg_email('alice')
        self.client_post('/new/', {'email': email})
        result = self.client_get("/activity/support", {"q": email})
        check_realm_creation_query_result(result, email)

        do_create_multiuse_invite_link(self.example_user("hamlet"),
                                       invited_as=1)
        result = self.client_get("/activity/support", {"q": "zulip"})
        check_multiuse_invite_link_query_result(result)
        check_zulip_realm_query_result(result)
        MultiuseInvite.objects.all().delete()

        do_send_realm_reactivation_email(get_realm("zulip"))
        result = self.client_get("/activity/support", {"q": "zulip"})
        check_realm_reactivation_link_query_result(result)
        check_zulip_realm_query_result(result)