:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(legal-documents): add download link in admin and allow staff to download without org membership (#58050)
Rafael Audibert4435faaddba6
diff --git a/products/legal_documents/backend/admin.py b/products/legal_documents/backend/admin.pyindex 996ce2c10248..a48dda5c1d92 100644--- a/products/legal_documents/backend/admin.py+++ b/products/legal_documents/backend/admin.py@@ -12,7 +12,6 @@ from django.utils.html import format_htmlfrom django.utils.safestring import SafeStringimport structlog-from django_admin_inline_paginator.admin import TabularInlinePaginatedfrom posthog.cloud_utils import is_cloud, is_dev_modefrom posthog.storage import object_storage@@ -100,6 +99,7 @@ class LegalDocumentAdmin(admin.ModelAdmin):"representative_email","status","pandadoc_link",+ "download_link","created_by","created_at","updated_at",@@ -137,6 +137,7 @@ class LegalDocumentAdmin(admin.ModelAdmin):"document_type","status","pandadoc_link",+ "download_link",)},),@@ -284,19 +285,22 @@ class LegalDocumentAdmin(admin.ModelAdmin):id=document.pandadoc_document_id,)+ @admin.display(description="Signed PDF")+ def download_link(self, document: LegalDocument) -> str | SafeString:+ # The PDF only exists once the row is signed (PandaDoc-signed rows get+ # the file via the completion webhook; admin-uploaded rows write it+ # synchronously on save). Hide the link until there's something to fetch.+ if document.status != LegalDocument.Status.SIGNED:+ return "—"+ url = f"/api/organizations/{document.organization_id}/legal_documents/{document.id}/download"+ return format_html('<a href="{}" target="_blank" rel="noopener">Download PDF</a>', url)-class LegalDocumentInline(TabularInlinePaginated):- """- Read-only list of an organization's legal documents, rendered as an inline- on the Organization admin page. The "Upload signed document" button in the- inline header links to the LegalDocumentAdmin add view with the- organization pre-filled via `?organization=<id>`.- """++class LegalDocumentInline(admin.TabularInline):+ """List of an organization's legal documents on the Organization admin."""model = LegalDocumentextra = 0- per_page = 20- pagination_key = "page-legal-document"show_change_link = Truetemplate = "admin/legal_documents/edit_inline/tabular.html"@@ -305,23 +309,11 @@ class LegalDocumentInline(TabularInlinePaginated):"company_name","status","pandadoc_link",+ "download_link","created_at",)readonly_fields = fields-can_delete = False- max_num = 0-- def has_add_permission(self, request: HttpRequest, obj: Any = None) -> bool:- # Adding goes through the LegalDocumentAdmin add view via the upload- # button rendered in the inline template — never inline.- return False-- def has_change_permission(self, request: HttpRequest, obj: Any = None) -> bool:- return False-- def has_delete_permission(self, request: HttpRequest, obj: Any = None) -> bool:- return False@admin.display(description="PandaDoc")def pandadoc_link(self, document: LegalDocument) -> str | SafeString:@@ -331,3 +323,10 @@ class LegalDocumentInline(TabularInlinePaginated):'<a href="https://app.pandadoc.com/a/#/documents/{id}" target="_blank" rel="noopener">{id}</a>',id=document.pandadoc_document_id,)++ @admin.display(description="Signed PDF")+ def download_link(self, document: LegalDocument) -> str | SafeString:+ if document.status != LegalDocument.Status.SIGNED:+ return "—"+ url = f"/api/organizations/{document.organization_id}/legal_documents/{document.id}/download"+ return format_html('<a href="{}" target="_blank" rel="noopener">Download PDF</a>', url)diff --git a/products/legal_documents/backend/presentation/views.py b/products/legal_documents/backend/presentation/views.pyindex 7f81a9964fc9..c34de4cd45c2 100644--- a/products/legal_documents/backend/presentation/views.py+++ b/products/legal_documents/backend/presentation/views.py@@ -23,6 +23,17 @@ class LegalDocumentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object = "legal_document"permission_classes = [IsCloudOrDevDeployment, permissions.IsAuthenticated, IsOrganizationAdminOrOwner]+ def dangerously_get_permissions(self) -> list[permissions.BasePermission]:+ # Staff users (Django admin) need to download signed PDFs from the+ # admin change view without first joining the customer's organization.+ # The default permission chain adds OrganizationMemberPermissions which+ # rejects them; bypass it here for the download action only. The+ # download still scopes by URL-provided org_id inside the view, so a+ # staff user can't grab a document that doesn't belong to that org.+ if self.action == "download" and getattr(self.request.user, "is_staff", False):+ return [IsCloudOrDevDeployment(), permissions.IsAuthenticated()]+ raise NotImplementedError()+@extend_schema(responses={200: LegalDocumentSerializer(many=True)})def list(self, request: Request, **kwargs) -> Response:documents = api.list_for_organization(self.organization.id)diff --git a/products/legal_documents/backend/templates/admin/legal_documents/edit_inline/tabular.html b/products/legal_documents/backend/templates/admin/legal_documents/edit_inline/tabular.htmlindex d7d748104906..78135b25f184 100644--- a/products/legal_documents/backend/templates/admin/legal_documents/edit_inline/tabular.html+++ b/products/legal_documents/backend/templates/admin/legal_documents/edit_inline/tabular.html@@ -1,63 +1,12 @@-{% load i18n admin_urls static admin_modify %}-<div class="inline-group" id="{{ inline_admin_formset.formset.prefix }}-group">- <div class="tabular inline-related {% if forloop.last %}last-related{% endif %}">-{{ inline_admin_formset.formset.management_form }}-<fieldset class="module {{ inline_admin_formset.classes }}">- <h2 style="display: flex; align-items: center; justify-content: space-between; gap: 12px;">- <span>{{ inline_admin_formset.opts.verbose_name_plural|capfirst }}</span>- {% if inline_admin_formset.formset.instance.pk %}- <a class="button" style="font-weight: normal;" href="{% url 'admin:legal_documents_legaldocument_add' %}?organization={{ inline_admin_formset.formset.instance.pk }}">- {% translate "Upload signed document" %}- </a>- {% endif %}- </h2>- {{ inline_admin_formset.formset.non_form_errors }}- {% if inline_admin_formset|length %}- <table>- <thead><tr>- {% for field in inline_admin_formset.fields %}- {% if not field.widget.is_hidden %}- <th class="column-{{ field.name }}">{{ field.label|capfirst }}- {% if field.help_text %}<img src="{% static "admin/img/icon-unknown.svg" %}" class="help help-tooltip" width="10" height="10" alt="({{ field.help_text|striptags }})" title="{{ field.help_text|striptags }}">{% endif %}- </th>- {% endif %}- {% endfor %}- {% if inline_admin_formset.opts.show_change_link %}<th></th>{% endif %}- </tr></thead>+{% load i18n %}+{% include "admin/edit_inline/tabular.html" %}- <tbody>- {% for inline_admin_form in inline_admin_formset %}- {% if inline_admin_form.form.non_field_errors %}- <tr class="row-form-errors"><td colspan="{{ inline_admin_form|cell_count }}">{{ inline_admin_form.form.non_field_errors }}</td></tr>- {% endif %}- <tr class="form-row" id="{{ inline_admin_formset.formset.prefix }}-{{ forloop.counter0 }}">- {% for fieldset in inline_admin_form %}- {% for line in fieldset %}- {% for field in line %}- {% if not field.field.is_hidden %}- <td class="{% if field.field.name %}field-{{ field.field.name }}{% endif %}">- {% if field.is_readonly %}- <p>{{ field.contents }}</p>- {% else %}- {{ field.field }}- {% endif %}- </td>- {% endif %}- {% endfor %}- {% endfor %}- {% endfor %}- {% if inline_admin_formset.opts.show_change_link and inline_admin_form.original %}- <td class="original">- <a href="{% url inline_admin_formset.opts.opts|admin_urlname:'change' inline_admin_form.original.pk|admin_urlquote %}" class="inlinechangelink">{% translate "Change" %}</a>- </td>- {% endif %}- </tr>- {% endfor %}- </tbody>- </table>- {% else %}- <p style="margin: 8px 0; color: var(--body-quiet-color);">{% translate "No legal documents yet for this organization." %}</p>- {% endif %}-</fieldset>- </div>-</div>+{% if inline_admin_formset.formset.instance.pk %}+<p style="margin: 8px 0 24px;">+ <a class="button" href="{% url 'admin:legal_documents_legaldocument_add' %}?organization={{ inline_admin_formset.formset.instance.pk }}">+ {% translate "Upload signed document" %}+ </a>+</p>+{% endif %}++<style>#{{ inline_admin_formset.formset.prefix }}-group .add-row { display: none; }</style>diff --git a/products/legal_documents/backend/tests/test_api.py b/products/legal_documents/backend/tests/test_api.pyindex 20bc5183a8cd..e0c521282bf7 100644--- a/products/legal_documents/backend/tests/test_api.py+++ b/products/legal_documents/backend/tests/test_api.py@@ -315,6 +315,20 @@ class TestLegalDocumentDownloadEndpoint(APIBaseTest):response = self.client.get(url)self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ def test_staff_user_without_membership_can_download(self) -> None:+ # PostHog staff need to fetch signed PDFs from the Django admin without+ # joining the customer's org first. Drop the membership entirely and+ # flip is_staff — the request should still 302 to the presigned URL.+ self.organization_membership.delete()+ self.user.is_staff = True+ self.user.save()+ with patch(+ "products.legal_documents.backend.logic.object_storage.get_presigned_url",+ return_value="https://s3.example/signed-url?token=abc",+ ):+ response = self.client.get(self.url)+ self.assertEqual(response.status_code, status.HTTP_302_FOUND)+@override_settings(CLOUD_DEPLOYMENT="US")class TestLegalDocumentPandaDocWebhook(APIBaseTest):