Permalink
Browse files

BACKWARD-INCOMPATIBLE: Tastypie now supports much more granular autho…

…rization checks, as well as saving deeply-nested data.

This patch was over a year in the making. Thanks to Yoav Aner for the report & for security feedback, as well as all the others who reported similar issues.
  • Loading branch information...
1 parent ad5128a commit d850758b088761a00f60a474f5b2d683dc1ec3c0 @toastdriven toastdriven committed Feb 7, 2013
@@ -1,21 +1,15 @@
-.. _authentication_authorization:
+.. _authentication:
-==============================
-Authentication / Authorization
-==============================
+==============
+Authentication
+==============
-Authentication & authorization make up the components needed to verify who a
-certain user is and to validate their access to the API and what they can do
-with it.
+Authentication is the component needed to verify who a
+certain user is and to validate their access to the API.
Authentication answers the question "Who is this person?" This usually involves
requiring credentials, such as an API key or username/password or oAuth tokens.
-Authorization answers the question "Is permission granted for this user to take
-this action?" This usually involves checking permissions such as
-Create/Read/Update/Delete access, or putting limits on what data the user
-can access.
-
Usage
=====
@@ -24,7 +18,6 @@ Using these classes is simple. Simply provide them (or your own class) as a
from django.contrib.auth.models import User
from tastypie.authentication import BasicAuthentication
- from tastypie.authorization import DjangoAuthorization
from tastypie.resources import ModelResource
@@ -35,7 +28,6 @@ Using these classes is simple. Simply provide them (or your own class) as a
excludes = ['email', 'password', 'is_superuser']
# Add it here.
authentication = BasicAuthentication()
- authorization = DjangoAuthorization()
Authentication Options
@@ -189,46 +181,15 @@ attempting each until successfully authenticating. For example::
In the case of an authentication returning a customized HttpUnauthorized, MultiAuthentication defaults to the first returned one. Authentication schemes that need to control the response, such as the included BasicAuthentication and DigestAuthentication, should be placed first.
-Authorization Options
-=====================
-
-Tastypie ships with the following ``Authorization`` classes:
-
-``Authorization``
-~~~~~~~~~~~~~~~~~~
-
-The no-op authorization option, no permissions checks are performed.
-
-.. warning::
-
- This is a potentially dangerous option, as it means *ANY* recognized user
- can modify *ANY* data they encounter in the API. Be careful who you trust.
-
-``ReadOnlyAuthorization``
-~~~~~~~~~~~~~~~~~~~~~~~~~
-
-This authorization class only permits reading data, regardless of what the
-``Resource`` might think is allowed. This is the default ``Authorization``
-class and the safe option.
-
-``DjangoAuthorization``
-~~~~~~~~~~~~~~~~~~~~~~~
-
-The most advanced form of authorization, this checks the permission a user
-has granted to them (via ``django.contrib.auth.models.Permission``). In
-conjunction with the admin, this is a very effective means of control.
-
Implementing Your Own Authentication/Authorization
==================================================
-Implementing your own ``Authentication/Authorization`` classes is a simple
+Implementing your own ``Authentication`` classes is a simple
process. ``Authentication`` has two methods to override (one of which is
-optional but recommended to be customized) and ``Authorization`` has just one
-required method and one optional method::
+optional but recommended to be customized)::
from tastypie.authentication import Authentication
- from tastypie.authorization import Authorization
class SillyAuthentication(Authentication):
@@ -242,22 +203,5 @@ required method and one optional method::
def get_identifier(self, request):
return request.user.username
- class SillyAuthorization(Authorization):
- def is_authorized(self, request, object=None):
- if request.user.date_joined.year == 2010:
- return True
- else:
- return False
-
- # Optional but useful for advanced limiting, such as per user.
- def apply_limits(self, request, object_list):
- if request and hasattr(request, 'user'):
- return object_list.filter(author__username=request.user.username)
-
- return object_list.none()
-
Under this scheme, only users with 'daniel' in their username will be allowed
-in, and only those who joined the site in 2010 will be allowed to affect data.
-
-If the optional ``apply_limits`` method is included, each user that fits the
-above criteria will only be able to access their own records.
+in.
View
@@ -0,0 +1,164 @@
+.. _authorization:
+
+=============
+Authorization
+=============
+
+Authorization is the component needed to verify what someone can do with
+the resources within an API.
+
+Authorization answers the question "Is permission granted for this user to take
+this action?" This usually involves checking permissions such as
+Create/Read/Update/Delete access, or putting limits on what data the user
+can access.
+
+Usage
+=====
+
+Using these classes is simple. Simply provide them (or your own class) as a
+``Meta`` option to the ``Resource`` in question. For example::
+
+ from django.contrib.auth.models import User
+ from tastypie.authorization import DjangoAuthorization
+ from tastypie.resources import ModelResource
+
+
+ class UserResource(ModelResource):
+ class Meta:
+ queryset = User.objects.all()
+ resource_name = 'auth/user'
+ excludes = ['email', 'password', 'is_superuser']
+ # Add it here.
+ authorization = DjangoAuthorization()
+
+
+Authorization Options
+=====================
+
+Tastypie ships with the following ``Authorization`` classes:
+
+``Authorization``
+~~~~~~~~~~~~~~~~~
+
+The no-op authorization option, no permissions checks are performed.
+
+.. warning::
+
+ This is a potentially dangerous option, as it means *ANY* recognized user
+ can modify *ANY* data they encounter in the API. Be careful who you trust.
+
+``ReadOnlyAuthorization``
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+This authorization class only permits reading data, regardless of what the
+``Resource`` might think is allowed. This is the default ``Authorization``
+class and the safe option.
+
+``DjangoAuthorization``
+~~~~~~~~~~~~~~~~~~~~~~~
+
+The most advanced form of authorization, this checks the permission a user
+has granted to them (via ``django.contrib.auth.models.Permission``). In
+conjunction with the admin, this is a very effective means of control.
+
+
+The ``Authorization`` API
+=========================
+
+An ``Authorization``-compatible class implements the following methods:
+
+* ``read_list``
+* ``read_detail``
+* ``create_list``
+* ``create_detail``
+* ``update_list``
+* ``update_detail``
+* ``delete_list``
+* ``delete_detail``
+
+Each method takes two parameters, ``object_list`` & ``bundle``.
+
+``object_list`` is the collection of objects being processed as part of the
+request. **FILTERING** & other restrictions to the set will have already been
+applied prior to this call.
+
+``bundle`` is the populated ``Bundle`` object for the request. You'll likely
+frequently be accessing ``bundle.request.user``, though raw access to the data
+can be helpful.
+
+What you return from the method varies based on the type of method.
+
+Return Values: The List Case
+----------------------------
+
+In the case of the ``*_list`` methods, you'll want to filter the ``object_list``
+& return only the objects the user has access to.
+
+Returning an empty list simply won't allow the action to be applied to any
+objects. However, they will not get a HTTP error status code.
+
+If you'd rather they received an unauthorized status code, raising
+``Unauthorized`` will return a HTTP ``401``.
+
+Return Values: The Detail Case
+------------------------------
+
+In the case of the ``*_detail`` methods, you'll have access to the
+``object_list`` (so you know if a given object fits within the overall set),
+**BUT** you'll want to be inspecting ``bundle.obj`` & either returning
+``True`` if they should be allowed to continue or raising the
+``Unauthorized`` exception if not.
+
+Raising ``Unauthorized`` will cause a HTTP ``401`` error status code in the
+response.
+
+
+Implementing Your Own Authorization
+===================================
+
+Implementing your own ``Authorization`` classes is a relatively simple
+process. Anything that is API-compatible is acceptable, only the method names
+matter to Tastypie.
+
+An example implementation of a user only being able to "their" objects might
+look like::
+
+ 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(user=bundle.request.user)
+
+ def read_detail(self, object_list, bundle):
+ # Is the requested object owned by the user?
+ return bundle.obj.user == bundle.request.user
+
+ def create_list(self, object_list, bundle):
+ # Assuming their auto-assigned to ``user``.
+ return object_list
+
+ def create_detail(self, object_list, bundle):
+ return bundle.obj.user == bundle.request.user
+
+ def update_list(self, object_list, bundle):
+ allowed = []
+
+ # Since they may not all be saved, iterate over them.
+ for obj in object_list:
+ if obj.user == bundle.request.user:
+ allowed.append(obj)
+
+ return allowed
+
+ def update_detail(self, object_list, bundle):
+ return bundle.obj.user == bundle.request.user
+
+ def delete_list(self, object_list, bundle):
+ # Sorry user, no deletes for you!
+ raise Unauthorized("Sorry, no deletes.")
+
+ def delete_detail(self, object_list, bundle):
+ raise Unauthorized("Sorry, no deletes.")
View
@@ -80,7 +80,7 @@ More specifically, this specific ``DatabaseError``::
django.db.utils.DatabaseError: no such table: tastypie_apikey
This is a side effect of the (disabled by default) ``create_api_key`` signal
-as described in the :ref:`authentication_authorization` section of the
+as described in the :ref:`authentication` section of the
documentation when used in conjunction with South.
To work around this issue, you can disable the ``create_api_key`` signal
View
@@ -22,7 +22,8 @@ interfaces.
fields
caching
validation
- authentication_authorization
+ authentication
+ authorization
serialization
throttling
paginator
Oops, something went wrong.

0 comments on commit d850758

Please sign in to comment.