2017-12-20 07:57:26 +01:00
|
|
|
from django.forms import Form
|
2016-10-12 04:50:38 +02:00
|
|
|
from django.conf import settings
|
2019-02-02 23:53:22 +01:00
|
|
|
from django.contrib.auth import authenticate
|
2020-02-02 13:12:38 +01:00
|
|
|
from django.contrib.auth.views import LoginView as DjangoLoginView, \
|
2016-10-12 04:50:38 +02:00
|
|
|
logout_then_login as django_logout_then_login
|
2020-02-02 14:44:13 +01:00
|
|
|
from django.contrib.auth.views import PasswordResetView as DjangoPasswordResetView
|
2018-01-30 06:05:25 +01:00
|
|
|
from django.urls import reverse
|
2019-02-02 23:53:22 +01:00
|
|
|
from zerver.decorator import require_post, \
|
2017-11-03 22:26:31 +01:00
|
|
|
process_client, do_login, log_view_func
|
2019-09-29 06:32:56 +02:00
|
|
|
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect, \
|
|
|
|
HttpResponseServerError
|
2018-05-21 06:40:18 +02:00
|
|
|
from django.template.response import SimpleTemplateResponse
|
2017-03-16 14:10:39 +01:00
|
|
|
from django.shortcuts import redirect, render
|
2016-10-12 04:50:38 +02:00
|
|
|
from django.views.decorators.csrf import csrf_exempt
|
2019-08-12 05:44:35 +02:00
|
|
|
from django.views.decorators.http import require_safe
|
2016-10-12 04:50:38 +02:00
|
|
|
from django.utils.translation import ugettext as _
|
2018-03-12 12:25:50 +01:00
|
|
|
from django.utils.http import is_safe_url
|
2017-11-05 05:30:31 +01:00
|
|
|
import urllib
|
2019-05-05 00:40:30 +02:00
|
|
|
from typing import Any, Dict, List, Optional, Mapping
|
2016-10-12 04:50:38 +02:00
|
|
|
|
2017-07-08 04:38:13 +02:00
|
|
|
from confirmation.models import Confirmation, create_confirmation_link
|
2019-03-20 13:13:44 +01:00
|
|
|
from zerver.context_processors import zulip_default_context, get_realm_from_request, \
|
|
|
|
login_context
|
2016-12-20 10:41:46 +01:00
|
|
|
from zerver.forms import HomepageForm, OurAuthenticationForm, \
|
2019-04-12 06:24:58 +02:00
|
|
|
WRONG_SUBDOMAIN_ERROR, DEACTIVATED_ACCOUNT_ERROR, ZulipPasswordResetForm, \
|
|
|
|
AuthenticationTokenForm
|
2020-02-01 17:45:22 +01:00
|
|
|
from zerver.lib.mobile_auth_otp import otp_encrypt_api_key
|
2018-02-12 23:34:59 +01:00
|
|
|
from zerver.lib.push_notifications import push_notifications_enabled
|
2020-01-23 12:21:55 +01:00
|
|
|
from zerver.lib.redis_utils import get_redis_client, get_dict_from_redis, put_dict_in_redis
|
2016-10-12 04:50:38 +02:00
|
|
|
from zerver.lib.request import REQ, has_request_variables, JsonableError
|
|
|
|
from zerver.lib.response import json_success, json_error
|
2020-02-06 18:27:10 +01:00
|
|
|
from zerver.lib.sessions import set_expirable_session_var
|
2017-10-19 07:21:57 +02:00
|
|
|
from zerver.lib.subdomains import get_subdomain, is_subdomain_root_or_alias
|
2018-12-06 02:49:34 +01:00
|
|
|
from zerver.lib.user_agent import parse_user_agent
|
2018-08-01 10:53:40 +02:00
|
|
|
from zerver.lib.users import get_api_key
|
2020-01-23 12:21:55 +01:00
|
|
|
from zerver.lib.utils import has_api_key_format
|
2017-04-07 08:21:29 +02:00
|
|
|
from zerver.lib.validator import validate_login_email
|
2017-08-15 00:13:58 +02:00
|
|
|
from zerver.models import PreregistrationUser, UserProfile, remote_user_to_email, Realm, \
|
|
|
|
get_realm
|
2017-06-15 07:15:57 +02:00
|
|
|
from zerver.signals import email_on_new_login
|
2017-04-27 23:34:44 +02:00
|
|
|
from zproject.backends import password_auth_enabled, dev_auth_enabled, \
|
2018-12-19 01:13:59 +01:00
|
|
|
ldap_auth_enabled, ZulipLDAPConfigurationError, ZulipLDAPAuthBackend, \
|
2019-10-26 01:51:48 +02:00
|
|
|
AUTH_BACKEND_NAME_MAP, auth_enabled_helper, saml_auth_enabled, SAMLAuthBackend, \
|
2020-02-01 17:45:22 +01:00
|
|
|
redirect_to_config_error, ZulipRemoteUserBackend, validate_otp_params
|
2017-02-27 08:30:26 +01:00
|
|
|
from version import ZULIP_VERSION
|
2016-10-12 04:50:38 +02:00
|
|
|
|
|
|
|
import jwt
|
|
|
|
import logging
|
|
|
|
|
2019-09-29 06:32:56 +02:00
|
|
|
from social_django.utils import load_backend, load_strategy
|
2020-01-27 12:05:32 +01:00
|
|
|
from social_django.views import auth as social_django_auth
|
2019-09-29 06:32:56 +02:00
|
|
|
|
2017-12-20 07:57:26 +01:00
|
|
|
from two_factor.forms import BackupTokenForm
|
|
|
|
from two_factor.views import LoginView as BaseTwoFactorLoginView
|
|
|
|
|
|
|
|
ExtraContext = Optional[Dict[str, Any]]
|
|
|
|
|
2020-01-23 12:21:55 +01:00
|
|
|
redis_client = get_redis_client()
|
|
|
|
|
2018-04-24 03:47:28 +02:00
|
|
|
def get_safe_redirect_to(url: str, redirect_host: str) -> str:
|
2020-02-04 14:42:03 +01:00
|
|
|
is_url_safe = is_safe_url(url=url, allowed_hosts=set(redirect_host))
|
2018-03-12 12:25:50 +01:00
|
|
|
if is_url_safe:
|
|
|
|
return urllib.parse.urljoin(redirect_host, url)
|
|
|
|
else:
|
|
|
|
return redirect_host
|
|
|
|
|
2018-04-24 03:47:28 +02:00
|
|
|
def create_preregistration_user(email: str, request: HttpRequest, realm_creation: bool=False,
|
2019-11-01 00:00:36 +01:00
|
|
|
password_required: bool=True, full_name: Optional[str]=None,
|
|
|
|
full_name_validated: bool=False) -> HttpResponse:
|
2017-11-08 22:02:59 +01:00
|
|
|
realm = None
|
|
|
|
if not realm_creation:
|
2019-05-04 04:47:44 +02:00
|
|
|
try:
|
|
|
|
realm = get_realm(get_subdomain(request))
|
|
|
|
except Realm.DoesNotExist:
|
|
|
|
pass
|
2019-11-01 00:00:36 +01:00
|
|
|
return PreregistrationUser.objects.create(
|
|
|
|
email=email,
|
|
|
|
realm_creation=realm_creation,
|
|
|
|
password_required=password_required,
|
|
|
|
realm=realm,
|
|
|
|
full_name=full_name,
|
|
|
|
full_name_validated=full_name_validated
|
|
|
|
)
|
2017-10-27 00:27:59 +02:00
|
|
|
|
2018-04-24 03:47:28 +02:00
|
|
|
def maybe_send_to_registration(request: HttpRequest, email: str, full_name: str='',
|
2020-02-06 18:27:10 +01:00
|
|
|
mobile_flow_otp: Optional[str]=None,
|
|
|
|
desktop_flow_otp: Optional[str]=None,
|
2019-02-08 17:09:25 +01:00
|
|
|
is_signup: bool=False, password_required: bool=True,
|
2019-11-01 00:00:36 +01:00
|
|
|
multiuse_object_key: str='',
|
|
|
|
full_name_validated: bool=False) -> HttpResponse:
|
2019-03-10 02:43:29 +01:00
|
|
|
"""Given a successful authentication for an email address (i.e. we've
|
|
|
|
confirmed the user controls the email address) that does not
|
|
|
|
currently have a Zulip account in the target realm, send them to
|
|
|
|
the registration flow or the "continue to registration" flow,
|
|
|
|
depending on is_signup, whether the email address can join the
|
|
|
|
organization (checked in HomepageForm), and similar details.
|
|
|
|
"""
|
2020-02-06 18:27:10 +01:00
|
|
|
|
|
|
|
# In the desktop and mobile registration flows, the sign up
|
|
|
|
# happens in the browser so the user can use their
|
|
|
|
# already-logged-in social accounts. Then at the end, with the
|
|
|
|
# user account created, we pass the appropriate data to the app
|
|
|
|
# via e.g. a `zulip://` redirect. We store the OTP keys for the
|
|
|
|
# mobile/desktop flow in the session with 1-hour expiry, because
|
|
|
|
# we want this configuration of having a successful authentication
|
|
|
|
# result in being logged into the app to persist if the user makes
|
|
|
|
# mistakes while trying to authenticate (E.g. clicks the wrong
|
|
|
|
# Google account, hits back, etc.) during a given browser session,
|
|
|
|
# rather than just logging into the webapp in the target browser.
|
|
|
|
#
|
|
|
|
# We can't use our usual pre-account-creation state storage
|
|
|
|
# approach of putting something in PreregistrationUser, because
|
|
|
|
# that would apply to future registration attempts on other
|
|
|
|
# devices, e.g. just creating an account on the web on their laptop.
|
|
|
|
assert not (mobile_flow_otp and desktop_flow_otp)
|
|
|
|
if mobile_flow_otp:
|
|
|
|
set_expirable_session_var(request.session, 'registration_mobile_flow_otp', mobile_flow_otp,
|
|
|
|
expiry_seconds=3600)
|
|
|
|
elif desktop_flow_otp:
|
|
|
|
set_expirable_session_var(request.session, 'registration_desktop_flow_otp', desktop_flow_otp,
|
|
|
|
expiry_seconds=3600)
|
|
|
|
|
2019-02-08 17:09:25 +01:00
|
|
|
if multiuse_object_key:
|
2017-09-27 03:34:58 +02:00
|
|
|
from_multiuse_invite = True
|
|
|
|
multiuse_obj = Confirmation.objects.get(confirmation_key=multiuse_object_key).content_object
|
|
|
|
realm = multiuse_obj.realm
|
2019-02-06 22:57:14 +01:00
|
|
|
invited_as = multiuse_obj.invited_as
|
2019-05-04 04:47:44 +02:00
|
|
|
else:
|
|
|
|
from_multiuse_invite = False
|
|
|
|
multiuse_obj = None
|
|
|
|
try:
|
|
|
|
realm = get_realm(get_subdomain(request))
|
|
|
|
except Realm.DoesNotExist:
|
|
|
|
realm = None
|
|
|
|
invited_as = PreregistrationUser.INVITE_AS['MEMBER']
|
2017-09-27 03:34:58 +02:00
|
|
|
|
|
|
|
form = HomepageForm({'email': email}, realm=realm, from_multiuse_invite=from_multiuse_invite)
|
2016-10-12 04:50:38 +02:00
|
|
|
if form.is_valid():
|
2019-03-10 02:43:29 +01:00
|
|
|
# If the email address is allowed to sign up for an account in
|
|
|
|
# this organization, construct a PreregistrationUser and
|
|
|
|
# Confirmation objects, and then send the user to account
|
|
|
|
# creation or confirm-continue-registration depending on
|
|
|
|
# is_signup.
|
2019-12-10 18:45:36 +01:00
|
|
|
try:
|
|
|
|
prereg_user = PreregistrationUser.objects.filter(
|
|
|
|
email__iexact=email, realm=realm).latest("invited_at")
|
|
|
|
|
|
|
|
# password_required and full_name data passed here as argument should take precedence
|
|
|
|
# over the defaults with which the existing PreregistrationUser that we've just fetched
|
|
|
|
# was created.
|
|
|
|
prereg_user.password_required = password_required
|
|
|
|
update_fields = ["password_required"]
|
|
|
|
if full_name:
|
|
|
|
prereg_user.full_name = full_name
|
|
|
|
prereg_user.full_name_validated = full_name_validated
|
|
|
|
update_fields.extend(["full_name", "full_name_validated"])
|
|
|
|
prereg_user.save(update_fields=update_fields)
|
|
|
|
except PreregistrationUser.DoesNotExist:
|
2019-11-01 00:00:36 +01:00
|
|
|
prereg_user = create_preregistration_user(
|
|
|
|
email, request,
|
|
|
|
password_required=password_required,
|
|
|
|
full_name=full_name,
|
|
|
|
full_name_validated=full_name_validated
|
|
|
|
)
|
2016-10-12 04:50:38 +02:00
|
|
|
|
2020-01-28 02:20:17 +01:00
|
|
|
if multiuse_obj is not None:
|
2017-09-27 03:34:58 +02:00
|
|
|
request.session.modified = True
|
2020-01-28 02:20:17 +01:00
|
|
|
streams_to_subscribe = list(multiuse_obj.streams.all())
|
|
|
|
prereg_user.streams.set(streams_to_subscribe)
|
2019-02-06 22:57:14 +01:00
|
|
|
prereg_user.invited_as = invited_as
|
|
|
|
prereg_user.save()
|
2017-09-27 03:34:58 +02:00
|
|
|
|
2019-05-13 20:14:41 +02:00
|
|
|
# We want to create a confirmation link to create an account
|
|
|
|
# in the current realm, i.e. one with a hostname of
|
|
|
|
# realm.host. For the Apache REMOTE_USER_SSO auth code path,
|
|
|
|
# this is preferable over realm.get_host() because the latter
|
|
|
|
# contains the port number of the Apache instance and we want
|
|
|
|
# to send the user back to nginx. But if we're in the realm
|
|
|
|
# creation code path, there might not be a realm yet, so we
|
|
|
|
# have to use request.get_host().
|
|
|
|
if realm is not None:
|
|
|
|
host = realm.host
|
|
|
|
else:
|
|
|
|
host = request.get_host()
|
|
|
|
confirmation_link = create_confirmation_link(prereg_user, host,
|
2019-01-29 21:20:31 +01:00
|
|
|
Confirmation.USER_REGISTRATION)
|
2018-04-23 00:12:52 +02:00
|
|
|
if is_signup:
|
|
|
|
return redirect(confirmation_link)
|
|
|
|
|
|
|
|
context = {'email': email,
|
2019-01-29 21:20:31 +01:00
|
|
|
'continue_link': confirmation_link,
|
|
|
|
'full_name': full_name}
|
2018-04-23 00:12:52 +02:00
|
|
|
return render(request,
|
|
|
|
'zerver/confirm_continue_registration.html',
|
|
|
|
context=context)
|
2019-03-10 02:43:29 +01:00
|
|
|
|
|
|
|
# This email address it not allowed to join this organization, so
|
|
|
|
# just send the user back to the registration page.
|
|
|
|
url = reverse('register')
|
2019-03-20 13:13:44 +01:00
|
|
|
context = login_context(request)
|
|
|
|
extra_context = {'form': form, 'current_url': lambda: url,
|
|
|
|
'from_multiuse_invite': from_multiuse_invite,
|
2020-02-06 18:27:10 +01:00
|
|
|
'multiuse_object_key': multiuse_object_key,
|
|
|
|
'mobile_flow_otp': mobile_flow_otp,
|
|
|
|
'desktop_flow_otp': desktop_flow_otp} # type: Mapping[str, Any]
|
2019-03-20 13:13:44 +01:00
|
|
|
context.update(extra_context)
|
|
|
|
return render(request, 'zerver/accounts_home.html', context=context)
|
2016-10-12 04:50:38 +02:00
|
|
|
|
2017-11-27 09:28:57 +01:00
|
|
|
def redirect_to_subdomain_login_url() -> HttpResponseRedirect:
|
2016-10-12 04:50:38 +02:00
|
|
|
login_url = reverse('django.contrib.auth.views.login')
|
|
|
|
redirect_url = login_url + '?subdomain=1'
|
|
|
|
return HttpResponseRedirect(redirect_url)
|
|
|
|
|
2020-01-18 13:47:08 +01:00
|
|
|
def register_remote_user(request: HttpRequest, remote_username: str,
|
|
|
|
full_name: str='',
|
2020-02-06 18:27:10 +01:00
|
|
|
mobile_flow_otp: Optional[str]=None,
|
|
|
|
desktop_flow_otp: Optional[str]=None,
|
2020-01-18 13:47:08 +01:00
|
|
|
is_signup: bool=False,
|
|
|
|
multiuse_object_key: str='',
|
|
|
|
full_name_validated: bool=False) -> HttpResponse:
|
|
|
|
email = remote_user_to_email(remote_username)
|
|
|
|
# We have verified the user controls an email address, but
|
|
|
|
# there's no associated Zulip user account. Consider sending
|
|
|
|
# the request to registration.
|
|
|
|
return maybe_send_to_registration(request, email, full_name, password_required=False,
|
2020-02-06 18:27:10 +01:00
|
|
|
mobile_flow_otp=mobile_flow_otp,
|
|
|
|
desktop_flow_otp=desktop_flow_otp,
|
2020-01-18 13:47:08 +01:00
|
|
|
is_signup=is_signup, multiuse_object_key=multiuse_object_key,
|
|
|
|
full_name_validated=full_name_validated)
|
|
|
|
|
2019-03-30 03:54:11 +01:00
|
|
|
def login_or_register_remote_user(request: HttpRequest, remote_username: str,
|
2018-04-24 03:47:28 +02:00
|
|
|
user_profile: Optional[UserProfile], full_name: str='',
|
2019-05-05 00:40:30 +02:00
|
|
|
mobile_flow_otp: Optional[str]=None,
|
2020-01-23 14:22:28 +01:00
|
|
|
desktop_flow_otp: Optional[str]=None,
|
|
|
|
realm: Optional[Realm]=None,
|
2019-02-08 17:09:25 +01:00
|
|
|
is_signup: bool=False, redirect_to: str='',
|
2019-11-01 00:00:36 +01:00
|
|
|
multiuse_object_key: str='',
|
|
|
|
full_name_validated: bool=False) -> HttpResponse:
|
2019-03-10 02:43:29 +01:00
|
|
|
"""Given a successful authentication showing the user controls given
|
|
|
|
email address (remote_username) and potentially a UserProfile
|
|
|
|
object (if the user already has a Zulip account), redirect the
|
|
|
|
browser to the appropriate place:
|
|
|
|
|
|
|
|
* The logged-in app if the user already has a Zulip account and is
|
|
|
|
trying to login, potentially to an initial narrow or page that had been
|
|
|
|
saved in the `redirect_to` parameter.
|
|
|
|
* The registration form if is_signup was set (i.e. the user is
|
|
|
|
trying to create a Zulip account)
|
|
|
|
* A special `confirm_continue_registration.html` "do you want to
|
|
|
|
register or try another account" if the user doesn't have a
|
|
|
|
Zulip account but is_signup is False (i.e. the user tried to login
|
|
|
|
and then did social authentication selecting an email address that does
|
|
|
|
not have a Zulip account in this organization).
|
2020-01-23 14:22:28 +01:00
|
|
|
* A zulip:// URL to send control back to the mobile or desktop apps if they
|
|
|
|
are doing authentication using the mobile_flow_otp or desktop_flow_otp flow.
|
2019-03-10 02:43:29 +01:00
|
|
|
"""
|
2017-05-05 19:19:02 +02:00
|
|
|
if user_profile is None or user_profile.is_mirror_dummy:
|
2020-01-18 13:47:08 +01:00
|
|
|
return register_remote_user(request, remote_username, full_name,
|
2020-02-06 18:27:10 +01:00
|
|
|
is_signup=is_signup,
|
|
|
|
mobile_flow_otp=mobile_flow_otp,
|
|
|
|
desktop_flow_otp=desktop_flow_otp,
|
|
|
|
multiuse_object_key=multiuse_object_key,
|
2020-01-18 13:47:08 +01:00
|
|
|
full_name_validated=full_name_validated)
|
2017-05-05 19:19:02 +02:00
|
|
|
|
2018-04-22 23:58:37 +02:00
|
|
|
# Otherwise, the user has successfully authenticated to an
|
|
|
|
# account, and we need to do the right thing depending whether
|
|
|
|
# or not they're using the mobile OTP flow or want a browser session.
|
2017-05-05 19:19:02 +02:00
|
|
|
if mobile_flow_otp is not None:
|
2020-01-18 14:41:12 +01:00
|
|
|
return finish_mobile_flow(request, user_profile, mobile_flow_otp)
|
2020-01-23 14:22:28 +01:00
|
|
|
elif desktop_flow_otp is not None:
|
|
|
|
assert realm is not None
|
|
|
|
return finish_desktop_flow(request, user_profile, realm, desktop_flow_otp)
|
2017-03-19 20:01:01 +01:00
|
|
|
|
2017-08-25 01:11:30 +02:00
|
|
|
do_login(request, user_profile)
|
2018-03-12 12:54:50 +01:00
|
|
|
|
|
|
|
redirect_to = get_safe_redirect_to(redirect_to, user_profile.realm.uri)
|
|
|
|
return HttpResponseRedirect(redirect_to)
|
2016-10-12 04:50:38 +02:00
|
|
|
|
2020-01-23 14:22:28 +01:00
|
|
|
def finish_desktop_flow(request: HttpRequest, user_profile: UserProfile,
|
|
|
|
realm: Realm, otp: str) -> HttpResponse:
|
|
|
|
"""
|
|
|
|
The desktop otp flow returns to the app (through a zulip:// redirect)
|
|
|
|
a token that allows obtaining (through log_into_subdomain) a logged in session
|
|
|
|
for the user account we authenticated in this flow.
|
|
|
|
The token can only be used once and within LOGIN_KEY_EXPIRATION_SECONDS
|
|
|
|
of being created, as nothing more powerful is needed for the desktop flow
|
|
|
|
and this ensures the key can only be used for completing this authentication attempt.
|
|
|
|
"""
|
|
|
|
data = {'email': user_profile.delivery_email,
|
|
|
|
'subdomain': realm.subdomain}
|
|
|
|
token = store_login_data(data)
|
|
|
|
|
|
|
|
return create_response_for_otp_flow(token, otp, user_profile,
|
|
|
|
encrypted_key_field_name='otp_encrypted_login_key')
|
|
|
|
|
2020-01-18 14:41:12 +01:00
|
|
|
def finish_mobile_flow(request: HttpRequest, user_profile: UserProfile, otp: str) -> HttpResponse:
|
|
|
|
# For the mobile Oauth flow, we send the API key and other
|
|
|
|
# necessary details in a redirect to a zulip:// URI scheme.
|
|
|
|
api_key = get_api_key(user_profile)
|
2020-01-23 14:22:28 +01:00
|
|
|
response = create_response_for_otp_flow(api_key, otp, user_profile,
|
|
|
|
encrypted_key_field_name='otp_encrypted_api_key')
|
2020-01-18 14:41:12 +01:00
|
|
|
|
|
|
|
# Since we are returning an API key instead of going through
|
|
|
|
# the Django login() function (which creates a browser
|
|
|
|
# session, etc.), the "new login" signal handler (which
|
|
|
|
# triggers an email notification new logins) will not run
|
|
|
|
# automatically. So we call it manually here.
|
|
|
|
#
|
|
|
|
# Arguably, sending a fake 'user_logged_in' signal would be a better approach:
|
|
|
|
# user_logged_in.send(sender=user_profile.__class__, request=request, user=user_profile)
|
|
|
|
email_on_new_login(sender=user_profile.__class__, request=request, user=user_profile)
|
|
|
|
|
|
|
|
# Mark this request as having a logged-in user for our server logs.
|
|
|
|
process_client(request, user_profile)
|
|
|
|
request._email = user_profile.delivery_email
|
|
|
|
|
|
|
|
return response
|
|
|
|
|
2020-01-23 14:22:28 +01:00
|
|
|
def create_response_for_otp_flow(key: str, otp: str, user_profile: UserProfile,
|
|
|
|
encrypted_key_field_name: str) -> HttpResponse:
|
2020-01-23 14:29:15 +01:00
|
|
|
params = {
|
2020-01-23 14:22:28 +01:00
|
|
|
encrypted_key_field_name: otp_encrypt_api_key(key, otp),
|
2020-01-23 14:29:15 +01:00
|
|
|
'email': user_profile.delivery_email,
|
|
|
|
'realm': user_profile.realm.uri,
|
|
|
|
}
|
|
|
|
# We can't use HttpResponseRedirect, since it only allows HTTP(S) URLs
|
|
|
|
response = HttpResponse(status=302)
|
|
|
|
response['Location'] = 'zulip://login?' + urllib.parse.urlencode(params)
|
|
|
|
|
|
|
|
return response
|
|
|
|
|
2017-11-03 22:26:31 +01:00
|
|
|
@log_view_func
|
2018-02-06 23:29:57 +01:00
|
|
|
@has_request_variables
|
|
|
|
def remote_user_sso(request: HttpRequest,
|
2020-02-01 17:00:56 +01:00
|
|
|
mobile_flow_otp: Optional[str]=REQ(default=None),
|
|
|
|
desktop_flow_otp: Optional[str]=REQ(default=None)) -> HttpResponse:
|
2019-12-11 22:47:22 +01:00
|
|
|
subdomain = get_subdomain(request)
|
|
|
|
try:
|
|
|
|
realm = get_realm(subdomain) # type: Optional[Realm]
|
|
|
|
except Realm.DoesNotExist:
|
|
|
|
realm = None
|
|
|
|
|
|
|
|
if not auth_enabled_helper([ZulipRemoteUserBackend.auth_backend_name], realm):
|
2019-12-11 23:13:21 +01:00
|
|
|
return redirect_to_config_error("remoteuser/backend_disabled")
|
2019-12-11 22:47:22 +01:00
|
|
|
|
2016-10-12 04:50:38 +02:00
|
|
|
try:
|
|
|
|
remote_user = request.META["REMOTE_USER"]
|
|
|
|
except KeyError:
|
2019-12-11 23:13:21 +01:00
|
|
|
return redirect_to_config_error("remoteuser/remote_user_header_missing")
|
2016-10-12 04:50:38 +02:00
|
|
|
|
2017-04-07 08:21:29 +02:00
|
|
|
# Django invokes authenticate methods by matching arguments, and this
|
|
|
|
# authentication flow will not invoke LDAP authentication because of
|
|
|
|
# this condition of Django so no need to check if LDAP backend is
|
|
|
|
# enabled.
|
|
|
|
validate_login_email(remote_user_to_email(remote_user))
|
|
|
|
|
2020-02-01 17:00:56 +01:00
|
|
|
# Here we support the mobile and desktop flow for REMOTE_USER_BACKEND; we
|
2018-02-06 23:29:57 +01:00
|
|
|
# validate the data format and then pass it through to
|
|
|
|
# login_or_register_remote_user if appropriate.
|
2020-02-01 17:20:11 +01:00
|
|
|
validate_otp_params(mobile_flow_otp, desktop_flow_otp)
|
2018-02-06 23:29:57 +01:00
|
|
|
|
2017-11-17 23:14:08 +01:00
|
|
|
subdomain = get_subdomain(request)
|
2019-12-11 22:47:22 +01:00
|
|
|
if realm is None:
|
2019-05-05 01:04:48 +02:00
|
|
|
user_profile = None
|
|
|
|
else:
|
|
|
|
user_profile = authenticate(remote_user=remote_user, realm=realm)
|
2018-02-24 22:38:48 +01:00
|
|
|
|
|
|
|
redirect_to = request.GET.get('next', '')
|
|
|
|
|
2018-02-06 23:29:57 +01:00
|
|
|
return login_or_register_remote_user(request, remote_user, user_profile,
|
2018-02-24 22:38:48 +01:00
|
|
|
mobile_flow_otp=mobile_flow_otp,
|
2020-02-01 17:00:56 +01:00
|
|
|
desktop_flow_otp=desktop_flow_otp,
|
|
|
|
realm=realm,
|
2018-02-24 22:38:48 +01:00
|
|
|
redirect_to=redirect_to)
|
2016-10-12 04:50:38 +02:00
|
|
|
|
|
|
|
@csrf_exempt
|
2017-11-03 22:26:31 +01:00
|
|
|
@log_view_func
|
2017-11-27 09:28:57 +01:00
|
|
|
def remote_user_jwt(request: HttpRequest) -> HttpResponse:
|
2016-10-24 11:12:45 +02:00
|
|
|
subdomain = get_subdomain(request)
|
|
|
|
try:
|
|
|
|
auth_key = settings.JWT_AUTH_KEYS[subdomain]
|
|
|
|
except KeyError:
|
|
|
|
raise JsonableError(_("Auth key for this subdomain not found."))
|
|
|
|
|
2016-10-12 04:50:38 +02:00
|
|
|
try:
|
|
|
|
json_web_token = request.POST["json_web_token"]
|
2016-10-24 11:12:45 +02:00
|
|
|
options = {'verify_signature': True}
|
|
|
|
payload = jwt.decode(json_web_token, auth_key, options=options)
|
2016-10-12 04:50:38 +02:00
|
|
|
except KeyError:
|
|
|
|
raise JsonableError(_("No JSON web token passed in request"))
|
2016-10-24 11:12:45 +02:00
|
|
|
except jwt.InvalidTokenError:
|
2016-10-12 04:50:38 +02:00
|
|
|
raise JsonableError(_("Bad JSON web token"))
|
|
|
|
|
|
|
|
remote_user = payload.get("user", None)
|
|
|
|
if remote_user is None:
|
|
|
|
raise JsonableError(_("No user specified in JSON web token claims"))
|
2017-10-03 02:35:41 +02:00
|
|
|
email_domain = payload.get('realm', None)
|
|
|
|
if email_domain is None:
|
2018-03-08 02:05:50 +01:00
|
|
|
raise JsonableError(_("No organization specified in JSON web token claims"))
|
2016-10-12 04:50:38 +02:00
|
|
|
|
2017-10-03 02:35:41 +02:00
|
|
|
email = "%s@%s" % (remote_user, email_domain)
|
2016-10-12 04:50:38 +02:00
|
|
|
|
2019-05-04 04:47:44 +02:00
|
|
|
try:
|
|
|
|
realm = get_realm(subdomain)
|
|
|
|
except Realm.DoesNotExist:
|
2017-10-03 02:34:58 +02:00
|
|
|
raise JsonableError(_("Wrong subdomain"))
|
|
|
|
|
2020-01-18 14:24:44 +01:00
|
|
|
user_profile = authenticate_remote_user(realm, email)
|
2016-10-12 04:50:38 +02:00
|
|
|
return login_or_register_remote_user(request, email, user_profile, remote_user)
|
|
|
|
|
2018-07-10 08:07:23 +02:00
|
|
|
def oauth_redirect_to_root(request: HttpRequest, url: str,
|
2019-09-29 06:32:56 +02:00
|
|
|
sso_type: str, is_signup: bool=False,
|
|
|
|
extra_url_params: Dict[str, str]={}) -> HttpResponse:
|
2017-10-27 03:17:12 +02:00
|
|
|
main_site_uri = settings.ROOT_DOMAIN_URI + url
|
2018-07-10 08:07:23 +02:00
|
|
|
if settings.SOCIAL_AUTH_SUBDOMAIN is not None and sso_type == 'social':
|
|
|
|
main_site_uri = (settings.EXTERNAL_URI_SCHEME +
|
|
|
|
settings.SOCIAL_AUTH_SUBDOMAIN +
|
|
|
|
"." +
|
|
|
|
settings.EXTERNAL_HOST) + url
|
|
|
|
|
2017-03-19 20:01:01 +01:00
|
|
|
params = {
|
|
|
|
'subdomain': get_subdomain(request),
|
|
|
|
'is_signup': '1' if is_signup else '0',
|
|
|
|
}
|
|
|
|
|
2019-02-08 17:09:25 +01:00
|
|
|
params['multiuse_object_key'] = request.GET.get('multiuse_object_key', '')
|
|
|
|
|
2017-03-19 20:01:01 +01:00
|
|
|
# mobile_flow_otp is a one-time pad provided by the app that we
|
|
|
|
# can use to encrypt the API key when passing back to the app.
|
|
|
|
mobile_flow_otp = request.GET.get('mobile_flow_otp')
|
2020-02-01 17:20:11 +01:00
|
|
|
desktop_flow_otp = request.GET.get('desktop_flow_otp')
|
|
|
|
|
|
|
|
validate_otp_params(mobile_flow_otp, desktop_flow_otp)
|
2017-03-19 20:01:01 +01:00
|
|
|
if mobile_flow_otp is not None:
|
|
|
|
params['mobile_flow_otp'] = mobile_flow_otp
|
2020-01-23 14:22:28 +01:00
|
|
|
if desktop_flow_otp is not None:
|
|
|
|
params['desktop_flow_otp'] = desktop_flow_otp
|
|
|
|
|
2018-03-12 12:54:50 +01:00
|
|
|
next = request.GET.get('next')
|
|
|
|
if next:
|
|
|
|
params['next'] = next
|
|
|
|
|
2019-09-29 06:32:56 +02:00
|
|
|
params = {**params, **extra_url_params}
|
|
|
|
|
2016-10-14 14:12:16 +02:00
|
|
|
return redirect(main_site_uri + '?' + urllib.parse.urlencode(params))
|
|
|
|
|
2019-10-22 18:23:57 +02:00
|
|
|
def start_social_login(request: HttpRequest, backend: str, extra_arg: Optional[str]=None
|
|
|
|
) -> HttpResponse:
|
2016-12-01 13:10:59 +01:00
|
|
|
backend_url = reverse('social:begin', args=[backend])
|
2019-09-29 06:32:56 +02:00
|
|
|
extra_url_params = {} # type: Dict[str, str]
|
|
|
|
if backend == "saml":
|
2019-10-26 01:51:48 +02:00
|
|
|
result = SAMLAuthBackend.check_config()
|
|
|
|
if result is not None:
|
|
|
|
return result
|
2019-09-29 06:32:56 +02:00
|
|
|
|
|
|
|
# This backend requires the name of the IdP (from the list of configured ones)
|
|
|
|
# to be passed as the parameter.
|
2019-10-22 18:23:57 +02:00
|
|
|
if not extra_arg or extra_arg not in settings.SOCIAL_AUTH_SAML_ENABLED_IDPS:
|
|
|
|
logging.info("Attempted to initiate SAML authentication with wrong idp argument: {}"
|
|
|
|
.format(extra_arg))
|
2019-09-29 06:32:56 +02:00
|
|
|
return redirect_to_config_error("saml")
|
2019-10-22 18:23:57 +02:00
|
|
|
extra_url_params = {'idp': extra_arg}
|
2017-11-05 03:14:28 +01:00
|
|
|
if (backend == "github") and not (settings.SOCIAL_AUTH_GITHUB_KEY and
|
|
|
|
settings.SOCIAL_AUTH_GITHUB_SECRET):
|
2017-08-07 17:38:25 +02:00
|
|
|
return redirect_to_config_error("github")
|
2019-02-02 16:51:26 +01:00
|
|
|
if (backend == "google") and not (settings.SOCIAL_AUTH_GOOGLE_KEY and
|
|
|
|
settings.SOCIAL_AUTH_GOOGLE_SECRET):
|
|
|
|
return redirect_to_config_error("google")
|
2020-01-31 18:19:53 +01:00
|
|
|
if (backend == "gitlab") and not (settings.SOCIAL_AUTH_GITLAB_KEY and
|
|
|
|
settings.SOCIAL_AUTH_GITLAB_SECRET):
|
|
|
|
return redirect_to_config_error("gitlab")
|
2019-09-29 06:32:56 +02:00
|
|
|
# TODO: Add a similar block for AzureAD.
|
2017-08-07 17:38:25 +02:00
|
|
|
|
2019-09-29 06:32:56 +02:00
|
|
|
return oauth_redirect_to_root(request, backend_url, 'social', extra_url_params=extra_url_params)
|
2016-12-01 13:10:59 +01:00
|
|
|
|
2019-10-22 18:23:57 +02:00
|
|
|
def start_social_signup(request: HttpRequest, backend: str, extra_arg: Optional[str]=None
|
|
|
|
) -> HttpResponse:
|
2017-04-18 11:50:44 +02:00
|
|
|
backend_url = reverse('social:begin', args=[backend])
|
2019-09-29 06:32:56 +02:00
|
|
|
extra_url_params = {} # type: Dict[str, str]
|
|
|
|
if backend == "saml":
|
2019-10-26 01:51:48 +02:00
|
|
|
result = SAMLAuthBackend.check_config()
|
|
|
|
if result is not None:
|
|
|
|
return result
|
|
|
|
|
2019-10-22 18:23:57 +02:00
|
|
|
if not extra_arg or extra_arg not in settings.SOCIAL_AUTH_SAML_ENABLED_IDPS:
|
|
|
|
logging.info("Attempted to initiate SAML authentication with wrong idp argument: {}"
|
|
|
|
.format(extra_arg))
|
|
|
|
return redirect_to_config_error("saml")
|
|
|
|
extra_url_params = {'idp': extra_arg}
|
2019-09-29 06:32:56 +02:00
|
|
|
return oauth_redirect_to_root(request, backend_url, 'social', is_signup=True,
|
|
|
|
extra_url_params=extra_url_params)
|
2017-04-18 11:50:44 +02:00
|
|
|
|
2020-01-27 12:05:32 +01:00
|
|
|
def social_auth(request: HttpRequest, backend: str) -> HttpResponse:
|
|
|
|
"""
|
|
|
|
python-social-auth sets certain fields from the request into the session
|
|
|
|
and doesn't clear them if another request is made with a field that was present
|
|
|
|
in the previous request now missing. We use this function to hook into the beginning
|
|
|
|
of the social auth flow to ensure the session is properly cleared out.
|
|
|
|
This function and the corresponding url entry in urls.py should be removed if this issue
|
|
|
|
gets fixed upstream - https://github.com/python-social-auth/social-core/issues/425
|
|
|
|
"""
|
|
|
|
|
|
|
|
for field_name in settings.SOCIAL_AUTH_FIELDS_STORED_IN_SESSION:
|
|
|
|
try:
|
|
|
|
del request.session[field_name]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
return social_django_auth(request, backend)
|
|
|
|
|
2019-07-27 00:49:33 +02:00
|
|
|
def authenticate_remote_user(realm: Realm,
|
|
|
|
email_address: Optional[str]) -> Optional[UserProfile]:
|
2017-04-18 08:34:29 +02:00
|
|
|
if email_address is None:
|
|
|
|
# No need to authenticate if email address is None. We already
|
|
|
|
# know that user_profile would be None as well. In fact, if we
|
|
|
|
# call authenticate in this case, we might get an exception from
|
|
|
|
# ZulipDummyBackend which doesn't accept a None as a username.
|
|
|
|
logging.warning("Email address was None while trying to authenticate "
|
|
|
|
"remote user.")
|
2019-05-05 00:40:30 +02:00
|
|
|
return None
|
2017-04-18 08:34:29 +02:00
|
|
|
|
2016-10-12 04:50:38 +02:00
|
|
|
user_profile = authenticate(username=email_address,
|
2017-10-03 02:29:20 +02:00
|
|
|
realm=realm,
|
2019-05-05 00:40:30 +02:00
|
|
|
use_dummy_backend=True)
|
|
|
|
return user_profile
|
2016-10-14 14:12:16 +02:00
|
|
|
|
2017-10-27 02:45:38 +02:00
|
|
|
_subdomain_token_salt = 'zerver.views.auth.log_into_subdomain'
|
2020-01-23 12:21:55 +01:00
|
|
|
LOGIN_KEY_PREFIX = "login_key_"
|
|
|
|
LOGIN_KEY_FORMAT = LOGIN_KEY_PREFIX + "{token}"
|
|
|
|
LOGIN_KEY_EXPIRATION_SECONDS = 15
|
|
|
|
LOGIN_TOKEN_LENGTH = UserProfile.API_KEY_LENGTH
|
2017-10-27 02:45:38 +02:00
|
|
|
|
2017-11-03 22:26:31 +01:00
|
|
|
@log_view_func
|
2018-04-24 03:47:28 +02:00
|
|
|
def log_into_subdomain(request: HttpRequest, token: str) -> HttpResponse:
|
2020-01-23 12:21:55 +01:00
|
|
|
"""Given a valid authentication token (generated by
|
2019-03-10 02:43:29 +01:00
|
|
|
redirect_and_log_into_subdomain called on auth.zulip.example.com),
|
|
|
|
call login_or_register_remote_user, passing all the authentication
|
2020-01-23 12:21:55 +01:00
|
|
|
result data that has been stored in redis, associated with this token.
|
2020-01-23 14:22:28 +01:00
|
|
|
Obligatory fields for the data are 'subdomain' and 'email', because this endpoint
|
|
|
|
needs to know which user and realm to log into. Others are optional and only used
|
|
|
|
if the user account still needs to be made and they're passed as argument to the
|
|
|
|
register_remote_user function.
|
2019-03-10 02:43:29 +01:00
|
|
|
"""
|
2020-01-23 12:21:55 +01:00
|
|
|
if not has_api_key_format(token): # The tokens are intended to have the same format as API keys.
|
|
|
|
logging.warning("log_into_subdomain: Malformed token given: %s" % (token,))
|
2016-10-14 14:12:16 +02:00
|
|
|
return HttpResponse(status=400)
|
2020-01-23 12:21:55 +01:00
|
|
|
|
|
|
|
data = get_login_data(token)
|
|
|
|
if data is None:
|
|
|
|
logging.warning("log_into_subdomain: Invalid token given: %s" % (token,))
|
2016-10-14 14:12:16 +02:00
|
|
|
return HttpResponse(status=400)
|
|
|
|
|
2020-01-20 16:51:24 +01:00
|
|
|
# We extract fields provided by the caller via the data object.
|
|
|
|
# The only fields that are required are email and subdomain (if we
|
|
|
|
# are simply doing login); more fields are expected if this is a
|
|
|
|
# new account registration flow or we're going to a specific
|
|
|
|
# narrow after login.
|
2017-10-03 02:24:27 +02:00
|
|
|
subdomain = get_subdomain(request)
|
|
|
|
if data['subdomain'] != subdomain:
|
2020-01-23 12:21:55 +01:00
|
|
|
raise JsonableError(_("Invalid subdomain"))
|
2016-10-14 14:12:16 +02:00
|
|
|
email_address = data['email']
|
2019-02-08 17:09:25 +01:00
|
|
|
|
2020-01-20 16:51:24 +01:00
|
|
|
full_name = data.get('name', '')
|
|
|
|
is_signup = data.get('is_signup', False)
|
|
|
|
redirect_to = data.get('next', '')
|
2020-02-06 18:27:10 +01:00
|
|
|
mobile_flow_otp = data.get('mobile_flow_otp')
|
|
|
|
desktop_flow_otp = data.get('desktop_flow_otp')
|
2020-01-20 16:51:24 +01:00
|
|
|
full_name_validated = data.get('full_name_validated', False)
|
|
|
|
multiuse_object_key = data.get('multiuse_object_key', '')
|
2019-02-08 17:09:25 +01:00
|
|
|
|
2019-03-10 02:43:29 +01:00
|
|
|
# We cannot pass the actual authenticated user_profile object that
|
|
|
|
# was fetched by the original authentication backend and passed
|
|
|
|
# into redirect_and_log_into_subdomain through a signed URL token,
|
|
|
|
# so we need to re-fetch it from the database.
|
2017-05-10 09:00:47 +02:00
|
|
|
if is_signup:
|
2019-03-10 02:43:29 +01:00
|
|
|
# If we are creating a new user account, user_profile will
|
|
|
|
# always have been None, so we set that here. In the event
|
|
|
|
# that a user account with this email was somehow created in a
|
|
|
|
# race, the eventual registration code will catch that and
|
|
|
|
# throw an error, so we don't need to check for that here.
|
2017-05-10 09:00:47 +02:00
|
|
|
user_profile = None
|
|
|
|
else:
|
2019-03-10 02:43:29 +01:00
|
|
|
# We're just trying to login. We can be reasonably confident
|
|
|
|
# that this subdomain actually has a corresponding active
|
|
|
|
# realm, since the signed cookie proves there was one very
|
|
|
|
# recently. But as part of fetching the UserProfile object
|
|
|
|
# for the target user, we use DummyAuthBackend, which
|
|
|
|
# conveniently re-validates that the realm and user account
|
|
|
|
# were not deactivated in the meantime.
|
|
|
|
|
|
|
|
# Note: Ideally, we'd have a nice user-facing error message
|
|
|
|
# for the case where this auth fails (because e.g. the realm
|
|
|
|
# or user was deactivated since the signed cookie was
|
|
|
|
# generated < 15 seconds ago), but the authentication result
|
|
|
|
# is correct in those cases and such a race would be very
|
|
|
|
# rare, so a nice error message is low priority.
|
2017-10-03 02:24:27 +02:00
|
|
|
realm = get_realm(subdomain)
|
2019-05-05 00:40:30 +02:00
|
|
|
user_profile = authenticate_remote_user(realm, email_address)
|
2019-03-10 02:43:29 +01:00
|
|
|
|
2016-10-14 14:12:16 +02:00
|
|
|
return login_or_register_remote_user(request, email_address, user_profile,
|
2019-05-05 00:40:30 +02:00
|
|
|
full_name,
|
2019-02-08 17:09:25 +01:00
|
|
|
is_signup=is_signup, redirect_to=redirect_to,
|
2020-02-06 18:27:10 +01:00
|
|
|
mobile_flow_otp=mobile_flow_otp,
|
|
|
|
desktop_flow_otp=desktop_flow_otp,
|
2019-11-01 00:00:36 +01:00
|
|
|
multiuse_object_key=multiuse_object_key,
|
|
|
|
full_name_validated=full_name_validated)
|
2016-10-12 04:50:38 +02:00
|
|
|
|
2020-01-23 12:21:55 +01:00
|
|
|
def store_login_data(data: Dict[str, Any]) -> str:
|
|
|
|
key = put_dict_in_redis(redis_client, LOGIN_KEY_FORMAT, data,
|
|
|
|
expiration_seconds=LOGIN_KEY_EXPIRATION_SECONDS,
|
|
|
|
token_length=LOGIN_TOKEN_LENGTH)
|
|
|
|
token = key.split(LOGIN_KEY_PREFIX, 1)[1] # remove the prefix
|
|
|
|
return token
|
|
|
|
|
|
|
|
def get_login_data(token: str, should_delete: bool=True) -> Optional[Dict[str, Any]]:
|
|
|
|
key = LOGIN_KEY_FORMAT.format(token=token)
|
2020-01-26 19:01:56 +01:00
|
|
|
data = get_dict_from_redis(redis_client, LOGIN_KEY_FORMAT, key)
|
2020-01-23 12:21:55 +01:00
|
|
|
if data is not None and should_delete:
|
|
|
|
redis_client.delete(key)
|
|
|
|
return data
|
|
|
|
|
2018-04-24 03:47:28 +02:00
|
|
|
def redirect_and_log_into_subdomain(realm: Realm, full_name: str, email_address: str,
|
2019-02-08 17:09:25 +01:00
|
|
|
is_signup: bool=False, redirect_to: str='',
|
2020-02-06 18:27:10 +01:00
|
|
|
mobile_flow_otp: Optional[str]=None,
|
|
|
|
desktop_flow_otp: Optional[str]=None,
|
2019-11-01 00:00:36 +01:00
|
|
|
multiuse_object_key: str='',
|
2020-02-06 18:27:10 +01:00
|
|
|
full_name_validated: bool=False,) -> HttpResponse:
|
2017-10-27 00:27:59 +02:00
|
|
|
data = {'name': full_name, 'email': email_address, 'subdomain': realm.subdomain,
|
2019-02-08 17:09:25 +01:00
|
|
|
'is_signup': is_signup, 'next': redirect_to,
|
2020-02-06 18:27:10 +01:00
|
|
|
'mobile_flow_otp': mobile_flow_otp,
|
|
|
|
'desktop_flow_otp': desktop_flow_otp,
|
2019-11-01 00:00:36 +01:00
|
|
|
'multiuse_object_key': multiuse_object_key,
|
|
|
|
'full_name_validated': full_name_validated}
|
2020-01-23 12:21:55 +01:00
|
|
|
token = store_login_data(data)
|
2017-10-27 02:45:38 +02:00
|
|
|
subdomain_login_uri = (realm.uri
|
|
|
|
+ reverse('zerver.views.auth.log_into_subdomain', args=[token]))
|
|
|
|
return redirect(subdomain_login_uri)
|
2017-10-27 00:27:59 +02:00
|
|
|
|
2017-11-27 09:28:57 +01:00
|
|
|
def get_dev_users(realm: Optional[Realm]=None, extra_users_count: int=10) -> List[UserProfile]:
|
2017-02-04 20:16:46 +01:00
|
|
|
# Development environments usually have only a few users, but
|
|
|
|
# it still makes sense to limit how many extra users we render to
|
|
|
|
# support performance testing with DevAuthBackend.
|
2017-08-15 00:13:58 +02:00
|
|
|
if realm is not None:
|
|
|
|
users_query = UserProfile.objects.select_related().filter(is_bot=False, is_active=True, realm=realm)
|
|
|
|
else:
|
|
|
|
users_query = UserProfile.objects.select_related().filter(is_bot=False, is_active=True)
|
|
|
|
|
2017-02-04 20:16:46 +01:00
|
|
|
shakespearian_users = users_query.exclude(email__startswith='extrauser').order_by('email')
|
|
|
|
extra_users = users_query.filter(email__startswith='extrauser').order_by('email')
|
|
|
|
# Limit the number of extra users we offer by default
|
|
|
|
extra_users = extra_users[0:extra_users_count]
|
|
|
|
users = list(shakespearian_users) + list(extra_users)
|
|
|
|
return users
|
|
|
|
|
2017-11-27 09:28:57 +01:00
|
|
|
def redirect_to_misconfigured_ldap_notice(error_type: int) -> HttpResponse:
|
2017-09-22 10:58:12 +02:00
|
|
|
if error_type == ZulipLDAPAuthBackend.REALM_IS_NONE_ERROR:
|
|
|
|
url = reverse('ldap_error_realm_is_none')
|
|
|
|
else:
|
|
|
|
raise AssertionError("Invalid error type")
|
|
|
|
|
|
|
|
return HttpResponseRedirect(url)
|
|
|
|
|
2017-11-27 09:28:57 +01:00
|
|
|
def show_deactivation_notice(request: HttpRequest) -> HttpResponse:
|
2017-10-27 00:27:59 +02:00
|
|
|
realm = get_realm_from_request(request)
|
|
|
|
if realm and realm.deactivated:
|
|
|
|
return render(request, "zerver/deactivated.html",
|
|
|
|
context={"deactivated_domain_name": realm.name})
|
|
|
|
|
|
|
|
return HttpResponseRedirect(reverse('zerver.views.auth.login_page'))
|
|
|
|
|
2017-11-27 09:28:57 +01:00
|
|
|
def redirect_to_deactivation_notice() -> HttpResponse:
|
2017-10-27 00:27:59 +02:00
|
|
|
return HttpResponseRedirect(reverse('zerver.views.auth.show_deactivation_notice'))
|
|
|
|
|
2019-05-04 04:47:44 +02:00
|
|
|
def add_dev_login_context(realm: Optional[Realm], context: Dict[str, Any]) -> None:
|
2017-11-29 00:17:33 +01:00
|
|
|
users = get_dev_users(realm)
|
|
|
|
context['current_realm'] = realm
|
|
|
|
context['all_realms'] = Realm.objects.all()
|
|
|
|
|
|
|
|
context['direct_admins'] = [u for u in users if u.is_realm_admin]
|
2018-04-20 22:12:02 +02:00
|
|
|
context['guest_users'] = [u for u in users if u.is_guest]
|
|
|
|
context['direct_users'] = [u for u in users if not (u.is_realm_admin or u.is_guest)]
|
2017-11-29 00:17:33 +01:00
|
|
|
|
2017-12-20 07:26:29 +01:00
|
|
|
def update_login_page_context(request: HttpRequest, context: Dict[str, Any]) -> None:
|
2019-04-12 06:24:58 +02:00
|
|
|
for key in ('email', 'subdomain', 'already_registered', 'is_deactivated'):
|
2017-12-20 07:26:29 +01:00
|
|
|
try:
|
|
|
|
context[key] = request.GET[key]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
|
2019-04-12 06:24:58 +02:00
|
|
|
context['deactivated_account_error'] = DEACTIVATED_ACCOUNT_ERROR
|
2017-12-20 07:26:29 +01:00
|
|
|
context['wrong_subdomain_error'] = WRONG_SUBDOMAIN_ERROR
|
|
|
|
|
2017-12-20 07:57:26 +01:00
|
|
|
class TwoFactorLoginView(BaseTwoFactorLoginView):
|
|
|
|
extra_context = None # type: ExtraContext
|
|
|
|
form_list = (
|
|
|
|
('auth', OurAuthenticationForm),
|
|
|
|
('token', AuthenticationTokenForm),
|
|
|
|
('backup', BackupTokenForm),
|
|
|
|
)
|
|
|
|
|
|
|
|
def __init__(self, extra_context: ExtraContext=None,
|
|
|
|
*args: Any, **kwargs: Any) -> None:
|
|
|
|
self.extra_context = extra_context
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
def get_context_data(self, **kwargs: Any) -> Dict[str, Any]:
|
2018-06-05 05:55:42 +02:00
|
|
|
context = super().get_context_data(**kwargs)
|
2017-12-20 07:57:26 +01:00
|
|
|
if self.extra_context is not None:
|
|
|
|
context.update(self.extra_context)
|
|
|
|
update_login_page_context(self.request, context)
|
|
|
|
|
|
|
|
realm = get_realm_from_request(self.request)
|
|
|
|
redirect_to = realm.uri if realm else '/'
|
|
|
|
context['next'] = self.request.GET.get('next', redirect_to)
|
|
|
|
return context
|
|
|
|
|
|
|
|
def done(self, form_list: List[Form], **kwargs: Any) -> HttpResponse:
|
|
|
|
"""
|
|
|
|
Login the user and redirect to the desired page.
|
|
|
|
|
|
|
|
We need to override this function so that we can redirect to
|
|
|
|
realm.uri instead of '/'.
|
|
|
|
"""
|
2018-06-05 10:25:41 +02:00
|
|
|
realm_uri = self.get_user().realm.uri
|
2018-10-18 00:27:27 +02:00
|
|
|
# This mock.patch business is an unpleasant hack that we'd
|
|
|
|
# ideally like to remove by instead patching the upstream
|
|
|
|
# module to support better configurability of the
|
|
|
|
# LOGIN_REDIRECT_URL setting. But until then, it works. We
|
|
|
|
# import mock.patch here because mock has an expensive import
|
|
|
|
# process involving pbr -> pkgresources (which is really slow).
|
|
|
|
from mock import patch
|
2018-06-05 10:25:41 +02:00
|
|
|
with patch.object(settings, 'LOGIN_REDIRECT_URL', realm_uri):
|
|
|
|
return super().done(form_list, **kwargs)
|
2017-12-20 07:57:26 +01:00
|
|
|
|
2017-11-27 09:28:57 +01:00
|
|
|
def login_page(request: HttpRequest, **kwargs: Any) -> HttpResponse:
|
2019-04-13 09:37:53 +02:00
|
|
|
# To support previewing the Zulip login pages, we have a special option
|
|
|
|
# that disables the default behavior of redirecting logged-in users to the
|
|
|
|
# logged-in app.
|
2019-08-12 05:44:35 +02:00
|
|
|
is_preview = 'preview' in request.GET
|
2017-07-12 09:50:19 +02:00
|
|
|
if settings.TWO_FACTOR_AUTHENTICATION_ENABLED:
|
|
|
|
if request.user and request.user.is_verified():
|
|
|
|
return HttpResponseRedirect(request.user.realm.uri)
|
2019-04-13 09:37:53 +02:00
|
|
|
elif request.user.is_authenticated and not is_preview:
|
2017-10-06 01:19:11 +02:00
|
|
|
return HttpResponseRedirect(request.user.realm.uri)
|
2017-08-25 04:32:16 +02:00
|
|
|
if is_subdomain_root_or_alias(request) and settings.ROOT_DOMAIN_LANDING_PAGE:
|
2018-08-25 16:21:59 +02:00
|
|
|
redirect_url = reverse('zerver.views.registration.realm_redirect')
|
2019-08-12 05:44:35 +02:00
|
|
|
if request.GET:
|
2018-08-25 16:21:59 +02:00
|
|
|
redirect_url = "{}?{}".format(redirect_url, request.GET.urlencode())
|
2017-01-10 10:44:56 +01:00
|
|
|
return HttpResponseRedirect(redirect_url)
|
|
|
|
|
2017-08-24 09:58:44 +02:00
|
|
|
realm = get_realm_from_request(request)
|
|
|
|
if realm and realm.deactivated:
|
|
|
|
return redirect_to_deactivation_notice()
|
|
|
|
|
2016-10-12 04:50:38 +02:00
|
|
|
extra_context = kwargs.pop('extra_context', {})
|
2019-03-17 22:03:57 +01:00
|
|
|
if dev_auth_enabled() and kwargs.get("template_name") == "zerver/dev_login.html":
|
2017-08-15 00:13:58 +02:00
|
|
|
if 'new_realm' in request.POST:
|
2019-05-21 23:37:21 +02:00
|
|
|
try:
|
|
|
|
realm = get_realm(request.POST['new_realm'])
|
|
|
|
except Realm.DoesNotExist:
|
|
|
|
realm = None
|
2017-08-15 00:13:58 +02:00
|
|
|
|
2017-11-29 00:17:33 +01:00
|
|
|
add_dev_login_context(realm, extra_context)
|
2017-10-23 20:33:56 +02:00
|
|
|
if realm and 'new_realm' in request.POST:
|
|
|
|
# If we're switching realms, redirect to that realm, but
|
|
|
|
# only if it actually exists.
|
2017-08-15 00:13:58 +02:00
|
|
|
return HttpResponseRedirect(realm.uri)
|
|
|
|
|
2018-02-23 09:02:13 +01:00
|
|
|
if 'username' in request.POST:
|
|
|
|
extra_context['email'] = request.POST['username']
|
2020-01-31 15:02:28 +01:00
|
|
|
extra_context.update(login_context(request))
|
2018-02-23 09:02:13 +01:00
|
|
|
|
2017-07-12 09:50:19 +02:00
|
|
|
if settings.TWO_FACTOR_AUTHENTICATION_ENABLED:
|
|
|
|
return start_two_factor_auth(request, extra_context=extra_context,
|
|
|
|
**kwargs)
|
|
|
|
|
2017-09-22 10:58:12 +02:00
|
|
|
try:
|
2020-02-02 13:12:38 +01:00
|
|
|
template_response = DjangoLoginView.as_view(
|
|
|
|
authentication_form=OurAuthenticationForm,
|
|
|
|
extra_context=extra_context, **kwargs)(request)
|
2017-09-22 10:58:12 +02:00
|
|
|
except ZulipLDAPConfigurationError as e:
|
|
|
|
assert len(e.args) > 1
|
|
|
|
return redirect_to_misconfigured_ldap_notice(e.args[1])
|
|
|
|
|
2018-05-21 06:40:18 +02:00
|
|
|
if isinstance(template_response, SimpleTemplateResponse):
|
|
|
|
# Only those responses that are rendered using a template have
|
|
|
|
# context_data attribute. This attribute doesn't exist otherwise. It is
|
|
|
|
# added in SimpleTemplateResponse class, which is a derived class of
|
|
|
|
# HttpResponse. See django.template.response.SimpleTemplateResponse,
|
|
|
|
# https://github.com/django/django/blob/master/django/template/response.py#L19.
|
|
|
|
update_login_page_context(request, template_response.context_data)
|
2017-12-20 09:53:50 +01:00
|
|
|
|
2016-10-12 04:50:38 +02:00
|
|
|
return template_response
|
|
|
|
|
2017-07-12 09:50:19 +02:00
|
|
|
def start_two_factor_auth(request: HttpRequest,
|
|
|
|
extra_context: ExtraContext=None,
|
|
|
|
**kwargs: Any) -> HttpResponse:
|
|
|
|
two_fa_form_field = 'two_factor_login_view-current_step'
|
|
|
|
if two_fa_form_field not in request.POST:
|
|
|
|
# Here we inject the 2FA step in the request context if it's missing to
|
|
|
|
# force the user to go to the first step of 2FA authentication process.
|
|
|
|
# This seems a bit hackish but simplifies things from testing point of
|
|
|
|
# view. I don't think this can result in anything bad because all the
|
|
|
|
# authentication logic runs after the auth step.
|
|
|
|
#
|
|
|
|
# If we don't do this, we will have to modify a lot of auth tests to
|
|
|
|
# insert this variable in the request.
|
|
|
|
request.POST = request.POST.copy()
|
|
|
|
request.POST.update({two_fa_form_field: 'auth'})
|
|
|
|
|
|
|
|
"""
|
|
|
|
This is how Django implements as_view(), so extra_context will be passed
|
|
|
|
to the __init__ method of TwoFactorLoginView.
|
|
|
|
|
|
|
|
def as_view(cls, **initkwargs):
|
|
|
|
def view(request, *args, **kwargs):
|
|
|
|
self = cls(**initkwargs)
|
|
|
|
...
|
|
|
|
|
|
|
|
return view
|
|
|
|
"""
|
|
|
|
two_fa_view = TwoFactorLoginView.as_view(extra_context=extra_context,
|
|
|
|
**kwargs)
|
|
|
|
return two_fa_view(request, **kwargs)
|
|
|
|
|
2017-10-11 17:30:04 +02:00
|
|
|
@csrf_exempt
|
2017-11-27 09:28:57 +01:00
|
|
|
def dev_direct_login(request: HttpRequest, **kwargs: Any) -> HttpResponse:
|
2017-11-05 03:14:28 +01:00
|
|
|
# This function allows logging in without a password and should only be called
|
|
|
|
# in development environments. It may be called if the DevAuthBackend is included
|
|
|
|
# in settings.AUTHENTICATION_BACKENDS
|
2016-10-12 04:50:38 +02:00
|
|
|
if (not dev_auth_enabled()) or settings.PRODUCTION:
|
2017-11-05 03:14:28 +01:00
|
|
|
# This check is probably not required, since authenticate would fail without
|
|
|
|
# an enabled DevAuthBackend.
|
2018-02-21 06:31:53 +01:00
|
|
|
return HttpResponseRedirect(reverse('dev_not_supported'))
|
2016-10-12 04:50:38 +02:00
|
|
|
email = request.POST['direct_email']
|
2017-11-21 21:13:46 +01:00
|
|
|
subdomain = get_subdomain(request)
|
|
|
|
realm = get_realm(subdomain)
|
2017-11-21 21:19:20 +01:00
|
|
|
user_profile = authenticate(dev_auth_username=email, realm=realm)
|
2016-10-12 04:50:38 +02:00
|
|
|
if user_profile is None:
|
2018-02-21 06:31:53 +01:00
|
|
|
return HttpResponseRedirect(reverse('dev_not_supported'))
|
2017-08-25 01:11:30 +02:00
|
|
|
do_login(request, user_profile)
|
2018-03-12 12:25:50 +01:00
|
|
|
|
|
|
|
next = request.GET.get('next', '')
|
|
|
|
redirect_to = get_safe_redirect_to(next, user_profile.realm.uri)
|
|
|
|
return HttpResponseRedirect(redirect_to)
|
2016-10-12 04:50:38 +02:00
|
|
|
|
|
|
|
@csrf_exempt
|
|
|
|
@require_post
|
|
|
|
@has_request_variables
|
2017-11-27 09:28:57 +01:00
|
|
|
def api_dev_fetch_api_key(request: HttpRequest, username: str=REQ()) -> HttpResponse:
|
2016-10-12 04:50:38 +02:00
|
|
|
"""This function allows logging in without a password on the Zulip
|
|
|
|
mobile apps when connecting to a Zulip development environment. It
|
|
|
|
requires DevAuthBackend to be included in settings.AUTHENTICATION_BACKENDS.
|
|
|
|
"""
|
|
|
|
if not dev_auth_enabled() or settings.PRODUCTION:
|
|
|
|
return json_error(_("Dev environment not enabled."))
|
2017-04-07 08:21:29 +02:00
|
|
|
|
|
|
|
# Django invokes authenticate methods by matching arguments, and this
|
|
|
|
# authentication flow will not invoke LDAP authentication because of
|
|
|
|
# this condition of Django so no need to check if LDAP backend is
|
|
|
|
# enabled.
|
|
|
|
validate_login_email(username)
|
|
|
|
|
2017-11-21 21:13:46 +01:00
|
|
|
subdomain = get_subdomain(request)
|
|
|
|
realm = get_realm(subdomain)
|
|
|
|
|
2017-05-17 22:09:33 +02:00
|
|
|
return_data = {} # type: Dict[str, bool]
|
2017-11-21 21:13:46 +01:00
|
|
|
user_profile = authenticate(dev_auth_username=username,
|
2017-11-21 21:19:20 +01:00
|
|
|
realm=realm,
|
2016-10-12 04:50:38 +02:00
|
|
|
return_data=return_data)
|
2017-01-24 06:11:18 +01:00
|
|
|
if return_data.get("inactive_realm"):
|
2018-03-08 01:30:34 +01:00
|
|
|
return json_error(_("This organization has been deactivated."),
|
2016-10-12 04:50:38 +02:00
|
|
|
data={"reason": "realm deactivated"}, status=403)
|
2017-01-24 06:11:18 +01:00
|
|
|
if return_data.get("inactive_user"):
|
2016-10-12 04:50:38 +02:00
|
|
|
return json_error(_("Your account has been disabled."),
|
|
|
|
data={"reason": "user disable"}, status=403)
|
2017-05-22 01:34:21 +02:00
|
|
|
if user_profile is None:
|
|
|
|
return json_error(_("This user is not registered."),
|
|
|
|
data={"reason": "unregistered"}, status=403)
|
2017-08-25 01:11:30 +02:00
|
|
|
do_login(request, user_profile)
|
2018-08-01 10:53:40 +02:00
|
|
|
api_key = get_api_key(user_profile)
|
2019-04-04 22:24:29 +02:00
|
|
|
return json_success({"api_key": api_key, "email": user_profile.delivery_email})
|
2016-10-12 04:50:38 +02:00
|
|
|
|
|
|
|
@csrf_exempt
|
2018-04-05 21:16:56 +02:00
|
|
|
def api_dev_list_users(request: HttpRequest) -> HttpResponse:
|
2016-10-12 04:50:38 +02:00
|
|
|
if not dev_auth_enabled() or settings.PRODUCTION:
|
|
|
|
return json_error(_("Dev environment not enabled."))
|
2017-02-04 20:16:46 +01:00
|
|
|
users = get_dev_users()
|
2019-04-04 22:24:29 +02:00
|
|
|
return json_success(dict(direct_admins=[dict(email=u.delivery_email, realm_uri=u.realm.uri)
|
2018-04-05 21:16:56 +02:00
|
|
|
for u in users if u.is_realm_admin],
|
2019-04-04 22:24:29 +02:00
|
|
|
direct_users=[dict(email=u.delivery_email, realm_uri=u.realm.uri)
|
2018-04-05 21:16:56 +02:00
|
|
|
for u in users if not u.is_realm_admin]))
|
2016-10-12 04:50:38 +02:00
|
|
|
|
|
|
|
@csrf_exempt
|
|
|
|
@require_post
|
|
|
|
@has_request_variables
|
2017-11-27 09:28:57 +01:00
|
|
|
def api_fetch_api_key(request: HttpRequest, username: str=REQ(), password: str=REQ()) -> HttpResponse:
|
2017-05-17 22:09:33 +02:00
|
|
|
return_data = {} # type: Dict[str, bool]
|
2017-11-17 23:56:45 +01:00
|
|
|
subdomain = get_subdomain(request)
|
|
|
|
realm = get_realm(subdomain)
|
2019-02-02 16:51:26 +01:00
|
|
|
if not ldap_auth_enabled(realm=get_realm_from_request(request)):
|
|
|
|
# In case we don't authenticate against LDAP, check for a valid
|
|
|
|
# email. LDAP backend can authenticate against a non-email.
|
|
|
|
validate_login_email(username)
|
2019-08-01 14:08:06 +02:00
|
|
|
user_profile = authenticate(request=request,
|
|
|
|
username=username,
|
2019-02-02 16:51:26 +01:00
|
|
|
password=password,
|
|
|
|
realm=realm,
|
|
|
|
return_data=return_data)
|
2017-01-24 06:11:18 +01:00
|
|
|
if return_data.get("inactive_user"):
|
2016-10-12 04:50:38 +02:00
|
|
|
return json_error(_("Your account has been disabled."),
|
|
|
|
data={"reason": "user disable"}, status=403)
|
2017-01-24 06:11:18 +01:00
|
|
|
if return_data.get("inactive_realm"):
|
2018-03-08 01:30:34 +01:00
|
|
|
return json_error(_("This organization has been deactivated."),
|
2016-10-12 04:50:38 +02:00
|
|
|
data={"reason": "realm deactivated"}, status=403)
|
2017-01-24 06:11:18 +01:00
|
|
|
if return_data.get("password_auth_disabled"):
|
2016-10-12 04:50:38 +02:00
|
|
|
return json_error(_("Password auth is disabled in your team."),
|
|
|
|
data={"reason": "password auth disabled"}, status=403)
|
|
|
|
if user_profile is None:
|
|
|
|
return json_error(_("Your username or password is incorrect."),
|
|
|
|
data={"reason": "incorrect_creds"}, status=403)
|
2017-06-15 07:15:57 +02:00
|
|
|
|
|
|
|
# Maybe sending 'user_logged_in' signal is the better approach:
|
|
|
|
# user_logged_in.send(sender=user_profile.__class__, request=request, user=user_profile)
|
|
|
|
# Not doing this only because over here we don't add the user information
|
|
|
|
# in the session. If the signal receiver assumes that we do then that
|
|
|
|
# would cause problems.
|
|
|
|
email_on_new_login(sender=user_profile.__class__, request=request, user=user_profile)
|
2017-08-25 00:58:34 +02:00
|
|
|
|
|
|
|
# Mark this request as having a logged-in user for our server logs.
|
|
|
|
process_client(request, user_profile)
|
2020-01-18 14:03:30 +01:00
|
|
|
request._email = user_profile.delivery_email
|
2017-08-25 00:58:34 +02:00
|
|
|
|
2018-08-01 10:53:40 +02:00
|
|
|
api_key = get_api_key(user_profile)
|
2019-04-04 22:24:29 +02:00
|
|
|
return json_success({"api_key": api_key, "email": user_profile.delivery_email})
|
2016-10-12 04:50:38 +02:00
|
|
|
|
2017-11-27 09:28:57 +01:00
|
|
|
def get_auth_backends_data(request: HttpRequest) -> Dict[str, Any]:
|
2017-03-10 06:29:09 +01:00
|
|
|
"""Returns which authentication methods are enabled on the server"""
|
2017-10-02 08:32:09 +02:00
|
|
|
subdomain = get_subdomain(request)
|
|
|
|
try:
|
|
|
|
realm = Realm.objects.get(string_id=subdomain)
|
|
|
|
except Realm.DoesNotExist:
|
|
|
|
# If not the root subdomain, this is an error
|
2017-10-20 02:56:49 +02:00
|
|
|
if subdomain != Realm.SUBDOMAIN_FOR_ROOT_DOMAIN:
|
2017-10-02 08:32:09 +02:00
|
|
|
raise JsonableError(_("Invalid subdomain"))
|
|
|
|
# With the root subdomain, it's an error or not depending
|
|
|
|
# whether ROOT_DOMAIN_LANDING_PAGE (which indicates whether
|
|
|
|
# there are some realms without subdomains on this server)
|
|
|
|
# is set.
|
|
|
|
if settings.ROOT_DOMAIN_LANDING_PAGE:
|
|
|
|
raise JsonableError(_("Subdomain required"))
|
|
|
|
else:
|
|
|
|
realm = None
|
2018-12-19 01:13:59 +01:00
|
|
|
result = {
|
2017-10-24 20:59:11 +02:00
|
|
|
"password": password_auth_enabled(realm),
|
|
|
|
}
|
2018-12-19 01:13:59 +01:00
|
|
|
for auth_backend_name in AUTH_BACKEND_NAME_MAP:
|
|
|
|
key = auth_backend_name.lower()
|
|
|
|
result[key] = auth_enabled_helper([auth_backend_name], realm)
|
|
|
|
return result
|
2017-05-04 01:13:40 +02:00
|
|
|
|
2018-12-06 02:49:34 +01:00
|
|
|
def check_server_incompatibility(request: HttpRequest) -> bool:
|
2018-12-11 20:29:25 +01:00
|
|
|
user_agent = parse_user_agent(request.META.get("HTTP_USER_AGENT", "Missing User-Agent"))
|
2018-12-06 02:49:34 +01:00
|
|
|
return user_agent['name'] == "ZulipInvalid"
|
|
|
|
|
2019-08-12 05:44:35 +02:00
|
|
|
@require_safe
|
2017-05-04 01:13:56 +02:00
|
|
|
@csrf_exempt
|
2017-11-27 09:28:57 +01:00
|
|
|
def api_get_server_settings(request: HttpRequest) -> HttpResponse:
|
2018-12-11 20:25:57 +01:00
|
|
|
# Log which client is making this request.
|
|
|
|
process_client(request, request.user, skip_update_user_activity=True)
|
2017-05-04 01:13:56 +02:00
|
|
|
result = dict(
|
|
|
|
authentication_methods=get_auth_backends_data(request),
|
|
|
|
zulip_version=ZULIP_VERSION,
|
2018-02-12 23:34:59 +01:00
|
|
|
push_notifications_enabled=push_notifications_enabled(),
|
2018-12-06 02:49:34 +01:00
|
|
|
is_incompatible=check_server_incompatibility(request),
|
2017-05-04 01:13:56 +02:00
|
|
|
)
|
|
|
|
context = zulip_default_context(request)
|
2019-03-20 13:13:44 +01:00
|
|
|
context.update(login_context(request))
|
2017-05-04 01:13:56 +02:00
|
|
|
# IMPORTANT NOTE:
|
|
|
|
# realm_name, realm_icon, etc. are not guaranteed to appear in the response.
|
|
|
|
# * If they do, that means the server URL has only one realm on it
|
|
|
|
# * If they don't, the server has multiple realms, and it's not clear which is
|
|
|
|
# the requested realm, so we can't send back these data.
|
2017-09-15 19:13:48 +02:00
|
|
|
for settings_item in [
|
|
|
|
"email_auth_enabled",
|
|
|
|
"require_email_format_usernames",
|
|
|
|
"realm_uri",
|
|
|
|
"realm_name",
|
|
|
|
"realm_icon",
|
2019-10-22 01:33:44 +02:00
|
|
|
"realm_description",
|
2019-11-03 23:51:49 +01:00
|
|
|
"external_authentication_methods"]:
|
2017-05-04 01:13:56 +02:00
|
|
|
if context[settings_item] is not None:
|
|
|
|
result[settings_item] = context[settings_item]
|
|
|
|
return json_success(result)
|
|
|
|
|
2016-10-12 04:50:38 +02:00
|
|
|
@has_request_variables
|
2017-11-27 09:28:57 +01:00
|
|
|
def json_fetch_api_key(request: HttpRequest, user_profile: UserProfile,
|
|
|
|
password: str=REQ(default='')) -> HttpResponse:
|
2017-11-17 23:56:45 +01:00
|
|
|
subdomain = get_subdomain(request)
|
|
|
|
realm = get_realm(subdomain)
|
2016-10-12 04:50:38 +02:00
|
|
|
if password_auth_enabled(user_profile.realm):
|
2019-08-01 14:08:06 +02:00
|
|
|
if not authenticate(request=request, username=user_profile.delivery_email, password=password,
|
2017-11-17 23:56:45 +01:00
|
|
|
realm=realm):
|
2016-10-12 04:50:38 +02:00
|
|
|
return json_error(_("Your username or password is incorrect."))
|
2018-08-01 10:53:40 +02:00
|
|
|
|
|
|
|
api_key = get_api_key(user_profile)
|
|
|
|
return json_success({"api_key": api_key})
|
2016-10-12 04:50:38 +02:00
|
|
|
|
|
|
|
@csrf_exempt
|
2017-11-27 09:28:57 +01:00
|
|
|
def api_fetch_google_client_id(request: HttpRequest) -> HttpResponse:
|
2016-10-12 04:50:38 +02:00
|
|
|
if not settings.GOOGLE_CLIENT_ID:
|
|
|
|
return json_error(_("GOOGLE_CLIENT_ID is not configured"), status=400)
|
|
|
|
return json_success({"google_client_id": settings.GOOGLE_CLIENT_ID})
|
|
|
|
|
|
|
|
@require_post
|
2017-11-27 09:28:57 +01:00
|
|
|
def logout_then_login(request: HttpRequest, **kwargs: Any) -> HttpResponse:
|
2016-10-12 04:50:38 +02:00
|
|
|
return django_logout_then_login(request, kwargs)
|
2017-11-18 03:30:07 +01:00
|
|
|
|
2020-02-02 14:44:13 +01:00
|
|
|
def password_reset(request: HttpRequest) -> HttpResponse:
|
2019-05-04 04:47:44 +02:00
|
|
|
if not Realm.objects.filter(string_id=get_subdomain(request)).exists():
|
2017-11-18 03:30:07 +01:00
|
|
|
# If trying to get to password reset on a subdomain that
|
|
|
|
# doesn't exist, just go to find_account.
|
|
|
|
redirect_url = reverse('zerver.views.registration.find_account')
|
|
|
|
return HttpResponseRedirect(redirect_url)
|
|
|
|
|
2020-02-02 14:44:13 +01:00
|
|
|
view_func = DjangoPasswordResetView.as_view(template_name='zerver/reset.html',
|
|
|
|
form_class=ZulipPasswordResetForm,
|
|
|
|
success_url='/accounts/password/reset/done/')
|
|
|
|
return view_func(request)
|
2019-09-29 06:32:56 +02:00
|
|
|
|
|
|
|
@csrf_exempt
|
|
|
|
def saml_sp_metadata(request: HttpRequest, **kwargs: Any) -> HttpResponse: # nocoverage
|
|
|
|
"""
|
|
|
|
This is the view function for generating our SP metadata
|
|
|
|
for SAML authentication. It's meant for helping check the correctness
|
|
|
|
of the configuration when setting up SAML, or for obtaining the XML metadata
|
|
|
|
if the IdP requires it.
|
|
|
|
Taken from https://python-social-auth.readthedocs.io/en/latest/backends/saml.html
|
|
|
|
"""
|
|
|
|
if not saml_auth_enabled():
|
|
|
|
return redirect_to_config_error("saml")
|
|
|
|
|
|
|
|
complete_url = reverse('social:complete', args=("saml",))
|
|
|
|
saml_backend = load_backend(load_strategy(request), "saml",
|
|
|
|
complete_url)
|
|
|
|
metadata, errors = saml_backend.generate_metadata_xml()
|
|
|
|
if not errors:
|
|
|
|
return HttpResponse(content=metadata,
|
|
|
|
content_type='text/xml')
|
|
|
|
|
|
|
|
return HttpResponseServerError(content=', '.join(errors))
|