Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
auth: Add login buttons for web public access.
Aman Agrawal3b29c61409d5
diff --git a/static/styles/portico/portico_signin.css b/static/styles/portico/portico_signin.cssindex c063c11329f..e9eeec7cad7 100644--- a/static/styles/portico/portico_signin.css+++ b/static/styles/portico/portico_signin.css@@ -687,6 +687,13 @@ html {max-width: 500px;}+.anonymous_access_form {+ button {+ /* Avoid excessive space at top of login form */+ margin-top: 0;+ }+}+button.login-social-button {width: 328px;height: auto;diff --git a/templates/zerver/development/dev_login.html b/templates/zerver/development/dev_login.htmlindex 6c4567097ee..cdef2b6d61a 100644--- a/templates/zerver/development/dev_login.html+++ b/templates/zerver/development/dev_login.html@@ -19,6 +19,11 @@ page can be easily identified in it's respective JavaScript file --><div class="control-group"><div class="controls"><div class="group">+ {% if realm_web_public_access_enabled %}+ <h2>{{_('Anonymous user') }}</h2>+ <p><input type="submit" formaction="{{ current_realm.uri }}{{ url('login-local') }}"+ name="prefers_web_public_view" class="btn-direct btn-admin" value="Anonymous login" /></p>+ {% endif %}<h2>{{_('Owners') }}</h2>{% if direct_owners %}{% for direct_owner in direct_owners %}diff --git a/templates/zerver/login.html b/templates/zerver/login.htmlindex 01ce53104e6..4a3840fab0f 100644--- a/templates/zerver/login.html+++ b/templates/zerver/login.html@@ -30,6 +30,22 @@ page can be easily identified in it's respective JavaScript file. -->{% endif %}<div class="right-side">+ {% if realm_web_public_access_enabled %}+ <div class="login-social">+ <form class="anonymous_access_form form-inline" action="/" method="post">+ {{ csrf_input }}+ <input type="hidden" name="prefers_web_public_view" value="true" />+ <input type="hidden" name="next" value="{{ next }}" />+ <button class="full-width">+ {{ _('Access without an account') }}+ </button>+ </form>+ </div>+ {% if no_auth_enabled %}+ {% else %}+ <div class="or"><span>{{ _('OR') }}</span></div>+ {% endif %}+ {% endif %}{% if no_auth_enabled %}<div class="alert"><p>No authentication backends are enabled on thisdiff --git a/zerver/context_processors.py b/zerver/context_processors.pyindex caac674f390..d4a8596590d 100644--- a/zerver/context_processors.py+++ b/zerver/context_processors.py@@ -188,9 +188,13 @@ def login_context(request: HttpRequest) -> Dict[str, Any]:if realm is None:realm_description = Nonerealm_invite_required = False+ realm_web_public_access_enabled = Falseelse:realm_description = get_realm_rendered_description(realm)realm_invite_required = realm.invite_required+ # We offer web public access only if the realm has actual web+ # public streams configured, in addition to having it enabled.+ realm_web_public_access_enabled = realm.has_web_public_streams()context: Dict[str, Any] = {"realm_invite_required": realm_invite_required,@@ -198,6 +202,7 @@ def login_context(request: HttpRequest) -> Dict[str, Any]:"require_email_format_usernames": require_email_format_usernames(realm),"password_auth_enabled": password_auth_enabled(realm),"two_factor_authentication_enabled": settings.TWO_FACTOR_AUTHENTICATION_ENABLED,+ "realm_web_public_access_enabled": realm_web_public_access_enabled,}if realm is not None and realm.description:diff --git a/zerver/decorator.py b/zerver/decorator.pyindex 8bc61381e48..c84b7af5c25 100644--- a/zerver/decorator.py+++ b/zerver/decorator.py@@ -389,9 +389,7 @@ def zulip_redirect_to_login():path = request.get_full_path()- # TODO: Restore testing for this case; it was removed when- # we enabled web-public stream testing on /.- if path == "/": # nocoverage+ if path == "/":# Don't add ?next=/, to keep our URLs cleanreturn HttpResponseRedirect(resolved_login_url)return redirect_to_login(path, resolved_login_url, redirect_field_name)diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.pyindex 332cc78786a..ae485282c53 100644--- a/zerver/lib/test_classes.py+++ b/zerver/lib/test_classes.py@@ -524,15 +524,6 @@ Output:# not as a spectator.self.assertEqual(page_params["is_spectator"], False)- def check_rendered_spectator(self, result: HttpResponse) -> None:- """Verifies that a visit of / was a 200 that rendered page_params- for a (logged-out) spectator."""- self.assertEqual(result.status_code, 200)- page_params = self._get_page_params(result)- # It is important to check `is_spectator` to verify- # that we treated this request to render for a `spectator`- self.assertEqual(page_params["is_spectator"], True)-def login_with_return(self, email: str, password: Optional[str] = None, **kwargs: Any) -> HttpResponse:diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.pyindex 481650805d6..09652192633 100644--- a/zerver/tests/test_auth_backends.py+++ b/zerver/tests/test_auth_backends.py@@ -4711,6 +4711,12 @@ class TestDevAuthBackend(ZulipTestCase):self.assertEqual(result.status_code, 302)self.assert_logged_in_user_id(user_profile.id)+ def test_spectator(self) -> None:+ data = {"prefers_web_public_view": "Anonymous login"}+ result = self.client_post("/accounts/login/local/", data)+ self.assertEqual(result.status_code, 302)+ self.assertEqual(result.url, "http://zulip.testserver/")+def test_login_success_with_2fa(self) -> None:user_profile = self.example_user("hamlet")self.create_default_device(user_profile)diff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.pyindex 3896dba8e31..8518d666317 100644--- a/zerver/tests/test_home.py+++ b/zerver/tests/test_home.py@@ -306,6 +306,18 @@ class HomeTest(ZulipTestCase):self.assertEqual(set(actual_keys), set(expected_keys))def test_logged_out_home(self) -> None:+ # Redirect to login on first request.+ result = self.client_get("/")+ self.assertEqual(result.status_code, 302)+ self.assertEqual(result.url, "/login/")++ # Tell server that user wants to login anonymously+ # Redirects to load webapp.+ result = self.client_post("/", {"prefers_web_public_view": "true"})+ self.assertEqual(result.status_code, 302)+ self.assertEqual(result.url, "http://zulip.testserver")++ # Always load the web app from then on directlyresult = self.client_get("/")self.assertEqual(result.status_code, 200)diff --git a/zerver/tests/test_sessions.py b/zerver/tests/test_sessions.pyindex 8ed57373dc7..95497630f2c 100644--- a/zerver/tests/test_sessions.py+++ b/zerver/tests/test_sessions.py@@ -28,7 +28,8 @@ class TestSessions(ZulipTestCase):action()if expected_result:result = self.client_get("/", subdomain=realm.subdomain)- self.check_rendered_spectator(result)+ self.assertEqual(302, result.status_code)+ self.assertEqual("/login/", result.url)else:self.assertIn("_auth_user_id", self.client.session)@@ -39,7 +40,8 @@ class TestSessions(ZulipTestCase):for session in user_sessions(user_profile):delete_session(session)result = self.client_get("/")- self.check_rendered_spectator(result)+ self.assertEqual(result.status_code, 302)+ self.assertEqual(result.url, "/login/")def test_delete_user_sessions(self) -> None:user_profile = self.example_user("hamlet")@@ -87,7 +89,8 @@ class TestSessions(ZulipTestCase):self.client_post("/accounts/logout/")delete_all_deactivated_user_sessions()result = self.client_get("/")- self.check_rendered_spectator(result)+ self.assertEqual(result.status_code, 302)+ self.assertEqual(result.url, "/login/")# Test nothing happens to an active user's sessionself.login("othello")@@ -107,7 +110,8 @@ class TestSessions(ZulipTestCase):[f"INFO:root:Deactivating session for deactivated user {user_profile_3.id}"],)result = self.client_get("/")- self.check_rendered_spectator(result)+ self.assertEqual(result.status_code, 302)+ self.assertEqual(result.url, "/login/")class TestExpirableSessionVars(ZulipTestCase):diff --git a/zerver/tests/test_urls.py b/zerver/tests/test_urls.pyindex b1130f4f199..ceb8bda02e5 100644--- a/zerver/tests/test_urls.py+++ b/zerver/tests/test_urls.py@@ -43,6 +43,9 @@ class PublicURLTest(ZulipTestCase):"/en/accounts/login/","/ru/accounts/login/","/help/",+ ],+ 302: [+ # These 302 because they redirect to the spectator experience."/","/en/","/ru/",diff --git a/zerver/views/development/dev_login.py b/zerver/views/development/dev_login.pyindex 7eea4975c38..5499263a8b2 100644--- a/zerver/views/development/dev_login.py+++ b/zerver/views/development/dev_login.py@@ -74,9 +74,16 @@ def dev_direct_login(# This check is probably not required, since authenticate would fail without# an enabled DevAuthBackend.return config_error(request, "dev")- email = request.POST["direct_email"]+subdomain = get_subdomain(request)realm = get_realm(subdomain)++ if request.POST.get("prefers_web_public_view") == "Anonymous login":+ request.session["prefers_web_public_view"] = True+ redirect_to = get_safe_redirect_to(next, realm.uri)+ return HttpResponseRedirect(redirect_to)++ email = request.POST["direct_email"]user_profile = authenticate(dev_auth_username=email, realm=realm)if user_profile is None:return config_error(request, "dev")diff --git a/zerver/views/home.py b/zerver/views/home.pyindex bfb72885999..9a9d4dcb4eb 100644--- a/zerver/views/home.py+++ b/zerver/views/home.py@@ -8,7 +8,7 @@ from django.shortcuts import redirect, renderfrom django.utils.cache import patch_cache_controlfrom zerver.context_processors import get_valid_realm_from_request-from zerver.decorator import web_public_view, zulip_login_required+from zerver.decorator import web_public_view, zulip_login_required, zulip_redirect_to_loginfrom zerver.forms import ToSFormfrom zerver.lib.actions import do_change_tos_version, realm_user_countfrom zerver.lib.compatibility import is_outdated_desktop_app, is_unsupported_browser@@ -18,6 +18,7 @@ from zerver.lib.streams import access_stream_by_namefrom zerver.lib.subdomains import get_subdomainfrom zerver.lib.utils import statsdfrom zerver.models import PreregistrationUser, Realm, Stream, UserProfile+from zerver.views.auth import get_safe_redirect_tofrom zerver.views.portico import hello_view@@ -148,10 +149,34 @@ def home_real(request: HttpRequest) -> HttpResponse:user_profile = request.userrealm = user_profile.realmelse:- # user_profile=None corresponds to the logged-out "web_public" visitor case.- user_profile = Nonerealm = get_valid_realm_from_request(request)+ # TODO: Ideally, we'd open Zulip directly as a spectator if+ # the URL had clicked a link to content on a web-public+ # stream. We could maybe do this by parsing `next`, but it's+ # not super convenient with Zulip's hash-based URL scheme.++ # The "Access without an account" button on the login page+ # submits a POST to this page with this hidden field set.+ if request.POST.get("prefers_web_public_view") == "true":+ request.session["prefers_web_public_view"] = True+ # We serve a redirect here, rather than serving a page, to+ # avoid browser "Confirm form resubmission" prompts on reload.+ redirect_to = get_safe_redirect_to(request.POST.get("next"), realm.uri)+ return redirect(redirect_to)++ prefers_web_public_view = request.session.get("prefers_web_public_view")+ if not prefers_web_public_view:+ # For users who haven't opted into the spectator+ # experience, we redirect to the login page.+ return zulip_redirect_to_login(request, settings.HOME_NOT_LOGGED_IN)++ # For users who have selected public access, we load the+ # spectator experience. We fall through to the shared code+ # for loading the application, with user_profile=None encoding+ # that we're a spectator, not a logged-in user.+ user_profile = None+update_last_reminder(user_profile)statsd.incr("views.home")