2021-11-02 15:42:58 +01:00
|
|
|
from django.contrib.auth.models import AnonymousUser
|
2020-06-11 00:54:34 +02:00
|
|
|
from django.http import HttpRequest, HttpResponse, HttpResponseForbidden
|
2018-03-08 09:37:09 +01:00
|
|
|
from django.shortcuts import redirect
|
2021-04-16 00:57:30 +02:00
|
|
|
from django.utils.translation import gettext as _
|
2020-06-11 00:54:34 +02:00
|
|
|
|
2021-11-02 15:42:58 +01:00
|
|
|
from zerver.context_processors import get_valid_realm_from_request
|
2023-12-15 20:03:19 +01:00
|
|
|
from zerver.lib.attachments import validate_attachment_request
|
2018-03-08 09:37:09 +01:00
|
|
|
from zerver.lib.thumbnail import generate_thumbnail_url
|
2024-06-28 21:14:00 +02:00
|
|
|
from zerver.lib.typed_endpoint import typed_endpoint
|
2023-12-15 20:03:19 +01:00
|
|
|
from zerver.models import Realm, UserProfile
|
2020-06-11 00:54:34 +02:00
|
|
|
|
2018-03-08 09:37:09 +01:00
|
|
|
|
2021-11-02 15:42:58 +01:00
|
|
|
def validate_thumbnail_request(
|
|
|
|
realm: Realm,
|
2024-07-12 02:30:23 +02:00
|
|
|
maybe_user_profile: UserProfile | AnonymousUser,
|
2021-11-02 15:42:58 +01:00
|
|
|
path: str,
|
2024-07-12 02:30:23 +02:00
|
|
|
) -> bool | None:
|
2018-03-08 09:37:09 +01:00
|
|
|
# path here does not have a leading / as it is parsed from request hitting the
|
|
|
|
# thumbnail endpoint (defined in urls.py) that way.
|
2021-02-12 08:20:45 +01:00
|
|
|
if path.startswith("user_uploads/"):
|
|
|
|
path_id = path[len("user_uploads/") :]
|
2021-11-02 15:42:58 +01:00
|
|
|
return validate_attachment_request(maybe_user_profile, path_id, realm)
|
2018-03-08 09:37:09 +01:00
|
|
|
|
|
|
|
# This is an external link and we don't enforce restricted view policy here.
|
|
|
|
return True
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2024-06-28 21:14:00 +02:00
|
|
|
@typed_endpoint
|
2021-02-12 08:19:30 +01:00
|
|
|
def backend_serve_thumbnail(
|
|
|
|
request: HttpRequest,
|
2024-07-12 02:30:23 +02:00
|
|
|
maybe_user_profile: UserProfile | AnonymousUser,
|
2024-06-28 21:14:00 +02:00
|
|
|
*,
|
|
|
|
url: str,
|
|
|
|
size: str,
|
2021-02-12 08:19:30 +01:00
|
|
|
) -> HttpResponse:
|
2021-11-02 15:42:58 +01:00
|
|
|
if not maybe_user_profile.is_authenticated:
|
|
|
|
realm = get_valid_realm_from_request(request)
|
|
|
|
else:
|
|
|
|
assert isinstance(maybe_user_profile, UserProfile)
|
|
|
|
realm = maybe_user_profile.realm
|
|
|
|
|
|
|
|
if not validate_thumbnail_request(realm, maybe_user_profile, url):
|
2018-03-08 09:37:09 +01:00
|
|
|
return HttpResponseForbidden(_("<p>You are not authorized to view this file.</p>"))
|
|
|
|
|
2021-05-07 00:38:24 +02:00
|
|
|
thumbnail_url = generate_thumbnail_url(url)
|
2018-03-08 09:37:09 +01:00
|
|
|
return redirect(thumbnail_url)
|