-
Notifications
You must be signed in to change notification settings - Fork 42
20 API Authentication
We will change our API back to the model where a user can only see their own notes.
First we need to deal with authentication. Then we need to handle authorization to indicate that a user can only view their own objects.
In note/api/resources.py
:
Import:
from tastypie.authentication import BasicAuthentication
Then add this into the Meta definitions for both resources:
authentication = BasicAuthentication()
BasicAuthentication uses the Django username/password combo.
You can read more about the authentication options here: http://django-tastypie.readthedocs.org/en/latest/authentication.html#authentication-options
Now that we know we have a valid user (because of the authentication step above), we can restrict what a user is able to see.
First, create a new file at note/api/authorization.py
from tastypie.authorization import Authorization
from tastypie.exceptions import Unauthorized
class UserObjectsOnlyAuthorization(Authorization):
def read_list(self, object_list, bundle):
# This assumes a ``QuerySet`` from ``ModelResource``.
return object_list.filter(owner=bundle.request.user)
def read_detail(self, object_list, bundle):
# Is the requested object owned by the user?
return bundle.obj.owner == bundle.request.user
Note that this is only affecting GET requests. For more information on authorization see the docs here: https://django-tastypie.readthedocs.org/en/latest/authorization.html
Then, in note/api/resources.py
use the new authorization class we created.
Import:
from .authorization import UserObjectsOnlyAuthorization
And add this line into the NoteResource
definition:
authorization = UserObjectsOnlyAuthorization()
Try seeing someone else's notes at: http://localhost:8000/api/v1/note/?format=json&owner__username=SOMEONE_ELSE
It should return an empty list.