Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(Surveys): Allow Personal API Keys to read responses_count for surveys #25879

Merged
merged 10 commits into from
Oct 29, 2024
2 changes: 1 addition & 1 deletion posthog/api/survey.py
Original file line number Diff line number Diff line change
Expand Up @@ -597,7 +597,7 @@ def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:

return super().destroy(request, *args, **kwargs)

@action(methods=["GET"], detail=False)
@action(methods=["GET"], detail=False, required_scopes=["survey:read"])
def responses_count(self, request: request.Request, **kwargs):
earliest_survey_start_date = Survey.objects.filter(team_id=self.team_id).aggregate(Min("start_date"))[
"start_date__min"
Expand Down
36 changes: 36 additions & 0 deletions posthog/api/test/test_survey.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from rest_framework import status

from posthog.api.survey import nh3_clean_with_allow_list
from posthog.api.test.test_personal_api_keys import PersonalAPIKeysBaseTest
from posthog.constants import AvailableFeature
from posthog.models import Action, FeatureFlag, Team
from posthog.models.cohort.cohort import Cohort
Expand Down Expand Up @@ -2783,6 +2784,41 @@ def test_list_surveys_excludes_description(self):
assert surveys[1]["name"] == "Survey 2"


class TestSurveyAPITokens(PersonalAPIKeysBaseTest, APIBaseTest):
def setUp(self):
super().setUp()
self.key.scopes = ["survey:read"]
self.key.save()

@freeze_time("2024-05-01 14:40:09")
def test_responses_count_works_with_survey_read(self):
survey_counts = {
"d63bb580-01af-4819-aae5-edcf7ef2044f": 3,
"fe7c4b62-8fc9-401e-b483-e4ff98fd13d5": 6,
"daed7689-d498-49fe-936f-e85554351b6c": 100,
}

earliest_survey = Survey.objects.create(team_id=self.team.id)
earliest_survey.start_date = datetime.now() - timedelta(days=101)
earliest_survey.save()

for survey_id, count in survey_counts.items():
for _ in range(count):
_create_event(
event="survey sent",
team=self.team,
distinct_id=self.user.id,
properties={"$survey_id": survey_id},
timestamp=datetime.now() - timedelta(days=count),
)

response = self._do_request(f"/api/projects/{self.team.id}/surveys/responses_count")
self.assertEqual(response.status_code, status.HTTP_200_OK)

data = response.json()
self.assertEqual(data, survey_counts)


class TestResponsesCount(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
@freeze_time("2024-05-01 14:40:09")
Expand Down
Loading