예제 #1
0
    def process_exception(self, request: HttpRequest,
                          exception: Exception) -> Optional[HttpResponse]:
        if isinstance(exception, MissingAuthenticationError):
            if 'text/html' in request.META.get('HTTP_ACCEPT', ''):
                # If this looks like a request from a top-level page in a
                # browser, send the user to the login page.
                #
                # TODO: The next part is a bit questionable; it will
                # execute the likely intent for intentionally visiting
                # an API endpoint without authentication in a browser,
                # but that's an unlikely to be done intentionally often.
                return HttpResponseRedirect(
                    f'{settings.HOME_NOT_LOGGED_IN}?next={request.path}')
            if request.path.startswith("/api"):
                # For API routes, ask for HTTP basic auth (email:apiKey).
                return json_unauthorized()
            else:
                # For /json routes, ask for session authentication.
                return json_unauthorized(www_authenticate='session')

        if isinstance(exception, JsonableError):
            return json_response_from_error(exception)
        if request.error_format == "JSON":
            capture_exception(exception)
            json_error_logger = logging.getLogger(
                "zerver.middleware.json_error_handler")
            json_error_logger.error(traceback.format_exc(),
                                    extra=dict(request=request))
            return json_error(_("Internal server error"), status=500)
        return None
예제 #2
0
 def process_exception(self, request: HttpRequest, exception: Exception) -> Optional[HttpResponse]:
     if isinstance(exception, JsonableError):
         return json_response_from_error(exception)
     if request.error_format == "JSON":
         logging.error(traceback.format_exc(), extra=dict(request=request))
         return json_error(_("Internal server error"), status=500)
     return None
예제 #3
0
 def process_exception(self, request: HttpRequest, exception: Exception) -> Optional[HttpResponse]:
     if isinstance(exception, JsonableError):
         return json_response_from_error(exception)
     if request.error_format == "JSON":
         logging.error(traceback.format_exc(), extra=dict(request=request))
         return json_error(_("Internal server error"), status=500)
     return None
예제 #4
0
    def process_exception(self, request: HttpRequest,
                          exception: Exception) -> Optional[HttpResponse]:
        if isinstance(exception, MissingAuthenticationError):
            if "text/html" in request.headers.get("Accept", ""):
                # If this looks like a request from a top-level page in a
                # browser, send the user to the login page.
                #
                # TODO: The next part is a bit questionable; it will
                # execute the likely intent for intentionally visiting
                # an API endpoint without authentication in a browser,
                # but that's an unlikely to be done intentionally often.
                return HttpResponseRedirect(
                    f"{settings.HOME_NOT_LOGGED_IN}?{urlencode({'next': request.path})}"
                )
            if request.path.startswith("/api"):
                # For API routes, ask for HTTP basic auth (email:apiKey).
                return json_unauthorized()
            else:
                # For /json routes, ask for session authentication.
                return json_unauthorized(www_authenticate="session")

        if isinstance(exception, JsonableError):
            return json_response_from_error(exception)
        if RequestNotes.get_notes(
                request).error_format == "JSON" and not settings.TEST_SUITE:
            capture_exception(exception)
            json_error_logger = logging.getLogger(
                "zerver.middleware.json_error_handler")
            json_error_logger.error(traceback.format_exc(),
                                    extra=dict(request=request))
            return json_response(res_type="error",
                                 msg=_("Internal server error"),
                                 status=500)
        return None
예제 #5
0
def csrf_failure(request, reason=""):
    # type: (HttpRequest, Text) -> HttpResponse
    if request.error_format == "JSON":
        return json_response_from_error(CsrfFailureError(reason))
    else:
        return html_csrf_failure(request, reason)
예제 #6
0
def csrf_failure(request: HttpRequest, reason: str = "") -> HttpResponse:
    if request.error_format == "JSON":
        return json_response_from_error(CsrfFailureError(reason))
    else:
        return html_csrf_failure(request, reason)
예제 #7
0
def avatar(
    request: HttpRequest,
    maybe_user_profile: Union[UserProfile, AnonymousUser],
    email_or_id: str,
    medium: bool = False,
) -> HttpResponse:
    """Accepts an email address or user ID and returns the avatar"""
    is_email = False
    try:
        int(email_or_id)
    except ValueError:
        is_email = True

    if not maybe_user_profile.is_authenticated:
        # Allow anonymous access to avatars only if spectators are
        # enabled in the organization.
        realm = get_valid_realm_from_request(request)
        if not realm.allow_web_public_streams_access():
            raise MissingAuthenticationError()

        # We only allow the ID format for accessing a user's avatar
        # for spectators. This is mainly for defense in depth, since
        # email_address_visibility should mean spectators only
        # interact with fake email addresses anyway.
        if is_email:
            raise MissingAuthenticationError()

        if settings.RATE_LIMITING:
            try:
                unique_avatar_key = f"{realm.id}/{email_or_id}/{medium}"
                rate_limit_spectator_attachment_access_by_file(
                    unique_avatar_key)
            except RateLimited:
                return json_response_from_error(
                    RateLimited(
                        _("Too many attempts, please try after some time.")))
    else:
        realm = maybe_user_profile.realm

    try:
        if is_email:
            avatar_user_profile = get_user_including_cross_realm(
                email_or_id, realm)
        else:
            avatar_user_profile = get_user_by_id_in_realm_including_cross_realm(
                int(email_or_id), realm)
        # If there is a valid user account passed in, use its avatar
        url = avatar_url(avatar_user_profile, medium=medium)
    except UserProfile.DoesNotExist:
        # If there is no such user, treat it as a new gravatar
        email = email_or_id
        avatar_version = 1
        url = get_gravatar_url(email, avatar_version, medium)

    # We can rely on the URL already having query parameters. Because
    # our templates depend on being able to use the ampersand to
    # add query parameters to our url, get_avatar_url does '?x=x'
    # hacks to prevent us from having to jump through decode/encode hoops.
    assert url is not None
    url = append_url_query_string(url, request.META["QUERY_STRING"])
    return redirect(url)
예제 #8
0
def csrf_failure(request: HttpRequest, reason: str="") -> HttpResponse:
    if request.error_format == "JSON":
        return json_response_from_error(CsrfFailureError(reason))
    else:
        return html_csrf_failure(request, reason)
예제 #9
0
def csrf_failure(request, reason=""):
    # type: (HttpRequest, Optional[Text]) -> HttpResponse
    if request.error_format == "JSON":
        return json_response_from_error(CsrfFailureError(reason))
    else:
        return html_csrf_failure(request, reason)