Problem statement
In this Django project, give the notes API its missing authentication, policy and scoping. Build the token endpoint in app/auth.py, the two permission classes in app/permissions.py, the private surface's scoping in app/views.py, and the project-wide defaults in the REST_FRAMEWORK dict in _project/api_settings.py_. Today every caller can read and rewrite every note: nothing says how a caller proves who it is, so the token the mobile app would send is read by nobody, and nothing says what a caller may then do, so a stranger can delete somebody else's note, one account's private notes are listed to everybody, and the moderators who are supposed to clear up abuse have no power the rest of us lack.
Requirements
Implement:
- the default authentication and permission classes in REST_FRAMEWORK in project/api_settings.py
- EmailAuthTokenView and the credentials it accepts, in app/auth.py
- IsOwnerOrReadOnly and CanDeleteAnyNote in app/permissions.py
- the permission policy on the shared views and the scoping on PrivateNoteViewSet, in app/views.py
The following are already implemented and provided: the accounts app, app/models.py, app/serializers.py, app/urls.py, app/migrations/ and project/settings.py. accounts.User is built on AbstractBaseUser and PermissionsMixin, its only identity field is a unique email, it has no username field at all, and USERNAME_FIELD = "email"; AUTH_USER_MODEL already points at it. Note has an owner, a title, a body and an is_private flag that says which surface it lives on. NoteSerializer is finished and renders owner as the owner's email address alongside title, body and is_private, with owner and is_private both read-only, so no payload can hand a note to somebody else or push it onto the other surface. rest_framework.authtoken is in INSTALLED_APPS, so the Token model and its migration are in place and you never create that table yourself. app/migrations/0002_note_moderators_group.py ships a group named note-moderators carrying Django's delete_note permission on Note; nobody is in it to begin with, and membership is the only way an account is meant to gain the power to remove other people's notes. project/settings.py imports REST_FRAMEWORK from project/api_settings.py, which is yours.
The routes are given: / is home, the banner the Run button shows, open to everybody. /api/token/ is named api-token and routed to app.auth.EmailAuthTokenView, a placeholder answering 501. /api/account/ is named account and routed to app.views.AccountView, which is finished: it declares no permissions of its own, because the project-wide default is what is supposed to protect it, and it returns {"email": request.user.get_username()} without caring which scheme put a user there. /api/notes/ is named note-list and /api/notes/<pk>/ is named note-detail, routed to PublicNoteListView and PublicNoteDetailView, whose Note.objects.filter(is_private=False) querysets are final: the shared surface is the notes that are not private, and a private note has no URL there at all. PrivateNoteViewSet is registered on a router, so /api/private/ (named private-list) and /api/private/<pk>/ (named private-detail) are two views of the same class. Every one of those class names stays as it is, because the read-only URLconf and the tests import them.
This table is the contract. token user and session user mean an account that is signed in but neither owns the note in question nor moderates; owner is the account that wrote it; moderator is an account in the moderators group that does not own it. Every 401 in it carries a WWW-Authenticate header naming the Token scheme.
| Route and method | anonymous | token user | session user | owner | moderator |
|---|---|---|---|---|---|
| POST /api/token/ | 200 with the key, 400 for wrong credentials | 200 with the key, 400 for wrong credentials | 200 with the key, 400 for wrong credentials | 200 with the key, 400 for wrong credentials | 200 with the key, 400 for wrong credentials |
| GET /api/account/ | 401 | 200, its own address | 200, its own address | 200, its own address | 200, its own address |
| GET /api/notes/ | 200, every note that is not private | 200, the same list | 200, the same list | 200, the same list | 200, the same list |
| GET /api/notes/<pk>/ | 200 | 200 | 200 | 200 | 200 |
| PUT /api/notes/<pk>/ | 401 | 403 | 403 | 200 | 403 |
| PATCH /api/notes/<pk>/ | 401 | 403 | 403 | 200 | 403 |
| DELETE /api/notes/<pk>/ | 401 | 403 | 403 | 204 | 204 |
| GET /api/private/ | 401 | 200, only its own private notes | 200, only its own private notes | 200, only its own private notes | 200, only its own private notes |
| GET /api/private/<pk>/ | 401 | 404 | 404 | 200 | 404 |
1. The schemes the project accepts, in order
- With the project-wide default authentication classes set in REST_FRAMEWORK, an Authorization: Token <key> header resolves request.user to the account that key belongs to, and a session from Django's login flow resolves it to the logged-in account with no Authorization header anywhere.
- A request with neither is refused with 401, and the response carries a WWW-Authenticate header that starts with Token. A key that was never issued is refused the same way.
- One account over the two schemes gets the same answer cell for cell: the same 200s, the same 403s and the same 404 as the table above.
2. The token endpoint
- /api/token/ accepts exactly two fields:
{"email": "ada@example.test", "password": "not-a-secret-1234"}
- Valid credentials answer 200 with the owner's key under the field name token:
{"token": "0a1b2c3d4e5f60718293a4b5c6d7e8f901234567"}
- The key belongs to the account, not to the call: the first valid request for an account creates their key, every later one hands back that same key, and an account never ends up with two. Two accounts get two different keys, and the key the endpoint hands out is the one that then works on the protected routes.
- A request that sends username instead of email is not valid credentials, no matter what address it carries, and neither is a wrong password nor an address nobody signed up with. All three answer 400, carry no token key, and create nothing. The wording of the error is yours.
- The credentials decide the answer and what the caller already holds does not: a client with no credentials, a client already holding a key, a client with a session and a moderator's client all get the same 200 for a valid body and the same 400 for a wrong password.
3. The project default, and the shared record
- DEFAULT_PERMISSION_CLASSES in REST_FRAMEWORK admits signed-in accounts only, so a view declaring nothing of its own is closed to strangers. That default is what protects /api/account/ and the private surface, and it is the reason an anonymous request to either is refused with 401.
- The shared record is the exception and says so on its own view: GET /api/notes/ answers 200 to a client with no account at all, with every note that is not private and no private note at all, and GET /api/notes/<pk>/ answers 200 to that same client.
- Reading is all such a client may do: every unsafe method on a shared note is refused with 401, and the row survives unchanged.
4. The owner rule and the moderators
- IsOwnerOrReadOnly decides what may happen to one already-loaded note: anybody who reaches it may read it, and only the account that owns it may change or remove it. The owner's PUT and PATCH answer 200 and the owner's DELETE answers 204.
- A signed-in account that does not own a shared note reads it and gets 403 on PUT, PATCH and DELETE, with the row left exactly as it was. The answer depends on the note rather than on the account: one account gets 200 patching its own note and 403 patching another's.
- CanDeleteAnyNote asks about the account rather than about the note: an account carrying Django's delete_note permission on Note may send DELETE to any note the shared surface serves, answering 204.
- Nothing in that class may name a person, an address, a group or a flag on the user model. The grant arrives through the group the project ships, so joining it turns the same refused DELETE into a 204 and leaving it revokes the power again, with no code changed either way.
- Safe methods never ask for that permission: an account holding no permission on Note still gets 200 on the shared list, on a shared note, and on HEAD and OPTIONS, in the same breath as its DELETE being refused.
- The permission is no licence to rewrite: PUT and PATCH by a moderator who does not own the note are still 403, and the delete that follows on the same note still answers 204.
- /api/notes/<pk>/ is where the two rules meet. They are alternatives, not conditions to satisfy together.
5. The private surface
- PrivateNoteViewSet serves only the private notes of the account making the request. Another account's private note is never in a list it returns, and neither is one of the requester's own notes that is not private.
- Asking for another account's private note by id answers 404 rather than 403, and asking for one of the requester's own answers 200. A moderator is told 404 too, and its private list is empty, because a permission answers about a row the view already found and cannot conjure one up.
- The scoping lives in the queryset and nowhere else: with the view's permissions relaxed to AllowAny, the same list request still returns the same rows.
- A list request never consults has_object_permission, while the same class on the same view is asked as soon as a request names one row.
- The class-level queryset has no request to work from; the hook that does is the one to override.
Notes
- DRF asks a request four separate questions, each with its own place to be answered, and mixing them up is what produces an API that refuses the wrong people with the wrong number. Who are you? An authentication class. May you call this at all? A permission class's has_permission, asked once before the handler runs, which sees the request and the view and nothing else. May you do that to this row? A permission class's has_object_permission, asked about one already-loaded row, and the only one of the two that can compare that row with the caller. Which rows exist for you? The queryset.
- A view walks its authentication classes in order; the first that recognises the request wins and sets request.user, and one that sees nothing it understands returns None so the next is tried. TokenAuthentication reads an Authorization: Token <key> header and SessionAuthentication reads the cookie Django's login flow set. Neither asks the other's question, so a project that wants both lists both.
- The order decides what a refusal looks like. When nothing authenticated a request that needed a user, DRF asks the first class in the list what challenge to advertise and puts the answer in a WWW-Authenticate header on a 401. SessionAuthentication has no challenge to offer, because a cookie is not something a server can ask for mid-request, so a project listing it first has no header to send and DRF downgrades the same refusal to a 403. This project advertises tokens.
- "Does this account carry a named Django permission" is a fact about the account, so it belongs in has_permission, and request.user.has_perm("<app>.<codename>") answers it from the account's own permissions and from every group it belongs to. A rule written as request.user.is_staff, or as a list of addresses, looks the same in the happy case and cannot be revoked without a deploy.
- permissions.SAFE_METHODS is DRF's tuple of GET, HEAD and OPTIONS. Answering yes for those before the owner is looked at is what keeps a shared record readable.
- permission_classes is an and: every class in the list has to say yes, so two rules that are alternatives cannot be written side by side, because no request could satisfy both. DRF overloads | on permission classes for exactly that, and A | B on the list means either one may admit the request.
- A permission can only say yes or no about a row the view already found, so it cannot hide anything: a row outside the queryset is not refused, it is never found, and the detail route answers 404. That is also why a list request never consults has_object_permission - there is no single object to ask about - and why list visibility is the queryset's job alone. get_queryset runs per request and can read self.request, which the class-level attribute cannot.
- DRF's bundled credential serializer declares a username field, which this user model does not have, so the credentials this project accepts have to be declared somewhere of your own. Get the account from authenticate() rather than looking a row up and calling check_password on it yourself, and hand out keys with get_or_create, never by creating a fresh row per login.
- Only _project/api_settings.py_, app/auth.py, app/permissions.py and app/views.py change, and in _project/api_settings.py_ only the REST_FRAMEWORK dictionary.
- Leave authentication_classes and permission_classes empty on EmailAuthTokenView: a client calling it has no key yet. Leave AccountView exactly as it is, including its lack of permissions, so that the project default is what guards it. Leave the two Note.objects.filter(is_private=False) querysets on the shared views as they are.
- Do not check request.user by hand inside a view handler; a permission class answers before the handler runs, and a queryset decides which rows a request can reach.
- Do not write a migration, a group, an authentication backend or a user model: the group and the permission already exist. Do not reach for pagination, filtering or throttling; no route here takes a query parameter.
