Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions cms/djangoapps/contentstore/rest_api/v3/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""
Serializers for the v3 contentstore API.
"""

from cms.djangoapps.contentstore.rest_api.v1.serializers import StudioHomeSerializer


class StudioHomeContextSerializer(StudioHomeSerializer):
"""
The Studio home page settings, without the course and library lists.

The v3 home is built with ``get_home_context(request, True)``, which leaves
those lists empty; they are served by ``/api/authoring/v4/courses/`` and the
library APIs instead.
"""
archived_courses = None
courses = None
in_process_course_actions = None
libraries = None
33 changes: 18 additions & 15 deletions cms/djangoapps/contentstore/rest_api/v3/views/home.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@
* ADR 0029 – standardized error envelope, opted in via
:class:`StandardizedErrorMixin` (v3-scoped — does not change the
project-wide DRF ``EXCEPTION_HANDLER`` setting)
* ADR 0036 – field selection via ``?fields=`` (e.g. ``?fields=courses``).
The ``list`` action returns a wide ``StudioHomeSerializer`` payload with
~25 top-level keys; clients that only need a subset can request it
* ADR 0036 – field selection via ``?fields=`` (e.g. ``?fields=studio_name``).
The ``list`` action returns a wide ``StudioHomeContextSerializer`` payload
with ~20 top-level keys; clients that only need a subset can request it
explicitly. The flat-list ``courses`` and ``libraries`` actions are
out of scope (single-key dict around a list) and do not honour
``?fields=``.
Expand All @@ -40,11 +40,8 @@
from rest_framework.request import Request
from rest_framework.response import Response

from cms.djangoapps.contentstore.rest_api.v1.serializers import (
CourseHomeTabSerializer,
LibraryTabSerializer,
StudioHomeSerializer,
)
from cms.djangoapps.contentstore.rest_api.v1.serializers import CourseHomeTabSerializer, LibraryTabSerializer
from cms.djangoapps.contentstore.rest_api.v3.serializers import StudioHomeContextSerializer
from cms.djangoapps.contentstore.utils import get_course_context, get_home_context, get_library_context
from cms.lib.spectacular import CmsAutoSchema

Expand Down Expand Up @@ -72,45 +69,47 @@ class HomeViewSet(StandardizedErrorMixin, viewsets.ViewSet):
schema = _HomeAutoSchema()
authentication_classes = (JwtAuthentication, SessionAuthenticationAllowInactiveUser)
permission_classes = (IsAuthenticated,)
serializer_class = StudioHomeSerializer
serializer_class = StudioHomeContextSerializer

def get_serializer_class(self):
"""Return the appropriate serializer class for the current action."""
if self.action == 'courses':
return CourseHomeTabSerializer
if self.action == 'libraries':
return LibraryTabSerializer
return StudioHomeSerializer
return StudioHomeContextSerializer

def get_serializer(self, *args, **kwargs):
"""Return a serializer instance using the action-appropriate class."""
return self.get_serializer_class()(*args, **kwargs)

@extend_schema(
responses={(200, "application/json"): StudioHomeSerializer},
responses={(200, "application/json"): StudioHomeContextSerializer},
parameters=[
OpenApiParameter("org", str, OpenApiParameter.QUERY, description="Filter by course org"),
OpenApiParameter(
"fields",
str,
OpenApiParameter.QUERY,
description=(
"ADR 0036 explicit field selection. Comma-separated list "
"of top-level keys to include in the response (e.g. "
"``courses,libraries,studio_name``). Omit for the full "
"``studio_name,platform_name``). Omit for the full "
"response. Unknown keys are silently skipped."
),
),
],
)
def list(self, request: Request):
"""
Get an object containing all courses and libraries on home page.
Get the Studio home page settings for the requesting user.

The course and library lists are not included; use
``/api/authoring/v4/courses/`` for the courses.

**Example Request**

GET /api/contentstore/v3/home/
GET /api/contentstore/v3/home/?fields=courses,libraries (ADR 0036)
GET /api/contentstore/v3/home/?fields=studio_name,platform_name (ADR 0036)
"""
home_context = get_home_context(request, True)
home_context.update({
Expand Down Expand Up @@ -144,6 +143,8 @@ def list(self, request: Request):
401: OpenApiResponse(description="The requester is not authenticated."),
},
)
# Replaced by /api/authoring/v4/courses/, so it stays out of the public schema.
@extend_schema(exclude=True)
@action(detail=False, methods=['get'], url_path='courses', url_name='courses')
def courses(self, request: Request):
"""
Expand Down Expand Up @@ -186,6 +187,8 @@ def courses(self, request: Request):
401: OpenApiResponse(description="The requester is not authenticated."),
},
)
# The legacy library list, which is being removed, so it stays out of the public schema.
@extend_schema(exclude=True)
@action(detail=False, methods=['get'], url_path='libraries', url_name='libraries')
def libraries(self, request: Request):
"""
Expand Down
36 changes: 28 additions & 8 deletions cms/djangoapps/contentstore/rest_api/v3/views/tests/test_home.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

patch.object is used for the ViewSet's get_serializer() method because:
- get_serializer_class() returns a *different* serializer per action.
- Each serializer (StudioHomeSerializer, CourseHomeTabSerializer,
- Each serializer (StudioHomeContextSerializer, CourseHomeTabSerializer,
LibraryTabSerializer) has many required fields that would be painful to
satisfy with synthetic data.
- Patching get_serializer() lets us focus on routing + service-call
Expand All @@ -14,10 +14,13 @@
"""
from unittest.mock import patch

from django.test import SimpleTestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase

from cms.djangoapps.contentstore.rest_api.v2.views.tests.helpers import generate_cms_schema
from cms.djangoapps.contentstore.rest_api.v3.serializers import StudioHomeContextSerializer
from cms.djangoapps.contentstore.rest_api.v3.views.home import HomeViewSet
from common.djangoapps.student.tests.factories import UserFactory

Expand Down Expand Up @@ -124,7 +127,7 @@ def test_libraries_calls_get_library_context(self, mock_libs, mock_get_ser):
class TestHomeViewSetFieldSelection(APITestCase):
"""
ADR 0036 — verify ``?fields=`` filters top-level keys on the ``list``
action's wide ``StudioHomeSerializer`` response. ``courses`` and
action's wide ``StudioHomeContextSerializer`` response. ``courses`` and
``libraries`` actions are out of scope (single-key dicts).
"""

Expand All @@ -143,31 +146,48 @@ def test_default_response_keeps_all_keys(self, mock_home, mock_org, mock_get_ser
mock_org.is_autocreate_enabled.return_value = True
mock_get_ser.return_value.data = {
'studio_name': 'Studio', 'platform_name': 'edX',
'courses': [], 'libraries': [], 'archived_courses': [],
'course_creator_status': 'granted', 'user_is_active': True,
}

response = self.client.get(self.url)

assert response.status_code == status.HTTP_200_OK
assert set(response.data.keys()) == {
'studio_name', 'platform_name', 'courses', 'libraries', 'archived_courses',
'studio_name', 'platform_name', 'course_creator_status', 'user_is_active',
}

@patch.object(HomeViewSet, 'get_serializer')
@patch(MOCK_ORG_API)
@patch(MOCK_GET_HOME_CONTEXT)
def test_fields_csv_restricts_top_level_keys(self, mock_home, mock_org, mock_get_ser): # noqa: ARG002
"""``?fields=courses,libraries`` returns exactly those keys."""
"""``?fields=course_creator_status,user_is_active`` returns exactly those keys."""
mock_home.return_value = {'can_create_organizations': True}
mock_org.is_autocreate_enabled.return_value = True
mock_get_ser.return_value.data = {
'studio_name': 'Studio', 'platform_name': 'edX',
'courses': [], 'libraries': [], 'archived_courses': [],
'course_creator_status': 'granted', 'user_is_active': True,
}

response = self.client.get(self.url, {'fields': 'courses,libraries'})
response = self.client.get(self.url, {'fields': 'course_creator_status,user_is_active'})

assert response.status_code == status.HTTP_200_OK
assert set(response.data.keys()) == {'courses', 'libraries'}
assert set(response.data.keys()) == {'course_creator_status', 'user_is_active'}
assert 'studio_name' not in response.data
assert 'platform_name' not in response.data


class TestHomeViewSetSchema(SimpleTestCase):
"""Only the ``list`` action is published, and it describes no course or library lists."""

def test_only_the_home_settings_are_published(self):
paths = generate_cms_schema()['paths']
for prefix in ('/api/contentstore/v3/home/', '/api/authoring/v3/home/'):
assert prefix in paths
assert f'{prefix}courses/' not in paths
assert f'{prefix}libraries/' not in paths

def test_the_home_settings_leave_out_the_course_and_library_lists(self):
fields = StudioHomeContextSerializer().fields
for name in ('courses', 'archived_courses', 'in_process_course_actions', 'libraries'):
assert name not in fields
assert 'course_creator_status' in fields
13 changes: 4 additions & 9 deletions cms/djangoapps/contentstore/views/course.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
from cms.djangoapps.contentstore.api.views.utils import get_bool_param, get_datetime_param
from cms.djangoapps.contentstore.xblock_storage_handlers.view_handlers import create_xblock_info
from cms.djangoapps.course_creators.models import CourseCreator
from cms.djangoapps.course_creators.views import add_user_with_status_unrequested, get_course_creator_status
from cms.djangoapps.course_creators.views import get_course_creator_status
from cms.djangoapps.models.settings.course_grading import CourseGradingModel
from cms.djangoapps.models.settings.course_metadata import CourseMetadata
from cms.djangoapps.models.settings.encoder import CourseSettingsEncoder
Expand Down Expand Up @@ -2053,21 +2053,16 @@ def _get_course_creator_status(user):
Helper method for returning the course creator status for a particular user,
taking into account the values of DISABLE_COURSE_CREATION and ENABLE_CREATOR_GROUP.

If the user passed in has not previously visited the index page, it will be
added with status 'unrequested' if the course creator group is in use.
A user with no entry in the course creator table is reported as 'unrequested';
the entry is created when they request access.
"""

if user.is_staff:
course_creator_status = 'granted'
elif getattr(settings, 'DISABLE_COURSE_CREATION', False):
course_creator_status = 'disallowed_for_this_site'
elif getattr(settings, 'ENABLE_CREATOR_GROUP', False):
course_creator_status = get_course_creator_status(user)
if course_creator_status is None:
# User not grandfathered in as an existing user, has not previously visited the dashboard page.
# Add the user to the course creator admin table with status 'unrequested'.
add_user_with_status_unrequested(user)
course_creator_status = get_course_creator_status(user)
course_creator_status = get_course_creator_status(user) or CourseCreator.UNREQUESTED

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On the side effect in the description: I think this needs a decision before merge rather than a note. CourseCreatorAdmin returns False from has_add_permission and keeps username read-only, so an admin can no longer grant creator access to someone who hasn't requested it. Operators who pre-approve staff or instructors today lose that workflow.

Two options I can see:

  • allow adding rows in the admin, with user editable only on the add form;
  • keep the behaviour and add an operator-facing release note saying users appear in the admin only after they request access.

I'd lean towards the first, since it keeps the old capability without bringing back the write on GET.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, went with the first option. Staff can add rows in the admin now; user is picked by id on the add form and stays read-only on the change form. Added a test that adds a user who never requested access as granted through the admin and checks they land in the creator group. I've dropped the side-effect note from the description.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The add form covers the capability, thanks. It's still something operators will notice though: with ENABLE_CREATOR_GROUP on by default, the Course Creator admin stops listing every user who has opened Studio, and granting access ahead of a request now goes through the add form. Can you add an entry for that to the Willow operator notes before this merges? https://openedx.atlassian.net/wiki/spaces/COMM/pages/6476169217/Willow+-+Operator+Dev+Notes

Something like:

Course creator access: Studio users no longer appear in the Course Creator admin as unrequested just by visiting Studio; a user is added only when they request course creator access. To grant access to someone before they request it, use the new "Add course creator" button in the Course Creator admin.

@taimoor-ahmed-1 taimoor-ahmed-1 Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correction to my note above: the code side (the add form, user read-only on the change form, and the test) is in 6f8c8a2, but the Willow operator-notes entry asked for here is not on the page yet as of Nov 11. This stays open until that entry is added.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added the entry to the Willow page myself, so this one is done. The last thing before this merges is the DEPR for the courses action, can you link it here once it's open?

else:
course_creator_status = 'granted'

Expand Down
14 changes: 13 additions & 1 deletion cms/djangoapps/course_creators/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,13 @@ class CourseCreatorAdmin(admin.ModelAdmin):
'fields': ['username', 'state', 'state_changed', 'note', 'all_organizations', 'organizations']
}),
)
# The user is chosen by id on the add form, and read-only once added.
add_fieldsets = (
(None, {
'fields': ['user', 'state', 'note', 'all_organizations', 'organizations']
}),
)
raw_id_fields = ('user',)
# Fields that filtering support
list_filter = ['state', 'state_changed']
# Fields that search supports.
Expand All @@ -99,8 +106,13 @@ def username(self, inst):

username.admin_order_field = 'user__username'

def get_fieldsets(self, request, obj=None):
if obj is None:
return self.add_fieldsets
return super().get_fieldsets(request, obj)

def has_add_permission(self, request):
return False
return request.user.is_staff

def has_delete_permission(self, request, obj=None):
return False
Expand Down
32 changes: 30 additions & 2 deletions cms/djangoapps/course_creators/tests/test_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from django.http import HttpRequest
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse

from cms.djangoapps.course_creators.admin import CourseCreatorAdmin
from cms.djangoapps.course_creators.models import CourseCreator
Expand Down Expand Up @@ -149,9 +150,36 @@ def _change_state(self, state):

def test_add_permission(self):
"""
Tests that staff cannot add entries
Tests that only staff can add entries
"""
self.assertFalse(self.creator_admin.has_add_permission(self.request)) # noqa: PT009
assert self.creator_admin.has_add_permission(self.request)

self.request.user = self.user
assert not self.creator_admin.has_add_permission(self.request)

@override_settings(ENABLE_CREATOR_GROUP=True)
def test_staff_can_grant_a_user_who_has_not_requested_access(self):
new_user = UserFactory.create()
superuser = UserFactory.create(is_staff=True, is_superuser=True, password='foo')
self.client.login(username=superuser.username, password='foo')

response = self.client.post(reverse('admin:course_creators_coursecreator_add'), {
'user': new_user.id,
'state': CourseCreator.GRANTED,
'note': '',
'all_organizations': 'on',
})

assert response.status_code == 302
assert CourseCreator.objects.get(user=new_user).state == CourseCreator.GRANTED
assert auth.user_has_role(new_user, CourseCreatorRole())

def test_the_user_is_read_only_once_added(self):
add_fields = self.creator_admin.get_fieldsets(self.request)[0][1]['fields']
change_fields = self.creator_admin.get_fieldsets(self.request, self.table_entry)[0][1]['fields']
assert 'user' in add_fields
assert 'user' not in change_fields
assert 'username' in self.creator_admin.get_readonly_fields(self.request, self.table_entry)

def test_delete_permission(self):
"""
Expand Down
Loading
Loading