2017-07-12 09:50:19 +02:00
|
|
|
import django_otp
|
|
|
|
from two_factor.utils import default_device
|
2019-09-23 02:06:21 +02:00
|
|
|
from django_otp import user_has_device
|
2017-07-12 09:50:19 +02:00
|
|
|
|
2017-07-12 10:16:02 +02:00
|
|
|
from django.contrib.auth.decorators import user_passes_test as django_user_passes_test
|
2019-01-04 00:17:50 +01:00
|
|
|
from django.contrib.auth.models import AnonymousUser
|
2016-05-25 15:02:02 +02:00
|
|
|
from django.utils.translation import ugettext as _
|
2016-06-06 01:54:58 +02:00
|
|
|
from django.http import HttpResponseRedirect, HttpResponse
|
2017-08-25 01:11:30 +02:00
|
|
|
from django.contrib.auth import REDIRECT_FIELD_NAME, login as django_login
|
2012-11-06 20:27:55 +01:00
|
|
|
from django.views.decorators.csrf import csrf_exempt
|
2016-06-06 01:54:58 +02:00
|
|
|
from django.http import QueryDict, HttpResponseNotAllowed, HttpRequest
|
2013-03-21 20:18:44 +01:00
|
|
|
from django.http.multipartparser import MultiPartParser
|
2017-10-20 02:52:15 +02:00
|
|
|
from zerver.models import Realm, UserProfile, get_client, get_user_profile_by_api_key
|
2016-11-15 17:20:22 +01:00
|
|
|
from zerver.lib.response import json_error, json_unauthorized, json_success
|
2016-04-21 23:48:34 +02:00
|
|
|
from django.shortcuts import resolve_url
|
|
|
|
from django.utils.decorators import available_attrs
|
2017-04-15 04:03:56 +02:00
|
|
|
from django.utils.timezone import now as timezone_now
|
2012-11-28 05:37:13 +01:00
|
|
|
from django.conf import settings
|
2018-11-15 05:31:34 +01:00
|
|
|
|
2019-06-06 05:55:09 +02:00
|
|
|
from zerver.lib.exceptions import UnexpectedWebhookEventType
|
2013-07-29 23:03:31 +02:00
|
|
|
from zerver.lib.queue import queue_json_publish
|
2017-10-20 02:53:24 +02:00
|
|
|
from zerver.lib.subdomains import get_subdomain, user_matches_subdomain
|
2016-12-22 04:46:31 +01:00
|
|
|
from zerver.lib.timestamp import datetime_to_timestamp, timestamp_to_datetime
|
tests: Add uuid_get and uuid_post.
We want a clean codepath for the vast majority
of cases of using api_get/api_post, which now
uses email and which we'll soon convert to
accepting `user` as a parameter.
These apis that take two different types of
values for the same parameter make sweeps
like this kinda painful, and they're pretty
easy to avoid by extracting helpers to do
the actual common tasks. So, for example,
here I still keep a common method to
actually encode the credentials (since
the whole encode/decode business is an
annoying detail that you don't want to fix
in two places):
def encode_credentials(self, identifier: str, api_key: str) -> str:
"""
identifier: Can be an email or a remote server uuid.
"""
credentials = "%s:%s" % (identifier, api_key)
return 'Basic ' + base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
But then the rest of the code has two separate
codepaths.
And for the uuid functions, we no longer have
crufty references to realm. (In fairness, realm
will also go away when we introduce users.)
For the `is_remote_server` helper, I just inlined
it, since it's now only needed in one place, and the
name didn't make total sense anyway, plus it wasn't
a super robust check. In context, it's easier
just to use a comment now to say what we're doing:
# If `role` doesn't look like an email, it might be a uuid.
if settings.ZILENCER_ENABLED and role is not None and '@' not in role:
# do stuff
2020-03-10 12:34:25 +01:00
|
|
|
from zerver.lib.utils import statsd, has_api_key_format
|
2019-04-01 20:11:56 +02:00
|
|
|
from zerver.lib.exceptions import JsonableError, ErrorCode, \
|
2019-12-16 08:12:39 +01:00
|
|
|
InvalidJSONError, InvalidAPIKeyError, InvalidAPIKeyFormatError, \
|
2019-11-16 15:53:56 +01:00
|
|
|
OrganizationAdministratorRequired
|
2018-03-13 17:44:46 +01:00
|
|
|
from zerver.lib.types import ViewFuncT
|
2019-02-09 23:57:54 +01:00
|
|
|
from zerver.lib.validator import to_non_negative_int
|
2017-10-12 03:02:35 +02:00
|
|
|
|
2020-03-04 14:05:25 +01:00
|
|
|
from zerver.lib.rate_limiter import RateLimitedUser
|
2019-04-26 01:16:38 +02:00
|
|
|
from zerver.lib.request import REQ, has_request_variables
|
2013-10-17 16:33:04 +02:00
|
|
|
|
2012-11-02 00:23:26 +01:00
|
|
|
from functools import wraps
|
2013-03-21 20:15:27 +01:00
|
|
|
import base64
|
2016-12-22 04:46:31 +01:00
|
|
|
import datetime
|
2017-05-12 05:21:09 +02:00
|
|
|
import ujson
|
2017-08-25 15:25:00 +02:00
|
|
|
import logging
|
2016-07-15 07:42:54 +02:00
|
|
|
from io import BytesIO
|
2017-11-05 05:30:31 +01:00
|
|
|
import urllib
|
2013-04-16 22:52:32 +02:00
|
|
|
|
2019-02-02 23:53:55 +01:00
|
|
|
from typing import Union, Any, Callable, Dict, Optional, TypeVar, Tuple
|
2017-12-13 01:45:57 +01:00
|
|
|
from zerver.lib.logging_util import log_to_file
|
2016-06-06 01:54:58 +02:00
|
|
|
|
2016-10-27 23:55:31 +02:00
|
|
|
# This is a hack to ensure that RemoteZulipServer always exists even
|
|
|
|
# if Zilencer isn't enabled.
|
|
|
|
if settings.ZILENCER_ENABLED:
|
|
|
|
from zilencer.models import get_remote_server_by_uuid, RemoteZulipServer
|
2018-04-26 06:53:50 +02:00
|
|
|
else: # nocoverage # Hack here basically to make impossible code paths compile
|
2016-10-27 23:55:31 +02:00
|
|
|
from mock import Mock
|
|
|
|
get_remote_server_by_uuid = Mock()
|
2020-04-22 04:13:37 +02:00
|
|
|
RemoteZulipServer = Mock() # type: ignore[misc] # https://github.com/JukkaL/mypy/issues/1188
|
2016-10-27 23:55:31 +02:00
|
|
|
|
2017-10-29 06:28:41 +01:00
|
|
|
ReturnT = TypeVar('ReturnT')
|
2016-07-22 15:10:19 +02:00
|
|
|
|
2017-12-13 01:45:57 +01:00
|
|
|
webhook_logger = logging.getLogger("zulip.zerver.webhooks")
|
|
|
|
log_to_file(webhook_logger, settings.API_KEY_ONLY_WEBHOOK_LOG_PATH)
|
2017-05-12 05:21:09 +02:00
|
|
|
|
2019-06-06 05:55:09 +02:00
|
|
|
webhook_unexpected_events_logger = logging.getLogger("zulip.zerver.lib.webhooks.common")
|
|
|
|
log_to_file(webhook_unexpected_events_logger,
|
|
|
|
settings.WEBHOOK_UNEXPECTED_EVENTS_LOG_PATH)
|
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def cachify(method: Callable[..., ReturnT]) -> Callable[..., ReturnT]:
|
2017-11-08 05:43:05 +01:00
|
|
|
dct = {} # type: Dict[Tuple[Any, ...], ReturnT]
|
2017-10-31 00:31:47 +01:00
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def cache_wrapper(*args: Any) -> ReturnT:
|
2017-10-31 00:31:47 +01:00
|
|
|
tup = tuple(args)
|
|
|
|
if tup in dct:
|
|
|
|
return dct[tup]
|
|
|
|
result = method(*args)
|
|
|
|
dct[tup] = result
|
|
|
|
return result
|
|
|
|
return cache_wrapper
|
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def update_user_activity(request: HttpRequest, user_profile: UserProfile,
|
|
|
|
query: Optional[str]) -> None:
|
2013-03-25 20:37:00 +01:00
|
|
|
# update_active_status also pushes to rabbitmq, and it seems
|
|
|
|
# redundant to log that here as well.
|
2016-04-03 07:58:06 +02:00
|
|
|
if request.META["PATH_INFO"] == '/json/users/me/presence':
|
2013-03-25 20:37:00 +01:00
|
|
|
return
|
2013-10-03 19:48:03 +02:00
|
|
|
|
2017-11-03 22:44:59 +01:00
|
|
|
if query is not None:
|
|
|
|
pass
|
|
|
|
elif hasattr(request, '_query'):
|
2013-10-03 19:48:03 +02:00
|
|
|
query = request._query
|
|
|
|
else:
|
|
|
|
query = request.META['PATH_INFO']
|
|
|
|
|
2016-11-28 23:29:01 +01:00
|
|
|
event = {'query': query,
|
|
|
|
'user_profile_id': user_profile.id,
|
2017-04-15 04:03:56 +02:00
|
|
|
'time': datetime_to_timestamp(timezone_now()),
|
2016-11-28 23:29:01 +01:00
|
|
|
'client': request.client.name}
|
2013-03-25 20:37:00 +01:00
|
|
|
queue_json_publish("user_activity", event, lambda event: None)
|
2013-01-11 21:16:42 +01:00
|
|
|
|
2013-11-08 02:02:48 +01:00
|
|
|
# Based on django.views.decorators.http.require_http_methods
|
2017-11-27 07:33:05 +01:00
|
|
|
def require_post(func: ViewFuncT) -> ViewFuncT:
|
2013-11-08 02:02:48 +01:00
|
|
|
@wraps(func)
|
2017-11-27 07:33:05 +01:00
|
|
|
def wrapper(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
|
dependencies: Remove WebSockets system for sending messages.
Zulip has had a small use of WebSockets (specifically, for the code
path of sending messages, via the webapp only) since ~2013. We
originally added this use of WebSockets in the hope that the latency
benefits of doing so would allow us to avoid implementing a markdown
local echo; they were not. Further, HTTP/2 may have eliminated the
latency difference we hoped to exploit by using WebSockets in any
case.
While we’d originally imagined using WebSockets for other endpoints,
there was never a good justification for moving more components to the
WebSockets system.
This WebSockets code path had a lot of downsides/complexity,
including:
* The messy hack involving constructing an emulated request object to
hook into doing Django requests.
* The `message_senders` queue processor system, which increases RAM
needs and must be provisioned independently from the rest of the
server).
* A duplicate check_send_receive_time Nagios test specific to
WebSockets.
* The requirement for users to have their firewalls/NATs allow
WebSocket connections, and a setting to disable them for networks
where WebSockets don’t work.
* Dependencies on the SockJS family of libraries, which has at times
been poorly maintained, and periodically throws random JavaScript
exceptions in our production environments without a deep enough
traceback to effectively investigate.
* A total of about 1600 lines of our code related to the feature.
* Increased load on the Tornado system, especially around a Zulip
server restart, and especially for large installations like
zulipchat.com, resulting in extra delay before messages can be sent
again.
As detailed in
https://github.com/zulip/zulip/pull/12862#issuecomment-536152397, it
appears that removing WebSockets moderately increases the time it
takes for the `send_message` API query to return from the server, but
does not significantly change the time between when a message is sent
and when it is received by clients. We don’t understand the reason
for that change (suggesting the possibility of a measurement error),
and even if it is a real change, we consider that potential small
latency regression to be acceptable.
If we later want WebSockets, we’ll likely want to just use Django
Channels.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-07-23 01:43:40 +02:00
|
|
|
if request.method != "POST":
|
|
|
|
err_method = request.method
|
2013-11-08 02:02:48 +01:00
|
|
|
logging.warning('Method Not Allowed (%s): %s', err_method, request.path,
|
|
|
|
extra={'status_code': 405, 'request': request})
|
|
|
|
return HttpResponseNotAllowed(["POST"])
|
|
|
|
return func(request, *args, **kwargs)
|
2020-04-22 04:13:37 +02:00
|
|
|
return wrapper # type: ignore[return-value] # https://github.com/python/mypy/issues/1927
|
2012-11-06 20:27:55 +01:00
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def require_realm_admin(func: ViewFuncT) -> ViewFuncT:
|
2013-12-09 22:12:18 +01:00
|
|
|
@wraps(func)
|
2017-11-27 07:33:05 +01:00
|
|
|
def wrapper(request: HttpRequest, user_profile: UserProfile, *args: Any, **kwargs: Any) -> HttpResponse:
|
2016-02-08 03:59:38 +01:00
|
|
|
if not user_profile.is_realm_admin:
|
2019-11-16 15:53:56 +01:00
|
|
|
raise OrganizationAdministratorRequired()
|
2013-12-09 22:12:18 +01:00
|
|
|
return func(request, user_profile, *args, **kwargs)
|
2020-04-22 04:13:37 +02:00
|
|
|
return wrapper # type: ignore[return-value] # https://github.com/python/mypy/issues/1927
|
2013-12-09 22:12:18 +01:00
|
|
|
|
2018-11-01 11:26:29 +01:00
|
|
|
def require_billing_access(func: ViewFuncT) -> ViewFuncT:
|
|
|
|
@wraps(func)
|
|
|
|
def wrapper(request: HttpRequest, user_profile: UserProfile, *args: Any, **kwargs: Any) -> HttpResponse:
|
|
|
|
if not user_profile.is_realm_admin and not user_profile.is_billing_admin:
|
2018-11-01 22:17:36 +01:00
|
|
|
raise JsonableError(_("Must be a billing administrator or an organization administrator"))
|
2018-11-01 11:26:29 +01:00
|
|
|
return func(request, user_profile, *args, **kwargs)
|
2020-04-22 04:13:37 +02:00
|
|
|
return wrapper # type: ignore[return-value] # https://github.com/python/mypy/issues/1927
|
2018-11-01 11:26:29 +01:00
|
|
|
|
2013-12-19 18:10:30 +01:00
|
|
|
from zerver.lib.user_agent import parse_user_agent
|
2013-06-27 20:21:21 +02:00
|
|
|
|
2020-03-08 21:12:38 +01:00
|
|
|
def get_client_name(request: HttpRequest) -> str:
|
2013-12-19 18:10:30 +01:00
|
|
|
# If the API request specified a client in the request content,
|
|
|
|
# that has priority. Otherwise, extract the client from the
|
|
|
|
# User-Agent.
|
2020-03-08 21:12:38 +01:00
|
|
|
if 'client' in request.GET: # nocoverage
|
2016-11-03 13:00:18 +01:00
|
|
|
return request.GET['client']
|
2017-02-11 05:26:10 +01:00
|
|
|
if 'client' in request.POST:
|
2016-11-03 13:00:18 +01:00
|
|
|
return request.POST['client']
|
2017-02-11 05:26:10 +01:00
|
|
|
if "HTTP_USER_AGENT" in request.META:
|
2018-10-25 00:26:27 +02:00
|
|
|
user_agent = parse_user_agent(request.META["HTTP_USER_AGENT"]) # type: Optional[Dict[str, str]]
|
2017-02-11 05:26:10 +01:00
|
|
|
else:
|
|
|
|
user_agent = None
|
|
|
|
if user_agent is not None:
|
2020-03-08 21:12:38 +01:00
|
|
|
return user_agent["name"]
|
|
|
|
|
|
|
|
# In the future, we will require setting USER_AGENT, but for
|
|
|
|
# now we just want to tag these requests so we can review them
|
|
|
|
# in logs and figure out the extent of the problem
|
|
|
|
return "Unspecified"
|
2013-03-21 19:21:46 +01:00
|
|
|
|
2017-12-09 06:40:18 +01:00
|
|
|
def process_client(request: HttpRequest, user_profile: UserProfile,
|
|
|
|
*, is_browser_view: bool=False,
|
2018-05-11 01:39:17 +02:00
|
|
|
client_name: Optional[str]=None,
|
2018-12-11 20:09:11 +01:00
|
|
|
skip_update_user_activity: bool=False,
|
2018-05-11 01:39:17 +02:00
|
|
|
query: Optional[str]=None) -> None:
|
2016-05-12 22:49:36 +02:00
|
|
|
if client_name is None:
|
2020-03-08 21:12:38 +01:00
|
|
|
client_name = get_client_name(request)
|
|
|
|
|
|
|
|
# We could check for a browser's name being "Mozilla", but
|
|
|
|
# e.g. Opera and MobileSafari don't set that, and it seems
|
|
|
|
# more robust to just key off whether it was a browser view
|
|
|
|
if is_browser_view and not client_name.startswith("Zulip"):
|
|
|
|
# Avoid changing the client string for browsers, but let
|
|
|
|
# the Zulip desktop apps be themselves.
|
|
|
|
client_name = "website"
|
2014-01-08 17:52:36 +01:00
|
|
|
|
2014-01-08 17:36:54 +01:00
|
|
|
request.client = get_client(client_name)
|
2018-12-11 20:09:11 +01:00
|
|
|
if not skip_update_user_activity:
|
2017-11-03 22:44:59 +01:00
|
|
|
update_user_activity(request, user_profile, query)
|
2013-03-21 19:21:46 +01:00
|
|
|
|
2017-10-12 03:02:35 +02:00
|
|
|
class InvalidZulipServerError(JsonableError):
|
|
|
|
code = ErrorCode.INVALID_ZULIP_SERVER
|
|
|
|
data_fields = ['role']
|
|
|
|
|
2018-05-11 01:39:17 +02:00
|
|
|
def __init__(self, role: str) -> None:
|
|
|
|
self.role = role # type: str
|
2017-10-12 03:02:35 +02:00
|
|
|
|
|
|
|
@staticmethod
|
2018-05-11 01:39:17 +02:00
|
|
|
def msg_format() -> str:
|
2017-10-12 03:02:35 +02:00
|
|
|
return "Zulip server auth failure: {role} is not registered"
|
|
|
|
|
2018-04-26 06:36:34 +02:00
|
|
|
class InvalidZulipServerKeyError(InvalidZulipServerError):
|
2017-10-12 03:02:35 +02:00
|
|
|
@staticmethod
|
2018-05-11 01:39:17 +02:00
|
|
|
def msg_format() -> str:
|
2017-10-12 03:02:35 +02:00
|
|
|
return "Zulip server auth failure: key does not match role {role}"
|
|
|
|
|
2018-05-11 01:39:17 +02:00
|
|
|
def validate_api_key(request: HttpRequest, role: Optional[str],
|
|
|
|
api_key: str, is_webhook: bool=False,
|
|
|
|
client_name: Optional[str]=None) -> Union[UserProfile, RemoteZulipServer]:
|
2013-08-21 00:36:45 +02:00
|
|
|
# Remove whitespace to protect users from trivial errors.
|
2017-08-15 01:21:46 +02:00
|
|
|
api_key = api_key.strip()
|
|
|
|
if role is not None:
|
|
|
|
role = role.strip()
|
2013-08-21 00:36:45 +02:00
|
|
|
|
tests: Add uuid_get and uuid_post.
We want a clean codepath for the vast majority
of cases of using api_get/api_post, which now
uses email and which we'll soon convert to
accepting `user` as a parameter.
These apis that take two different types of
values for the same parameter make sweeps
like this kinda painful, and they're pretty
easy to avoid by extracting helpers to do
the actual common tasks. So, for example,
here I still keep a common method to
actually encode the credentials (since
the whole encode/decode business is an
annoying detail that you don't want to fix
in two places):
def encode_credentials(self, identifier: str, api_key: str) -> str:
"""
identifier: Can be an email or a remote server uuid.
"""
credentials = "%s:%s" % (identifier, api_key)
return 'Basic ' + base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
But then the rest of the code has two separate
codepaths.
And for the uuid functions, we no longer have
crufty references to realm. (In fairness, realm
will also go away when we introduce users.)
For the `is_remote_server` helper, I just inlined
it, since it's now only needed in one place, and the
name didn't make total sense anyway, plus it wasn't
a super robust check. In context, it's easier
just to use a comment now to say what we're doing:
# If `role` doesn't look like an email, it might be a uuid.
if settings.ZILENCER_ENABLED and role is not None and '@' not in role:
# do stuff
2020-03-10 12:34:25 +01:00
|
|
|
# If `role` doesn't look like an email, it might be a uuid.
|
|
|
|
if settings.ZILENCER_ENABLED and role is not None and '@' not in role:
|
2016-10-27 23:55:31 +02:00
|
|
|
try:
|
2017-08-15 00:41:04 +02:00
|
|
|
remote_server = get_remote_server_by_uuid(role)
|
2016-10-27 23:55:31 +02:00
|
|
|
except RemoteZulipServer.DoesNotExist:
|
2017-10-12 03:02:35 +02:00
|
|
|
raise InvalidZulipServerError(role)
|
2017-08-15 00:41:04 +02:00
|
|
|
if api_key != remote_server.api_key:
|
2017-10-12 03:02:35 +02:00
|
|
|
raise InvalidZulipServerKeyError(role)
|
2017-08-15 00:39:36 +02:00
|
|
|
|
2017-10-20 02:52:15 +02:00
|
|
|
if get_subdomain(request) != Realm.SUBDOMAIN_FOR_ROOT_DOMAIN:
|
2017-10-12 03:02:35 +02:00
|
|
|
raise JsonableError(_("Invalid subdomain for push notifications bouncer"))
|
2017-08-16 06:04:19 +02:00
|
|
|
request.user = remote_server
|
2017-08-15 00:59:19 +02:00
|
|
|
remote_server.rate_limits = ""
|
2018-12-11 20:09:11 +01:00
|
|
|
# Skip updating UserActivity, since remote_server isn't actually a UserProfile object.
|
|
|
|
process_client(request, remote_server, skip_update_user_activity=True)
|
2017-08-15 00:41:04 +02:00
|
|
|
return remote_server
|
2017-08-15 00:40:20 +02:00
|
|
|
|
2017-08-15 00:59:57 +02:00
|
|
|
user_profile = access_user_by_api_key(request, api_key, email=role)
|
|
|
|
if user_profile.is_incoming_webhook and not is_webhook:
|
2017-08-15 00:44:34 +02:00
|
|
|
raise JsonableError(_("This API is not available to incoming webhook bots."))
|
|
|
|
|
2017-08-15 00:59:19 +02:00
|
|
|
request.user = user_profile
|
2017-08-15 01:21:46 +02:00
|
|
|
process_client(request, user_profile, client_name=client_name)
|
2017-08-15 00:59:19 +02:00
|
|
|
|
2017-08-15 00:59:57 +02:00
|
|
|
return user_profile
|
2013-03-21 19:21:46 +01:00
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def validate_account_and_subdomain(request: HttpRequest, user_profile: UserProfile) -> None:
|
2017-08-15 00:28:39 +02:00
|
|
|
if user_profile.realm.deactivated:
|
2018-03-17 00:51:11 +01:00
|
|
|
raise JsonableError(_("This organization has been deactivated"))
|
2018-08-10 00:57:18 +02:00
|
|
|
if not user_profile.is_active:
|
2018-08-10 00:58:31 +02:00
|
|
|
raise JsonableError(_("Account is deactivated"))
|
2017-08-15 00:28:39 +02:00
|
|
|
|
dependencies: Remove WebSockets system for sending messages.
Zulip has had a small use of WebSockets (specifically, for the code
path of sending messages, via the webapp only) since ~2013. We
originally added this use of WebSockets in the hope that the latency
benefits of doing so would allow us to avoid implementing a markdown
local echo; they were not. Further, HTTP/2 may have eliminated the
latency difference we hoped to exploit by using WebSockets in any
case.
While we’d originally imagined using WebSockets for other endpoints,
there was never a good justification for moving more components to the
WebSockets system.
This WebSockets code path had a lot of downsides/complexity,
including:
* The messy hack involving constructing an emulated request object to
hook into doing Django requests.
* The `message_senders` queue processor system, which increases RAM
needs and must be provisioned independently from the rest of the
server).
* A duplicate check_send_receive_time Nagios test specific to
WebSockets.
* The requirement for users to have their firewalls/NATs allow
WebSocket connections, and a setting to disable them for networks
where WebSockets don’t work.
* Dependencies on the SockJS family of libraries, which has at times
been poorly maintained, and periodically throws random JavaScript
exceptions in our production environments without a deep enough
traceback to effectively investigate.
* A total of about 1600 lines of our code related to the feature.
* Increased load on the Tornado system, especially around a Zulip
server restart, and especially for large installations like
zulipchat.com, resulting in extra delay before messages can be sent
again.
As detailed in
https://github.com/zulip/zulip/pull/12862#issuecomment-536152397, it
appears that removing WebSockets moderately increases the time it
takes for the `send_message` API query to return from the server, but
does not significantly change the time between when a message is sent
and when it is received by clients. We don’t understand the reason
for that change (suggesting the possibility of a measurement error),
and even if it is a real change, we consider that potential small
latency regression to be acceptable.
If we later want WebSockets, we’ll likely want to just use Django
Channels.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-07-23 01:43:40 +02:00
|
|
|
# Either the subdomain matches, or we're accessing Tornado from
|
|
|
|
# and to localhost (aka spoofing a request as the user).
|
2017-10-20 02:53:24 +02:00
|
|
|
if (not user_matches_subdomain(get_subdomain(request), user_profile) and
|
2017-08-15 00:42:16 +02:00
|
|
|
not (settings.RUNNING_INSIDE_TORNADO and
|
|
|
|
request.META["SERVER_NAME"] == "127.0.0.1" and
|
|
|
|
request.META["REMOTE_ADDR"] == "127.0.0.1")):
|
2017-10-02 22:12:04 +02:00
|
|
|
logging.warning("User %s (%s) attempted to access API on wrong subdomain (%s)" % (
|
2018-12-07 00:05:57 +01:00
|
|
|
user_profile.delivery_email, user_profile.realm.subdomain, get_subdomain(request)))
|
2017-08-15 00:28:39 +02:00
|
|
|
raise JsonableError(_("Account is not associated with this subdomain"))
|
|
|
|
|
2018-05-11 01:39:17 +02:00
|
|
|
def access_user_by_api_key(request: HttpRequest, api_key: str, email: Optional[str]=None) -> UserProfile:
|
2019-12-16 08:12:39 +01:00
|
|
|
if not has_api_key_format(api_key):
|
|
|
|
raise InvalidAPIKeyFormatError()
|
|
|
|
|
2017-08-15 01:28:48 +02:00
|
|
|
try:
|
2017-08-25 07:43:38 +02:00
|
|
|
user_profile = get_user_profile_by_api_key(api_key)
|
2017-08-15 01:28:48 +02:00
|
|
|
except UserProfile.DoesNotExist:
|
2019-01-05 20:18:18 +01:00
|
|
|
raise InvalidAPIKeyError()
|
2018-12-07 00:05:57 +01:00
|
|
|
if email is not None and email.lower() != user_profile.delivery_email.lower():
|
2017-08-15 01:28:48 +02:00
|
|
|
# This covers the case that the API key is correct, but for a
|
|
|
|
# different user. We may end up wanting to relaxing this
|
|
|
|
# constraint or give a different error message in the future.
|
2019-01-05 20:18:18 +01:00
|
|
|
raise InvalidAPIKeyError()
|
2017-08-15 01:28:48 +02:00
|
|
|
|
|
|
|
validate_account_and_subdomain(request, user_profile)
|
|
|
|
|
2017-08-15 00:28:39 +02:00
|
|
|
return user_profile
|
|
|
|
|
2019-06-06 05:55:09 +02:00
|
|
|
def log_exception_to_webhook_logger(
|
|
|
|
request: HttpRequest, user_profile: UserProfile,
|
|
|
|
request_body: Optional[str]=None,
|
|
|
|
unexpected_event: Optional[bool]=False
|
|
|
|
) -> None:
|
2018-02-28 03:13:15 +01:00
|
|
|
if request_body is not None:
|
|
|
|
payload = request_body
|
|
|
|
else:
|
|
|
|
payload = request.body
|
|
|
|
|
2018-02-25 01:54:29 +01:00
|
|
|
if request.content_type == 'application/json':
|
|
|
|
try:
|
2018-02-28 03:13:15 +01:00
|
|
|
payload = ujson.dumps(ujson.loads(payload), indent=4)
|
2018-02-25 01:54:29 +01:00
|
|
|
except ValueError:
|
2018-02-28 03:13:15 +01:00
|
|
|
request_body = str(payload)
|
2018-02-25 01:54:29 +01:00
|
|
|
else:
|
2018-02-28 03:13:15 +01:00
|
|
|
request_body = str(payload)
|
|
|
|
|
2018-03-29 21:04:05 +02:00
|
|
|
custom_header_template = "{header}: {value}\n"
|
|
|
|
|
2018-10-25 00:26:27 +02:00
|
|
|
header_text = ""
|
2018-03-29 21:04:05 +02:00
|
|
|
for header in request.META.keys():
|
|
|
|
if header.lower().startswith('http_x'):
|
2018-10-25 00:26:27 +02:00
|
|
|
header_text += custom_header_template.format(
|
2018-03-29 21:04:05 +02:00
|
|
|
header=header, value=request.META[header])
|
|
|
|
|
2018-10-25 00:26:27 +02:00
|
|
|
header_message = header_text if header_text else None
|
2018-03-29 21:04:05 +02:00
|
|
|
|
2018-02-25 01:54:29 +01:00
|
|
|
message = """
|
|
|
|
user: {email} ({realm})
|
|
|
|
client: {client_name}
|
|
|
|
URL: {path_info}
|
|
|
|
content_type: {content_type}
|
2018-03-29 21:04:05 +02:00
|
|
|
custom_http_headers:
|
|
|
|
{custom_headers}
|
2018-02-25 01:54:29 +01:00
|
|
|
body:
|
|
|
|
|
|
|
|
{body}
|
|
|
|
""".format(
|
2018-12-07 00:05:57 +01:00
|
|
|
email=user_profile.delivery_email,
|
2018-02-25 01:54:29 +01:00
|
|
|
realm=user_profile.realm.string_id,
|
|
|
|
client_name=request.client.name,
|
2018-02-28 03:13:15 +01:00
|
|
|
body=payload,
|
2018-02-25 01:54:29 +01:00
|
|
|
path_info=request.META.get('PATH_INFO', None),
|
|
|
|
content_type=request.content_type,
|
2018-03-29 21:04:05 +02:00
|
|
|
custom_headers=header_message,
|
2018-02-25 01:54:29 +01:00
|
|
|
)
|
|
|
|
message = message.strip(' ')
|
2019-06-06 05:55:09 +02:00
|
|
|
|
|
|
|
if unexpected_event:
|
|
|
|
webhook_unexpected_events_logger.exception(message)
|
|
|
|
else:
|
|
|
|
webhook_logger.exception(message)
|
2018-02-25 01:54:29 +01:00
|
|
|
|
2018-03-16 23:37:32 +01:00
|
|
|
def full_webhook_client_name(raw_client_name: Optional[str]=None) -> Optional[str]:
|
|
|
|
if raw_client_name is None:
|
|
|
|
return None
|
|
|
|
return "Zulip{}Webhook".format(raw_client_name)
|
|
|
|
|
2013-10-03 01:12:57 +02:00
|
|
|
# Use this for webhook views that don't get an email passed in.
|
2018-11-15 05:31:34 +01:00
|
|
|
def api_key_only_webhook_view(
|
|
|
|
webhook_client_name: str,
|
2018-11-20 18:52:25 +01:00
|
|
|
notify_bot_owner_on_invalid_json: Optional[bool]=True
|
2018-11-15 05:31:34 +01:00
|
|
|
) -> Callable[[ViewFuncT], ViewFuncT]:
|
2017-10-28 05:50:09 +02:00
|
|
|
# TODO The typing here could be improved by using the Extended Callable types:
|
|
|
|
# https://mypy.readthedocs.io/en/latest/kinds_of_types.html#extended-callable-types
|
2018-11-15 05:31:34 +01:00
|
|
|
|
2018-03-13 23:03:41 +01:00
|
|
|
def _wrapped_view_func(view_func: ViewFuncT) -> ViewFuncT:
|
2016-05-12 22:49:36 +02:00
|
|
|
@csrf_exempt
|
|
|
|
@has_request_variables
|
|
|
|
@wraps(view_func)
|
2018-05-11 01:39:17 +02:00
|
|
|
def _wrapped_func_arguments(request: HttpRequest, api_key: str=REQ(),
|
2017-12-09 06:40:18 +01:00
|
|
|
*args: Any, **kwargs: Any) -> HttpResponse:
|
2017-08-15 01:21:46 +02:00
|
|
|
user_profile = validate_api_key(request, None, api_key, is_webhook=True,
|
2018-03-16 23:37:32 +01:00
|
|
|
client_name=full_webhook_client_name(webhook_client_name))
|
2016-05-12 22:49:36 +02:00
|
|
|
|
|
|
|
if settings.RATE_LIMITING:
|
2019-08-03 20:39:49 +02:00
|
|
|
rate_limit_user(request, user_profile, domain='api_by_user')
|
2017-05-12 05:21:09 +02:00
|
|
|
try:
|
|
|
|
return view_func(request, user_profile, *args, **kwargs)
|
2017-07-19 05:08:51 +02:00
|
|
|
except Exception as err:
|
2018-12-06 00:12:19 +01:00
|
|
|
if isinstance(err, InvalidJSONError) and notify_bot_owner_on_invalid_json:
|
|
|
|
# NOTE: importing this at the top of file leads to a
|
|
|
|
# cyclic import; correct fix is probably to move
|
|
|
|
# notify_bot_owner_about_invalid_json to a smaller file.
|
|
|
|
from zerver.lib.webhooks.common import notify_bot_owner_about_invalid_json
|
|
|
|
notify_bot_owner_about_invalid_json(user_profile, webhook_client_name)
|
|
|
|
else:
|
2019-06-06 05:55:09 +02:00
|
|
|
kwargs = {'request': request, 'user_profile': user_profile}
|
|
|
|
if isinstance(err, UnexpectedWebhookEventType):
|
|
|
|
kwargs['unexpected_event'] = True
|
|
|
|
|
|
|
|
log_exception_to_webhook_logger(**kwargs)
|
2017-07-19 05:08:51 +02:00
|
|
|
raise err
|
2017-05-12 05:21:09 +02:00
|
|
|
|
2016-05-12 22:49:36 +02:00
|
|
|
return _wrapped_func_arguments
|
2013-10-03 01:12:57 +02:00
|
|
|
return _wrapped_view_func
|
|
|
|
|
2016-04-21 23:41:28 +02:00
|
|
|
# From Django 1.8, modified to leave off ?next=/
|
2018-05-11 01:39:17 +02:00
|
|
|
def redirect_to_login(next: str, login_url: Optional[str]=None,
|
|
|
|
redirect_field_name: str=REDIRECT_FIELD_NAME) -> HttpResponseRedirect:
|
2016-04-21 23:48:34 +02:00
|
|
|
"""
|
|
|
|
Redirects the user to the login page, passing the given 'next' page
|
|
|
|
"""
|
|
|
|
resolved_url = resolve_url(login_url or settings.LOGIN_URL)
|
|
|
|
|
|
|
|
login_url_parts = list(urllib.parse.urlparse(resolved_url))
|
|
|
|
if redirect_field_name:
|
|
|
|
querystring = QueryDict(login_url_parts[4], mutable=True)
|
|
|
|
querystring[redirect_field_name] = next
|
2016-04-21 23:41:28 +02:00
|
|
|
# Don't add ?next=/, to keep our URLs clean
|
|
|
|
if next != '/':
|
|
|
|
login_url_parts[4] = querystring.urlencode(safe='/')
|
2016-04-21 23:48:34 +02:00
|
|
|
|
|
|
|
return HttpResponseRedirect(urllib.parse.urlunparse(login_url_parts))
|
|
|
|
|
|
|
|
# From Django 1.8
|
2018-05-11 01:39:17 +02:00
|
|
|
def user_passes_test(test_func: Callable[[HttpResponse], bool], login_url: Optional[str]=None,
|
|
|
|
redirect_field_name: str=REDIRECT_FIELD_NAME) -> Callable[[ViewFuncT], ViewFuncT]:
|
2016-04-21 23:48:34 +02:00
|
|
|
"""
|
|
|
|
Decorator for views that checks that the user passes the given test,
|
|
|
|
redirecting to the log-in page if necessary. The test should be a callable
|
|
|
|
that takes the user object and returns True if the user passes.
|
|
|
|
"""
|
2018-03-13 23:03:41 +01:00
|
|
|
def decorator(view_func: ViewFuncT) -> ViewFuncT:
|
2016-04-21 23:48:34 +02:00
|
|
|
@wraps(view_func, assigned=available_attrs(view_func))
|
2017-11-27 07:33:05 +01:00
|
|
|
def _wrapped_view(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
|
2016-07-19 14:22:13 +02:00
|
|
|
if test_func(request):
|
2016-04-21 23:48:34 +02:00
|
|
|
return view_func(request, *args, **kwargs)
|
|
|
|
path = request.build_absolute_uri()
|
|
|
|
resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
|
|
|
|
# If the login url is the same scheme and net location then just
|
|
|
|
# use the path as the "next" url.
|
|
|
|
login_scheme, login_netloc = urllib.parse.urlparse(resolved_login_url)[:2]
|
|
|
|
current_scheme, current_netloc = urllib.parse.urlparse(path)[:2]
|
|
|
|
if ((not login_scheme or login_scheme == current_scheme) and
|
|
|
|
(not login_netloc or login_netloc == current_netloc)):
|
|
|
|
path = request.get_full_path()
|
|
|
|
return redirect_to_login(
|
|
|
|
path, resolved_login_url, redirect_field_name)
|
2020-04-22 04:13:37 +02:00
|
|
|
return _wrapped_view # type: ignore[return-value] # https://github.com/python/mypy/issues/1927
|
2016-04-21 23:48:34 +02:00
|
|
|
return decorator
|
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def logged_in_and_active(request: HttpRequest) -> bool:
|
2017-05-18 11:42:19 +02:00
|
|
|
if not request.user.is_authenticated:
|
2016-04-22 00:56:39 +02:00
|
|
|
return False
|
2016-07-19 14:22:13 +02:00
|
|
|
if not request.user.is_active:
|
2016-04-22 00:56:39 +02:00
|
|
|
return False
|
2016-07-19 14:22:13 +02:00
|
|
|
if request.user.realm.deactivated:
|
2016-04-22 00:56:39 +02:00
|
|
|
return False
|
2017-10-20 02:53:24 +02:00
|
|
|
return user_matches_subdomain(get_subdomain(request), request.user)
|
2016-04-22 00:56:39 +02:00
|
|
|
|
2017-07-12 09:50:19 +02:00
|
|
|
def do_two_factor_login(request: HttpRequest, user_profile: UserProfile) -> None:
|
|
|
|
device = default_device(user_profile)
|
|
|
|
if device:
|
|
|
|
django_otp.login(request, device)
|
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def do_login(request: HttpRequest, user_profile: UserProfile) -> None:
|
2017-08-25 01:11:30 +02:00
|
|
|
"""Creates a session, logging in the user, using the Django method,
|
|
|
|
and also adds helpful data needed by our server logs.
|
|
|
|
"""
|
|
|
|
django_login(request, user_profile)
|
2020-03-09 11:39:20 +01:00
|
|
|
request._requestor_for_logs = user_profile.format_requestor_for_logs()
|
2017-08-25 01:11:30 +02:00
|
|
|
process_client(request, user_profile, is_browser_view=True)
|
2017-07-12 09:50:19 +02:00
|
|
|
if settings.TWO_FACTOR_AUTHENTICATION_ENABLED:
|
|
|
|
# Login with two factor authentication as well.
|
|
|
|
do_two_factor_login(request, user_profile)
|
2017-08-25 01:11:30 +02:00
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def log_view_func(view_func: ViewFuncT) -> ViewFuncT:
|
2017-11-03 22:26:31 +01:00
|
|
|
@wraps(view_func)
|
2017-11-27 07:33:05 +01:00
|
|
|
def _wrapped_view_func(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
|
2017-11-03 22:26:31 +01:00
|
|
|
request._query = view_func.__name__
|
|
|
|
return view_func(request, *args, **kwargs)
|
2020-04-22 04:13:37 +02:00
|
|
|
return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927
|
2017-11-03 22:26:31 +01:00
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def add_logging_data(view_func: ViewFuncT) -> ViewFuncT:
|
2017-02-20 20:55:18 +01:00
|
|
|
@wraps(view_func)
|
2017-11-27 07:33:05 +01:00
|
|
|
def _wrapped_view_func(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
|
2017-11-03 22:44:59 +01:00
|
|
|
process_client(request, request.user, is_browser_view=True,
|
|
|
|
query=view_func.__name__)
|
2017-03-26 07:00:59 +02:00
|
|
|
return rate_limit()(view_func)(request, *args, **kwargs)
|
2020-04-22 04:13:37 +02:00
|
|
|
return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927
|
2017-04-15 20:51:51 +02:00
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def human_users_only(view_func: ViewFuncT) -> ViewFuncT:
|
2017-04-15 20:51:51 +02:00
|
|
|
@wraps(view_func)
|
2017-11-27 07:33:05 +01:00
|
|
|
def _wrapped_view_func(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
|
2017-04-15 20:51:51 +02:00
|
|
|
if request.user.is_bot:
|
|
|
|
return json_error(_("This endpoint does not accept bot requests."))
|
|
|
|
return view_func(request, *args, **kwargs)
|
2020-04-22 04:13:37 +02:00
|
|
|
return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927
|
2017-02-20 20:55:18 +01:00
|
|
|
|
2016-04-21 23:48:34 +02:00
|
|
|
# Based on Django 1.8's @login_required
|
2017-12-09 06:40:18 +01:00
|
|
|
def zulip_login_required(
|
2018-03-14 20:56:20 +01:00
|
|
|
function: Optional[ViewFuncT]=None,
|
2018-05-11 01:39:17 +02:00
|
|
|
redirect_field_name: str=REDIRECT_FIELD_NAME,
|
|
|
|
login_url: str=settings.HOME_NOT_LOGGED_IN,
|
2018-03-14 20:56:20 +01:00
|
|
|
) -> Union[Callable[[ViewFuncT], ViewFuncT], ViewFuncT]:
|
2016-04-21 23:48:34 +02:00
|
|
|
actual_decorator = user_passes_test(
|
2016-04-22 00:56:39 +02:00
|
|
|
logged_in_and_active,
|
2016-04-21 23:48:34 +02:00
|
|
|
login_url=login_url,
|
|
|
|
redirect_field_name=redirect_field_name
|
|
|
|
)
|
2017-07-12 10:16:02 +02:00
|
|
|
|
|
|
|
otp_required_decorator = zulip_otp_required(
|
|
|
|
redirect_field_name=redirect_field_name,
|
|
|
|
login_url=login_url
|
|
|
|
)
|
|
|
|
|
2016-04-21 23:48:34 +02:00
|
|
|
if function:
|
2017-02-20 20:55:18 +01:00
|
|
|
# Add necessary logging data via add_logging_data
|
2017-07-12 10:16:02 +02:00
|
|
|
return actual_decorator(zulip_otp_required(add_logging_data(function)))
|
|
|
|
return actual_decorator(otp_required_decorator) # nocoverage # We don't use this without a function
|
2016-04-21 23:48:34 +02:00
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def require_server_admin(view_func: ViewFuncT) -> ViewFuncT:
|
2016-04-21 23:48:34 +02:00
|
|
|
@zulip_login_required
|
2013-11-01 18:43:38 +01:00
|
|
|
@wraps(view_func)
|
2017-11-27 07:33:05 +01:00
|
|
|
def _wrapped_view_func(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
|
2016-12-14 06:02:50 +01:00
|
|
|
if not request.user.is_staff:
|
2013-10-22 15:39:39 +02:00
|
|
|
return HttpResponseRedirect(settings.HOME_NOT_LOGGED_IN)
|
2013-10-22 21:03:34 +02:00
|
|
|
|
2017-02-20 20:55:18 +01:00
|
|
|
return add_logging_data(view_func)(request, *args, **kwargs)
|
2020-04-22 04:13:37 +02:00
|
|
|
return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927
|
2013-10-03 01:12:57 +02:00
|
|
|
|
2018-04-15 18:29:06 +02:00
|
|
|
def require_server_admin_api(view_func: ViewFuncT) -> ViewFuncT:
|
|
|
|
@zulip_login_required
|
|
|
|
@wraps(view_func)
|
2018-04-15 18:43:48 +02:00
|
|
|
def _wrapped_view_func(request: HttpRequest, user_profile: UserProfile, *args: Any,
|
|
|
|
**kwargs: Any) -> HttpResponse:
|
2018-04-15 18:29:06 +02:00
|
|
|
if not user_profile.is_staff:
|
|
|
|
raise JsonableError(_("Must be an server administrator"))
|
|
|
|
return view_func(request, user_profile, *args, **kwargs)
|
2020-04-22 04:13:37 +02:00
|
|
|
return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927
|
2018-04-15 18:29:06 +02:00
|
|
|
|
2018-05-04 19:14:29 +02:00
|
|
|
def require_non_guest_user(view_func: ViewFuncT) -> ViewFuncT:
|
|
|
|
@wraps(view_func)
|
|
|
|
def _wrapped_view_func(request: HttpRequest, user_profile: UserProfile, *args: Any,
|
|
|
|
**kwargs: Any) -> HttpResponse:
|
|
|
|
if user_profile.is_guest:
|
|
|
|
raise JsonableError(_("Not allowed for guest users"))
|
|
|
|
return view_func(request, user_profile, *args, **kwargs)
|
2020-04-22 04:13:37 +02:00
|
|
|
return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927
|
2018-05-04 19:14:29 +02:00
|
|
|
|
2019-06-18 16:43:22 +02:00
|
|
|
def require_member_or_admin(view_func: ViewFuncT) -> ViewFuncT:
|
2018-05-04 19:14:29 +02:00
|
|
|
@wraps(view_func)
|
|
|
|
def _wrapped_view_func(request: HttpRequest, user_profile: UserProfile, *args: Any,
|
|
|
|
**kwargs: Any) -> HttpResponse:
|
|
|
|
if user_profile.is_guest:
|
|
|
|
raise JsonableError(_("Not allowed for guest users"))
|
|
|
|
if user_profile.is_bot:
|
|
|
|
return json_error(_("This endpoint does not accept bot requests."))
|
|
|
|
return view_func(request, user_profile, *args, **kwargs)
|
2020-04-22 04:13:37 +02:00
|
|
|
return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927
|
2019-11-02 17:58:55 +01:00
|
|
|
|
2019-11-16 15:56:40 +01:00
|
|
|
def require_user_group_edit_permission(view_func: ViewFuncT) -> ViewFuncT:
|
|
|
|
@require_member_or_admin
|
2019-11-02 17:58:55 +01:00
|
|
|
@wraps(view_func)
|
|
|
|
def _wrapped_view_func(request: HttpRequest, user_profile: UserProfile,
|
|
|
|
*args: Any, **kwargs: Any) -> HttpResponse:
|
|
|
|
realm = user_profile.realm
|
|
|
|
if realm.user_group_edit_policy != Realm.USER_GROUP_EDIT_POLICY_MEMBERS and \
|
|
|
|
not user_profile.is_realm_admin:
|
2019-11-16 15:53:56 +01:00
|
|
|
raise OrganizationAdministratorRequired()
|
2019-11-02 17:58:55 +01:00
|
|
|
return view_func(request, user_profile, *args, **kwargs)
|
2020-04-22 04:13:37 +02:00
|
|
|
return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927
|
2018-05-04 19:14:29 +02:00
|
|
|
|
2018-04-13 19:04:39 +02:00
|
|
|
# This API endpoint is used only for the mobile apps. It is part of a
|
|
|
|
# workaround for the fact that React Native doesn't support setting
|
|
|
|
# HTTP basic authentication headers.
|
2018-12-11 20:46:52 +01:00
|
|
|
def authenticated_uploads_api_view(skip_rate_limiting: bool=False) -> Callable[[ViewFuncT], ViewFuncT]:
|
2018-04-13 19:04:39 +02:00
|
|
|
def _wrapped_view_func(view_func: ViewFuncT) -> ViewFuncT:
|
|
|
|
@csrf_exempt
|
|
|
|
@has_request_variables
|
|
|
|
@wraps(view_func)
|
|
|
|
def _wrapped_func_arguments(request: HttpRequest,
|
|
|
|
api_key: str=REQ(),
|
|
|
|
*args: Any, **kwargs: Any) -> HttpResponse:
|
|
|
|
user_profile = validate_api_key(request, None, api_key, False)
|
2018-12-11 20:46:52 +01:00
|
|
|
if not skip_rate_limiting:
|
|
|
|
limited_func = rate_limit()(view_func)
|
|
|
|
else:
|
|
|
|
limited_func = view_func
|
2018-04-13 19:04:39 +02:00
|
|
|
return limited_func(request, user_profile, *args, **kwargs)
|
|
|
|
return _wrapped_func_arguments
|
|
|
|
return _wrapped_view_func
|
|
|
|
|
2013-08-29 20:47:04 +02:00
|
|
|
# A more REST-y authentication decorator, using, in particular, HTTP Basic
|
|
|
|
# authentication.
|
2018-03-16 23:37:32 +01:00
|
|
|
#
|
|
|
|
# If webhook_client_name is specific, the request is a webhook view
|
|
|
|
# with that string as the basis for the client string.
|
2018-10-25 00:26:27 +02:00
|
|
|
def authenticated_rest_api_view(*, webhook_client_name: Optional[str]=None,
|
2018-12-11 20:46:52 +01:00
|
|
|
is_webhook: bool=False,
|
|
|
|
skip_rate_limiting: bool=False) -> Callable[[ViewFuncT], ViewFuncT]:
|
2018-03-13 23:03:41 +01:00
|
|
|
def _wrapped_view_func(view_func: ViewFuncT) -> ViewFuncT:
|
2016-05-18 20:35:35 +02:00
|
|
|
@csrf_exempt
|
|
|
|
@wraps(view_func)
|
2017-11-27 07:33:05 +01:00
|
|
|
def _wrapped_func_arguments(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
|
2016-05-18 20:35:35 +02:00
|
|
|
# First try block attempts to get the credentials we need to do authentication
|
|
|
|
try:
|
|
|
|
# Grab the base64-encoded authentication string, decode it, and split it into
|
|
|
|
# the email and API key
|
2016-07-07 21:50:08 +02:00
|
|
|
auth_type, credentials = request.META['HTTP_AUTHORIZATION'].split()
|
2016-05-18 20:35:35 +02:00
|
|
|
# case insensitive per RFC 1945
|
|
|
|
if auth_type.lower() != "basic":
|
2017-03-08 18:04:59 +01:00
|
|
|
return json_error(_("This endpoint requires HTTP basic authentication."))
|
Don't use force_bytes() in decorator.py.
In python3 base64.b64decode() can take an ASCII string, and any
legit data will be ASCII. If you pass in non-ASCII data, the
function will properly throw a ValueError (verified in python3 shell).
>>> s = '안녕하세요'
>>> import base64
>>> base64.b64decode(s)
Traceback (most recent call last):
File "/srv/zulip-py3-venv/lib/python3.4/base64.py", line 37, in _bytes_from_decode_data
return s.encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/srv/zulip-py3-venv/lib/python3.4/base64.py", line 83, in b64decode
s = _bytes_from_decode_data(s)
File "/srv/zulip-py3-venv/lib/python3.4/base64.py", line 39, in _bytes_from_decode_data
raise ValueError('string argument should contain only ASCII characters')
ValueError: string argument should contain only ASCII characters
2017-11-04 16:53:23 +01:00
|
|
|
role, api_key = base64.b64decode(credentials).decode('utf-8').split(":")
|
2016-05-18 20:35:35 +02:00
|
|
|
except ValueError:
|
2017-01-29 21:48:10 +01:00
|
|
|
return json_unauthorized(_("Invalid authorization header for basic auth"))
|
2016-05-18 20:35:35 +02:00
|
|
|
except KeyError:
|
2018-04-26 07:14:21 +02:00
|
|
|
return json_unauthorized(_("Missing authorization header for basic auth"))
|
2016-05-18 20:35:35 +02:00
|
|
|
|
|
|
|
# Now we try to do authentication or die
|
|
|
|
try:
|
2016-10-27 23:55:31 +02:00
|
|
|
# profile is a Union[UserProfile, RemoteZulipServer]
|
2018-03-16 23:37:32 +01:00
|
|
|
profile = validate_api_key(request, role, api_key,
|
|
|
|
is_webhook=is_webhook or webhook_client_name is not None,
|
|
|
|
client_name=full_webhook_client_name(webhook_client_name))
|
2016-05-18 20:35:35 +02:00
|
|
|
except JsonableError as e:
|
2017-07-20 00:22:36 +02:00
|
|
|
return json_unauthorized(e.msg)
|
2018-03-27 04:34:43 +02:00
|
|
|
try:
|
2018-12-11 20:46:52 +01:00
|
|
|
if not skip_rate_limiting:
|
|
|
|
# Apply rate limiting
|
|
|
|
target_view_func = rate_limit()(view_func)
|
|
|
|
else:
|
|
|
|
target_view_func = view_func
|
|
|
|
return target_view_func(request, profile, *args, **kwargs)
|
2018-03-27 04:34:43 +02:00
|
|
|
except Exception as err:
|
|
|
|
if is_webhook or webhook_client_name is not None:
|
|
|
|
request_body = request.POST.get('payload')
|
|
|
|
if request_body is not None:
|
2019-06-06 05:55:09 +02:00
|
|
|
kwargs = {
|
|
|
|
'request_body': request_body,
|
|
|
|
'request': request,
|
|
|
|
'user_profile': profile,
|
|
|
|
}
|
|
|
|
if isinstance(err, UnexpectedWebhookEventType):
|
|
|
|
kwargs['unexpected_event'] = True
|
|
|
|
|
|
|
|
log_exception_to_webhook_logger(**kwargs)
|
|
|
|
|
2018-03-27 04:34:43 +02:00
|
|
|
raise err
|
2016-05-18 20:35:35 +02:00
|
|
|
return _wrapped_func_arguments
|
2013-03-21 20:15:27 +01:00
|
|
|
return _wrapped_view_func
|
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def process_as_post(view_func: ViewFuncT) -> ViewFuncT:
|
2013-03-21 20:18:44 +01:00
|
|
|
@wraps(view_func)
|
2017-11-27 07:33:05 +01:00
|
|
|
def _wrapped_view_func(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
|
2013-03-21 20:18:44 +01:00
|
|
|
# Adapted from django/http/__init__.py.
|
|
|
|
# So by default Django doesn't populate request.POST for anything besides
|
2013-04-03 21:44:12 +02:00
|
|
|
# POST requests. We want this dict populated for PATCH/PUT, so we have to
|
2013-03-21 20:18:44 +01:00
|
|
|
# do it ourselves.
|
|
|
|
#
|
|
|
|
# This will not be required in the future, a bug will be filed against
|
|
|
|
# Django upstream.
|
2013-04-03 22:01:58 +02:00
|
|
|
|
|
|
|
if not request.POST:
|
|
|
|
# Only take action if POST is empty.
|
|
|
|
if request.META.get('CONTENT_TYPE', '').startswith('multipart'):
|
2013-08-01 19:33:30 +02:00
|
|
|
# Note that request._files is just the private attribute that backs the
|
|
|
|
# FILES property, so we are essentially setting request.FILES here. (In
|
|
|
|
# Django 1.5 FILES was still a read-only property.)
|
2016-12-03 00:04:17 +01:00
|
|
|
request.POST, request._files = MultiPartParser(
|
|
|
|
request.META,
|
|
|
|
BytesIO(request.body),
|
|
|
|
request.upload_handlers,
|
|
|
|
request.encoding
|
|
|
|
).parse()
|
2013-04-03 22:01:58 +02:00
|
|
|
else:
|
|
|
|
request.POST = QueryDict(request.body, encoding=request.encoding)
|
2013-03-21 20:18:44 +01:00
|
|
|
|
|
|
|
return view_func(request, *args, **kwargs)
|
|
|
|
|
2020-04-22 04:13:37 +02:00
|
|
|
return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927
|
2013-03-21 20:18:44 +01:00
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def authenticate_log_and_execute_json(request: HttpRequest,
|
2018-03-13 17:51:56 +01:00
|
|
|
view_func: ViewFuncT,
|
2018-12-11 20:46:52 +01:00
|
|
|
*args: Any, skip_rate_limiting: bool = False,
|
2018-12-17 00:10:20 +01:00
|
|
|
allow_unauthenticated: bool=False,
|
2018-12-11 20:46:52 +01:00
|
|
|
**kwargs: Any) -> HttpResponse:
|
2018-12-17 00:10:20 +01:00
|
|
|
if not skip_rate_limiting:
|
|
|
|
limited_view_func = rate_limit()(view_func)
|
|
|
|
else:
|
|
|
|
limited_view_func = view_func
|
|
|
|
|
2017-05-18 11:42:19 +02:00
|
|
|
if not request.user.is_authenticated:
|
2018-12-17 00:10:20 +01:00
|
|
|
if not allow_unauthenticated:
|
2019-09-14 00:58:02 +02:00
|
|
|
return json_unauthorized()
|
2018-12-17 00:10:20 +01:00
|
|
|
|
|
|
|
process_client(request, request.user, is_browser_view=True,
|
|
|
|
skip_update_user_activity=True,
|
|
|
|
query=view_func.__name__)
|
|
|
|
return limited_view_func(request, request.user, *args, **kwargs)
|
|
|
|
|
2013-03-29 17:39:53 +01:00
|
|
|
user_profile = request.user
|
2017-08-15 01:28:48 +02:00
|
|
|
validate_account_and_subdomain(request, user_profile)
|
|
|
|
|
2016-05-19 23:44:58 +02:00
|
|
|
if user_profile.is_incoming_webhook:
|
|
|
|
raise JsonableError(_("Webhook bots can only access webhooks"))
|
2016-08-14 04:16:39 +02:00
|
|
|
|
2017-11-03 22:58:33 +01:00
|
|
|
process_client(request, user_profile, is_browser_view=True,
|
|
|
|
query=view_func.__name__)
|
2018-12-17 00:10:20 +01:00
|
|
|
return limited_view_func(request, user_profile, *args, **kwargs)
|
2012-12-02 20:51:51 +01:00
|
|
|
|
2012-11-06 20:27:55 +01:00
|
|
|
# Checks if the request is a POST request and that the user is logged
|
|
|
|
# in. If not, return an error (the @login_required behavior of
|
|
|
|
# redirecting to a login page doesn't make sense for json views)
|
2017-11-27 07:33:05 +01:00
|
|
|
def authenticated_json_post_view(view_func: ViewFuncT) -> ViewFuncT:
|
2012-11-06 20:27:55 +01:00
|
|
|
@require_post
|
2012-11-28 21:15:50 +01:00
|
|
|
@has_request_variables
|
2012-11-06 20:27:55 +01:00
|
|
|
@wraps(view_func)
|
2017-12-09 06:40:18 +01:00
|
|
|
def _wrapped_view_func(request: HttpRequest,
|
|
|
|
*args: Any, **kwargs: Any) -> HttpResponse:
|
2013-06-27 20:21:21 +02:00
|
|
|
return authenticate_log_and_execute_json(request, view_func, *args, **kwargs)
|
2020-04-22 04:13:37 +02:00
|
|
|
return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927
|
2012-12-02 20:51:51 +01:00
|
|
|
|
2018-12-17 00:10:20 +01:00
|
|
|
def authenticated_json_view(view_func: ViewFuncT, skip_rate_limiting: bool=False,
|
|
|
|
allow_unauthenticated: bool=False) -> ViewFuncT:
|
2012-12-02 20:51:51 +01:00
|
|
|
@wraps(view_func)
|
2017-12-09 06:40:18 +01:00
|
|
|
def _wrapped_view_func(request: HttpRequest,
|
|
|
|
*args: Any, **kwargs: Any) -> HttpResponse:
|
2018-12-11 20:46:52 +01:00
|
|
|
kwargs["skip_rate_limiting"] = skip_rate_limiting
|
2018-12-17 00:10:20 +01:00
|
|
|
kwargs["allow_unauthenticated"] = allow_unauthenticated
|
2013-06-27 20:21:21 +02:00
|
|
|
return authenticate_log_and_execute_json(request, view_func, *args, **kwargs)
|
2020-04-22 04:13:37 +02:00
|
|
|
return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927
|
2012-11-01 23:21:12 +01:00
|
|
|
|
2018-05-11 01:39:17 +02:00
|
|
|
def is_local_addr(addr: str) -> bool:
|
2016-07-09 20:37:09 +02:00
|
|
|
return addr in ('127.0.0.1', '::1')
|
|
|
|
|
2012-11-28 05:37:13 +01:00
|
|
|
# These views are used by the main Django server to notify the Tornado server
|
|
|
|
# of events. We protect them from the outside world by checking a shared
|
|
|
|
# secret, and also the originating IP (for now).
|
2017-11-27 07:33:05 +01:00
|
|
|
def authenticate_notify(request: HttpRequest) -> bool:
|
2017-01-24 05:50:04 +01:00
|
|
|
return (is_local_addr(request.META['REMOTE_ADDR']) and
|
|
|
|
request.POST.get('secret') == settings.SHARED_SECRET)
|
2012-11-28 05:37:13 +01:00
|
|
|
|
2017-11-27 07:33:05 +01:00
|
|
|
def client_is_exempt_from_rate_limiting(request: HttpRequest) -> bool:
|
2016-07-09 08:08:42 +02:00
|
|
|
|
|
|
|
# Don't rate limit requests from Django that come from our own servers,
|
|
|
|
# and don't rate-limit dev instances
|
2017-01-24 05:50:04 +01:00
|
|
|
return ((request.client and request.client.name.lower() == 'internal') and
|
|
|
|
(is_local_addr(request.META['REMOTE_ADDR']) or
|
|
|
|
settings.DEBUG_RATE_LIMITING))
|
2016-07-09 08:08:42 +02:00
|
|
|
|
2018-03-13 23:03:41 +01:00
|
|
|
def internal_notify_view(is_tornado_view: bool) -> Callable[[ViewFuncT], ViewFuncT]:
|
2017-10-28 05:52:10 +02:00
|
|
|
# The typing here could be improved by using the Extended Callable types:
|
|
|
|
# https://mypy.readthedocs.io/en/latest/kinds_of_types.html#extended-callable-types
|
2017-04-18 18:56:19 +02:00
|
|
|
"""Used for situations where something running on the Zulip server
|
|
|
|
needs to make a request to the (other) Django/Tornado processes running on
|
|
|
|
the server."""
|
2018-03-13 23:03:41 +01:00
|
|
|
def _wrapped_view_func(view_func: ViewFuncT) -> ViewFuncT:
|
2017-04-18 18:56:19 +02:00
|
|
|
@csrf_exempt
|
|
|
|
@require_post
|
|
|
|
@wraps(view_func)
|
2017-11-27 07:33:05 +01:00
|
|
|
def _wrapped_func_arguments(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
|
2017-04-18 18:56:19 +02:00
|
|
|
if not authenticate_notify(request):
|
|
|
|
return json_error(_('Access denied'), status=403)
|
|
|
|
is_tornado_request = hasattr(request, '_tornado_handler')
|
|
|
|
# These next 2 are not security checks; they are internal
|
|
|
|
# assertions to help us find bugs.
|
|
|
|
if is_tornado_view and not is_tornado_request:
|
|
|
|
raise RuntimeError('Tornado notify view called with no Tornado handler')
|
|
|
|
if not is_tornado_view and is_tornado_request:
|
|
|
|
raise RuntimeError('Django notify view called with Tornado handler')
|
2020-03-09 11:39:20 +01:00
|
|
|
request._requestor_for_logs = "internal"
|
2017-04-18 18:56:19 +02:00
|
|
|
return view_func(request, *args, **kwargs)
|
|
|
|
return _wrapped_func_arguments
|
2012-11-28 05:37:13 +01:00
|
|
|
return _wrapped_view_func
|
|
|
|
|
2016-11-30 10:42:58 +01:00
|
|
|
|
2018-05-11 01:39:17 +02:00
|
|
|
def to_not_negative_int_or_none(s: str) -> Optional[int]:
|
2016-11-30 10:42:58 +01:00
|
|
|
if s:
|
|
|
|
return to_non_negative_int(s)
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
2018-05-11 01:39:17 +02:00
|
|
|
def to_utc_datetime(timestamp: str) -> datetime.datetime:
|
2016-12-22 04:46:31 +01:00
|
|
|
return timestamp_to_datetime(float(timestamp))
|
|
|
|
|
2018-05-11 01:39:17 +02:00
|
|
|
def statsd_increment(counter: str, val: int=1,
|
2017-12-09 06:40:18 +01:00
|
|
|
) -> Callable[[Callable[..., ReturnT]], Callable[..., ReturnT]]:
|
2013-04-16 22:52:32 +02:00
|
|
|
"""Increments a statsd counter on completion of the
|
|
|
|
decorated function.
|
|
|
|
|
|
|
|
Pass the name of the counter to this decorator-returning function."""
|
2017-11-27 07:33:05 +01:00
|
|
|
def wrapper(func: Callable[..., ReturnT]) -> Callable[..., ReturnT]:
|
2013-04-16 22:52:32 +02:00
|
|
|
@wraps(func)
|
2017-11-27 07:33:05 +01:00
|
|
|
def wrapped_func(*args: Any, **kwargs: Any) -> ReturnT:
|
2013-05-29 23:58:07 +02:00
|
|
|
ret = func(*args, **kwargs)
|
2013-04-16 22:52:32 +02:00
|
|
|
statsd.incr(counter, val)
|
2013-05-29 23:58:07 +02:00
|
|
|
return ret
|
|
|
|
return wrapped_func
|
|
|
|
return wrapper
|
|
|
|
|
2018-05-11 01:39:17 +02:00
|
|
|
def rate_limit_user(request: HttpRequest, user: UserProfile, domain: str) -> None:
|
2013-06-06 20:08:02 +02:00
|
|
|
"""Returns whether or not a user was rate limited. Will raise a RateLimited exception
|
|
|
|
if the user has been rate limited, otherwise returns and modifies request to contain
|
|
|
|
the rate limit information"""
|
|
|
|
|
2020-03-04 14:05:25 +01:00
|
|
|
RateLimitedUser(user, domain=domain).rate_limit_request(request)
|
2013-06-06 20:08:02 +02:00
|
|
|
|
2019-08-03 20:39:49 +02:00
|
|
|
def rate_limit(domain: str='api_by_user') -> Callable[[ViewFuncT], ViewFuncT]:
|
2017-01-08 16:40:03 +01:00
|
|
|
"""Rate-limits a view. Takes an optional 'domain' param if you wish to
|
|
|
|
rate limit different types of API calls independently.
|
2013-05-29 23:58:07 +02:00
|
|
|
|
|
|
|
Returns a decorator"""
|
2018-03-13 17:51:56 +01:00
|
|
|
def wrapper(func: ViewFuncT) -> ViewFuncT:
|
2013-05-29 23:58:07 +02:00
|
|
|
@wraps(func)
|
2017-11-27 07:33:05 +01:00
|
|
|
def wrapped_func(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
|
2016-07-09 08:08:42 +02:00
|
|
|
|
2016-07-09 20:25:31 +02:00
|
|
|
# It is really tempting to not even wrap our original function
|
|
|
|
# when settings.RATE_LIMITING is False, but it would make
|
|
|
|
# for awkward unit testing in some situations.
|
|
|
|
if not settings.RATE_LIMITING:
|
|
|
|
return func(request, *args, **kwargs)
|
|
|
|
|
2016-07-09 08:08:42 +02:00
|
|
|
if client_is_exempt_from_rate_limiting(request):
|
2013-05-29 23:58:07 +02:00
|
|
|
return func(request, *args, **kwargs)
|
|
|
|
|
|
|
|
try:
|
|
|
|
user = request.user
|
2018-04-26 07:16:17 +02:00
|
|
|
except Exception: # nocoverage # See comments below
|
2016-07-09 08:08:42 +02:00
|
|
|
# TODO: This logic is not tested, and I'm not sure we are
|
|
|
|
# doing the right thing here.
|
2013-05-29 23:58:07 +02:00
|
|
|
user = None
|
|
|
|
|
2018-04-26 07:16:17 +02:00
|
|
|
if not user: # nocoverage # See comments below
|
2016-12-03 18:07:49 +01:00
|
|
|
logging.error("Requested rate-limiting on %s but user is not authenticated!" %
|
2019-04-20 01:00:46 +02:00
|
|
|
(func.__name__,))
|
2013-05-29 23:58:07 +02:00
|
|
|
return func(request, *args, **kwargs)
|
|
|
|
|
2019-01-04 00:17:50 +01:00
|
|
|
if isinstance(user, AnonymousUser): # nocoverage
|
|
|
|
# We can only rate-limit logged-in users for now.
|
|
|
|
# We also only support rate-limiting authenticated
|
|
|
|
# views right now.
|
|
|
|
# TODO: implement per-IP non-authed rate limiting
|
|
|
|
return func(request, *args, **kwargs)
|
|
|
|
|
2016-07-09 08:08:42 +02:00
|
|
|
# Rate-limiting data is stored in redis
|
2013-06-06 20:08:02 +02:00
|
|
|
rate_limit_user(request, user, domain)
|
2013-05-29 23:58:07 +02:00
|
|
|
|
|
|
|
return func(request, *args, **kwargs)
|
2020-04-22 04:13:37 +02:00
|
|
|
return wrapped_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927
|
2013-04-16 22:52:32 +02:00
|
|
|
return wrapper
|
2013-07-02 17:30:04 +02:00
|
|
|
|
2018-03-13 17:51:56 +01:00
|
|
|
def return_success_on_head_request(view_func: ViewFuncT) -> ViewFuncT:
|
2016-11-15 17:20:22 +01:00
|
|
|
@wraps(view_func)
|
2017-10-29 22:36:43 +01:00
|
|
|
def _wrapped_view_func(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
|
2016-11-15 17:20:22 +01:00
|
|
|
if request.method == 'HEAD':
|
|
|
|
return json_success()
|
|
|
|
return view_func(request, *args, **kwargs)
|
2020-04-22 04:13:37 +02:00
|
|
|
return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927
|
2017-07-12 10:16:02 +02:00
|
|
|
|
|
|
|
def zulip_otp_required(view: Any=None,
|
|
|
|
redirect_field_name: str='next',
|
|
|
|
login_url: str=settings.HOME_NOT_LOGGED_IN,
|
|
|
|
) -> Callable[..., HttpResponse]:
|
|
|
|
"""
|
|
|
|
The reason we need to create this function is that the stock
|
|
|
|
otp_required decorator doesn't play well with tests. We cannot
|
|
|
|
enable/disable if_configured parameter during tests since the decorator
|
|
|
|
retains its value due to closure.
|
|
|
|
|
|
|
|
Similar to :func:`~django.contrib.auth.decorators.login_required`, but
|
|
|
|
requires the user to be :term:`verified`. By default, this redirects users
|
|
|
|
to :setting:`OTP_LOGIN_URL`.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def test(user: UserProfile) -> bool:
|
|
|
|
"""
|
|
|
|
:if_configured: If ``True``, an authenticated user with no confirmed
|
|
|
|
OTP devices will be allowed. Default is ``False``. If ``False``,
|
|
|
|
2FA will not do any authentication.
|
|
|
|
"""
|
|
|
|
if_configured = settings.TWO_FACTOR_AUTHENTICATION_ENABLED
|
|
|
|
if not if_configured:
|
|
|
|
return True
|
|
|
|
|
2019-09-23 02:06:21 +02:00
|
|
|
return user.is_verified() or (user.is_authenticated
|
2017-07-12 10:16:02 +02:00
|
|
|
and not user_has_device(user))
|
|
|
|
|
|
|
|
decorator = django_user_passes_test(test,
|
|
|
|
login_url=login_url,
|
|
|
|
redirect_field_name=redirect_field_name)
|
|
|
|
|
|
|
|
return decorator if (view is None) else decorator(view)
|