StaffCoder
Django
DjangoDjango 5.2Python 3.13
18 modules · 72 challengesSign up
Module 18 · DRF Authentication & Permissions

Object Owner Permission

mediumDjango REST FrameworkDRF Authentication & Permissions—No data yet

Problem statement

In this Django project, make the journal API respect who owns a post. Implement IsOwnerOrReadOnly in app/permissions.py and scope the drafts endpoint in app/views.py, so a write is judged against the row's owner and a draft list holds only the requester's own rows. Today nothing compares a post's owner with the account sending the request, so any signed-in account can rewrite or delete any published post, and the drafts endpoint lists every unpublished post in the project - one account's private drafts turn up in everybody else's list and can be read one by one through the detail route.

Requirements

Implement:

  • has_object_permission on IsOwnerOrReadOnly in app/permissions.py
  • get_queryset on DraftViewSet in app/views.py

The following files are already implemented and provided: app/models.py, app/serializers.py, app/urls.py, the accounts app and project/settings.py. Post holds owner, title, body and published; owner is a foreign key to the project's user model, so post.owner is an account and post.owner_id is its primary key. PostSerializer carries id, owner, title, body and published, with owner and published read-only, so no request can hand a post to another account or publish a draft through these endpoints. Accounts are identified by their email address and there is no username field. project/settings.py carries the project-wide REST_FRAMEWORK dict: authentication is sessions plus HTTP basic and the default permission is IsAuthenticated, so every endpoint already needs a signed-in account and nothing in this question is about strangers. app/urls.py routes /api/posts/<int:pk>/ to PostDetailView under the name post-detail, and registers DraftViewSet on a router under the basename draft, giving /api/drafts/ the name draft-list and /api/drafts/<pk>/ the name draft-detail. IsOwnerOrReadOnly has an empty body today, so it inherits the base class's "yes" to every question, which is why every write is currently allowed; keep that class name, and keep PostDetailView and DraftViewSet along with the serializer_class, queryset and permission_classes they already declare.

1. The object permission

  • A safe method is allowed for any signed-in account; any other method is allowed only for the account that owns the row.
  • GET /api/posts/<pk>/ answers 200 to any signed-in account, and the body carries the owner's email under owner.
  • The owner's PATCH answers 200 and the change is stored; the owner's DELETE answers 204 and removes that one row and no other.
  • A PUT, PATCH or DELETE from any other signed-in account answers 403 and leaves the row exactly as it was.
  • The answer depends on the row, not on the account: one signed-in account patching its own post gets 200 and patching somebody else's gets 403, in the same test.

2. The drafts queryset

  • get_queryset on DraftViewSet reaches only the requesting account's own unpublished posts.
  • GET /api/drafts/ then answers 200 with that account's drafts and nothing else: no other account's drafts, and none of the requester's own published posts. Another account asking the same endpoint gets its own drafts.
  • The scoping lives in the queryset and nowhere else: with the object permission taken off the class, the same list request still returns the same two rows.
  • A list request never consults the object permission. has_object_permission is not asked about a single row during a list, while the same class on the same view is asked as soon as a request names one row.

3. The detail route follows the same queryset

  • Because get_object() looks the row up inside get_queryset(), GET /api/drafts/<pk>/ answers 404 for a draft belonging to another account and 200 for the requester's own.
  • Do not add an owner check to the drafts endpoint to produce a 403 here: there is nothing to refuse, because there is nothing found.

Notes

  • DRF asks a permission class two different questions. has_permission(self, request, view) is asked once before the handler runs; it sees the request and the view and nothing else, so it cannot answer anything about a row, because at that moment no row has been loaded. has_object_permission(self, request, view, obj) is asked about one already-loaded row, and is the only hook that can compare a row with the account sending the request.
  • A generic detail view loads the row in get_object() and then calls check_object_permissions, which puts every permission class in the list through has_object_permission.
  • permissions.SAFE_METHODS is DRF's tuple of GET, HEAD and OPTIONS. Returning True for those before looking at the owner is the whole of "or read only"; without it the class is an owner-only permission and no other account can even read a post.
  • A list request never loads a single object, so get_object() is never called, so check_object_permissions is never called. DRF does not walk the rows and filter them through the permission class, and it never has: a permission class on a list view can only answer "may this request happen at all" - yes for everyone or no for everyone.
  • The only thing that decides which rows a list returns is the queryset. get_queryset runs per request and can read self.request, which the class-level queryset attribute cannot, and every route on the class goes through it, the list route and the detail route alike.
  • That is also what decides the status code on the detail route. A row outside the request's queryset is not found at all, so the lookup raises Http404 before any permission is consulted. A 403 there would be a worse design: it would confirm that the row exists. Reaching for 403 on a scoped endpoint is the sign of an owner check written in the wrong layer, because a permission can only refuse a row the view already found.
  • No request in this project ever answers 401, not even an anonymous one: a 401 needs an authentication class that can offer a WWW-Authenticate challenge, and the project lists session authentication first, which has none. Every refusal here is a 403.
  • Only app/permissions.py and app/views.py change. Do not check request.user inside a handler and do not write an if that returns 403 itself: the permission class answers before the handler runs.
  • Do not filter the drafts list by hand in a list method and do not loop the rows through the permission class: the queryset is what decides visibility.
  • Do not reach for Django's model permissions, groups, token endpoints or a login view - the account on the request is already there - and do not add pagination, filtering or throttling.

More in DRF Authentication & Permissions

See the module
Token Authenticated APIMobile clients cannot use browser sessions, so they send an email and a password with every API request. Build the token-obtain endpoint for the project's email-based user model and make token authentication the API's first scheme, with sessions still accepted.—No data yetmediumPermission Class PoliciesEvery endpoint in this API is either wide open or locked to everyone, because no view and no project setting says who is allowed in. Name an authenticated-only project default, let anonymous clients read but not write the public catalog, and gate catalog writes on the model permissions the catalog editors group carries.—No data yetmediumShared Notes APIA notes API is read and rewritten by anybody who can reach it, because no scheme says who a caller is and no rule says what they may do. Accept both token and session authentication, let strangers read the shared record and nothing more, give each note's owner the only write, scope the private surface to its requester, and let the moderators group delete.—No data yetmedium

We use cookies that are necessary to run Staffcoder, and optional analytics cookies to see which pages get used. Analytics stays off unless you accept. Read our Cookie Policy.