Merge branch 'master' into many-fields

This commit is contained in:
Tom Christie 2013-01-26 21:37:43 +00:00
commit b5d8f50f9d
27 changed files with 642 additions and 185 deletions

View File

@ -81,6 +81,21 @@ To run the tests.
# Changelog
### 2.1.17
**Date**: 26th Jan 2013
* Support proper 401 Unauthorized responses where appropriate, instead of always using 403 Forbidden.
* Support json encoding of timedelta objects.
* `format_suffix_patterns()` now supports `include` style URL patterns.
* Bugfix: Fix issues with custom pagination serializers.
* Bugfix: Nested serializers now accept `source='*'` argument.
* Bugfix: Return proper validation errors when incorrect types supplied for relational fields.
* Bugfix: Support nullable FKs with `SlugRelatedField`.
* Bugfix: Don't call custom validation methods if the field has an error.
**Note**: If the primary authentication class is `TokenAuthentication` or `BasicAuthentication`, a view will now correctly return 401 responses to unauthenticated access, with an appropriate `WWW-Authenticate` header, instead of 403 responses.
### 2.1.16
**Date**: 14th Jan 2013
@ -131,20 +146,20 @@ This change will not affect user code, so long as it's following the recommended
* Bugfix: Fix exception in browseable API on DELETE.
* Bugfix: Fix issue where pk was was being set to a string if set by URL kwarg.
## 2.1.11
### 2.1.11
**Date**: 17th Dec 2012
* Bugfix: Fix issue with M2M fields in browseable API.
## 2.1.10
### 2.1.10
**Date**: 17th Dec 2012
* Bugfix: Ensure read-only fields don't have model validation applied.
* Bugfix: Fix hyperlinked fields in paginated results.
## 2.1.9
### 2.1.9
**Date**: 11th Dec 2012
@ -152,14 +167,14 @@ This change will not affect user code, so long as it's following the recommended
* Bugfix: Fix `Meta.fields` only working as tuple not as list.
* Bugfix: Edge case if unnecessarily specifying `required=False` on read only field.
## 2.1.8
### 2.1.8
**Date**: 8th Dec 2012
* Fix for creating nullable Foreign Keys with `''` as well as `None`.
* Added `null=<bool>` related field option.
## 2.1.7
### 2.1.7
**Date**: 7th Dec 2012
@ -171,19 +186,19 @@ This change will not affect user code, so long as it's following the recommended
* Make `Request.user` settable.
* Bugfix: Fix `RegexField` to work with `BrowsableAPIRenderer`
## 2.1.6
### 2.1.6
**Date**: 23rd Nov 2012
* Bugfix: Unfix DjangoModelPermissions. (I am a doofus.)
## 2.1.5
### 2.1.5
**Date**: 23rd Nov 2012
* Bugfix: Fix DjangoModelPermissions.
## 2.1.4
### 2.1.4
**Date**: 22nd Nov 2012
@ -194,7 +209,7 @@ This change will not affect user code, so long as it's following the recommended
* Added `obtain_token_view` to get tokens when using `TokenAuthentication`.
* Bugfix: Django 1.5 configurable user support for `TokenAuthentication`.
## 2.1.3
### 2.1.3
**Date**: 16th Nov 2012
@ -205,14 +220,14 @@ This change will not affect user code, so long as it's following the recommended
* 201 Responses now return a 'Location' header.
* Bugfix: Serializer fields now respect `max_length`.
## 2.1.2
### 2.1.2
**Date**: 9th Nov 2012
* **Filtering support.**
* Bugfix: Support creation of objects with reverse M2M relations.
## 2.1.1
### 2.1.1
**Date**: 7th Nov 2012
@ -222,7 +237,7 @@ This change will not affect user code, so long as it's following the recommended
* Bugfix: Make textareas same width as other fields in browsable API.
* Private API change: `.get_serializer` now uses same `instance` and `data` ordering as serializer initialization.
## 2.1.0
### 2.1.0
**Date**: 5th Nov 2012
@ -235,13 +250,13 @@ This change will not affect user code, so long as it's following the recommended
* Minor field improvements. (Don't stringify dicts, more robust many-pk fields.)
* Bugfixes (Support choice field in Browseable API)
## 2.0.2
### 2.0.2
**Date**: 2nd Nov 2012
* Fix issues with pk related fields in the browsable API.
## 2.0.1
### 2.0.1
**Date**: 1st Nov 2012
@ -249,12 +264,12 @@ This change will not affect user code, so long as it's following the recommended
* Added SlugRelatedField and ManySlugRelatedField.
* If PUT creates an instance return '201 Created', instead of '200 OK'.
## 2.0.0
### 2.0.0
**Date**: 30th Oct 2012
* Redesign of core components.
* Fix **all of the things**.
* **Fix all of the things**.
# License

View File

@ -8,7 +8,7 @@
Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The [permission] and [throttling] policies can then use those credentials to determine if the request should be permitted.
REST framework provides a number of authentication policies out of the box, and also allows you to implement custom policies.
REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.
Authentication will run the first time either the `request.user` or `request.auth` properties are accessed, and determines how those properties are initialized.
@ -16,17 +16,25 @@ The `request.user` property will typically be set to an instance of the `contrib
The `request.auth` property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.
---
**Note:** Don't forget that **authentication by itself won't allow or disallow an incoming request**, it simply identifies the credentials that the request was made with.
For information on how to setup the permission polices for your API please see the [permissions documentation][permission].
---
## How authentication is determined
The authentication policy is always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set `request.user` and `request.auth` using the return value of the first class that successfully authenticates.
The authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set `request.user` and `request.auth` using the return value of the first class that successfully authenticates.
If no class authenticates, `request.user` will be set to an instance of `django.contrib.auth.models.AnonymousUser`, and `request.auth` will be set to `None`.
The value of `request.user` and `request.auth` for unauthenticated requests can be modified using the `UNAUTHENTICATED_USER` and `UNAUTHENTICATED_TOKEN` settings.
## Setting the authentication policy
## Setting the authentication scheme
The default authentication policy may be set globally, using the `DEFAULT_AUTHENTICATION_CLASSES` setting. For example.
The default authentication schemes may be set globally, using the `DEFAULT_AUTHENTICATION` setting. For example.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
@ -35,7 +43,7 @@ The default authentication policy may be set globally, using the `DEFAULT_AUTHEN
)
}
You can also set the authentication policy on a per-view basis, using the `APIView` class based views.
You can also set the authentication scheme on a per-view basis, using the `APIView` class based views.
class ExampleView(APIView):
authentication_classes = (SessionAuthentication, BasicAuthentication)
@ -60,6 +68,19 @@ Or, if you're using the `@api_view` decorator with function based views.
}
return Response(content)
## Unauthorized and Forbidden responses
When an unauthenticated request is denied permission there are two different error codes that may be appropriate.
* [HTTP 401 Unauthorized][http401]
* [HTTP 403 Permission Denied][http403]
HTTP 401 responses must always include a `WWW-Authenticate` header, that instructs the client how to authenticate. HTTP 403 responses do not include the `WWW-Authenticate` header.
The kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. **The first authentication class set on the view is used when determining the type of response**.
Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a `403 Permission Denied` response will always be used, regardless of the authentication scheme.
## Apache mod_wsgi specific configuration
Note that if deploying to [Apache using mod_wsgi][mod_wsgi_official], the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level.
@ -69,24 +90,30 @@ If you are deploying to Apache, and using any non-session based authentication,
# this can go in either server config, virtual host, directory or .htaccess
WSGIPassAuthorization On
---
# API Reference
## BasicAuthentication
This policy uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. Basic authentication is generally only appropriate for testing.
This authentication scheme uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. Basic authentication is generally only appropriate for testing.
If successfully authenticated, `BasicAuthentication` provides the following credentials.
* `request.user` will be a Django `User` instance.
* `request.auth` will be `None`.
Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example:
WWW-Authenticate: Basic realm="api"
**Note:** If you use `BasicAuthentication` in production you must ensure that your API is only available over `https` only. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.
## TokenAuthentication
This policy uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.
This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.
To use the `TokenAuthentication` policy, include `rest_framework.authtoken` in your `INSTALLED_APPS` setting.
To use the `TokenAuthentication` scheme, include `rest_framework.authtoken` in your `INSTALLED_APPS` setting.
You'll also need to create tokens for your users.
@ -102,10 +129,15 @@ For clients to authenticate, the token key should be included in the `Authorizat
If successfully authenticated, `TokenAuthentication` provides the following credentials.
* `request.user` will be a Django `User` instance.
* `request.auth` will be a `rest_framework.tokenauth.models.BasicToken` instance.
* `request.auth` will be a `rest_framework.authtoken.models.BasicToken` instance.
Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example:
WWW-Authenticate: Token
**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https` only.
=======
If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
@receiver(post_save, sender=User)
@ -136,20 +168,35 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
## SessionAuthentication
This policy uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
If successfully authenticated, `SessionAuthentication` provides the following credentials.
* `request.user` will be a Django `User` instance.
* `request.auth` will be `None`.
Unauthenticated responses that are denied permission will result in an `HTTP 403 Forbidden` response.
If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
# Custom authentication
To implement a custom authentication policy, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise.
To implement a custom authentication scheme, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise.
In some circumstances instead of returning `None`, you may want to raise an `AuthenticationFailed` exception from the `.authenticate()` method.
Typically the approach you should take is:
* If authentication is not attempted, return `None`. Any other authentication schemes also in use will still be checked.
* If authentication is attempted but fails, raise a `AuthenticationFailed` exception. An error response will be returned immediately, without checking any other authentication schemes.
You *may* also override the `.authentication_header(self, request)` method. If implemented, it should return a string that will be used as the value of the `WWW-Authenticate` header in a `HTTP 401 Unauthorized` response.
If the `.authentication_header()` method is not overridden, the authentication scheme will return `HTTP 403 Forbidden` responses when an unauthenticated request is denied access.
[cite]: http://jacobian.org/writing/rest-worst-practices/
[http401]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
[http403]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4
[basicauth]: http://tools.ietf.org/html/rfc2617
[oauth]: http://oauth.net/2/
[permission]: permissions.md

View File

@ -53,11 +53,27 @@ Raised if the request contains malformed data when accessing `request.DATA` or `
By default this exception results in a response with the HTTP status code "400 Bad Request".
## AuthenticationFailed
**Signature:** `AuthenticationFailed(detail=None)`
Raised when an incoming request includes incorrect authentication.
By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.
## NotAuthenticated
**Signature:** `NotAuthenticated(detail=None)`
Raised when an unauthenticated request fails the permission checks.
By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.
## PermissionDenied
**Signature:** `PermissionDenied(detail=None)`
Raised when an incoming request fails the permission checks.
Raised when an authenticated request fails the permission checks.
By default this exception results in a response with the HTTP status code "403 Forbidden".
@ -86,3 +102,4 @@ Raised when an incoming request fails the throttling checks.
By default this exception results in a response with the HTTP status code "429 Too Many Requests".
[cite]: http://www.doughellmann.com/articles/how-tos/python-exception-handling/index.html
[authentication]: authentication.md

View File

@ -114,8 +114,8 @@ You can also override the name used for the object list field, by setting the `r
For example, to nest a pair of links labelled 'prev' and 'next', and set the name for the results field to 'objects', you might use something like this.
class LinksSerializer(serializers.Serializer):
next = pagination.NextURLField(source='*')
prev = pagination.PreviousURLField(source='*')
next = pagination.NextPageField(source='*')
prev = pagination.PreviousPageField(source='*')
class CustomPaginationSerializer(pagination.BasePaginationSerializer):
links = LinksSerializer(source='*') # Takes the page object as the source

View File

@ -25,18 +25,29 @@ pre {
margin-top: 9px;
}
body.index-page #main-content p.badges {
padding-bottom: 1px;
}
/* GitHub 'Star' badge */
body.index-page #main-content iframe {
body.index-page #main-content iframe.github-star-button {
float: right;
margin-top: -12px;
margin-right: -15px;
}
/* Tweet button */
body.index-page #main-content iframe.twitter-share-button {
float: right;
margin-top: -12px;
margin-right: 8px;
}
/* Travis CI badge */
body.index-page #main-content p:first-of-type {
body.index-page #main-content img.travis-build-image {
float: right;
margin-right: 8px;
margin-top: -14px;
margin-top: -9px;
margin-bottom: 0px;
}

View File

@ -1,5 +1,11 @@
<iframe src="http://ghbtns.com/github-btn.html?user=tomchristie&amp;repo=django-rest-framework&amp;type=watch&amp;count=true" allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>
[![Travis build image][travis-build-image]][travis]
<p class="badges">
<iframe src="http://ghbtns.com/github-btn.html?user=tomchristie&amp;repo=django-rest-framework&amp;type=watch&amp;count=true" class="github-star-button" allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>
<a href="https://twitter.com/share" class="twitter-share-button" data-url="django-rest-framework.org" data-text="Current status: Checking out the totally awesome Django REST framework! http://django-rest-framework.org" data-count="none">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="http://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
<img alt="Travis build image" src="https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master" class="travis-build-image">
</p>
# Django REST framework
@ -136,6 +142,11 @@ For support please see the [REST framework discussion group][group], try the `#
[Paid support is available][paid-support] from [DabApps][dabapps], and can include work on REST framework core, or support with building your REST framework API. Please [contact DabApps][contact-dabapps] if you'd like to discuss commercial support options.
For updates on REST framework development, you may also want to follow [the author][twitter] on Twitter.
<a style="padding-top: 10px" href="https://twitter.com/_tomchristie" class="twitter-follow-button" data-show-count="false">Follow @_tomchristie</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
## License
Copyright (c) 2011-2013, Tom Christie
@ -215,3 +226,4 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[paid-support]: http://dabapps.com/services/build/api-development/
[dabapps]: http://dabapps.com
[contact-dabapps]: http://dabapps.com/contact/
[twitter]: https://twitter.com/_tomchristie

View File

@ -93,6 +93,9 @@ The following people have helped make REST framework great.
* James Cleveland - [radiosilence]
* Steve Gregory - [steve-gregory]
* Federico Capoano - [nemesisdesign]
* Bruno Renié - [brutasse]
* Kevin Stone - [kevinastone]
* Guglielmo Celata - [guglielmo]
Many thanks to everyone who's contributed to the project.
@ -221,3 +224,6 @@ You can also contact [@_tomchristie][twitter] directly on twitter.
[radiosilence]: https://github.com/radiosilence
[steve-gregory]: https://github.com/steve-gregory
[nemesisdesign]: https://github.com/nemesisdesign
[brutasse]: https://github.com/brutasse
[kevinastone]: https://github.com/kevinastone
[guglielmo]: https://github.com/guglielmo

View File

@ -16,11 +16,20 @@ Major version numbers (x.0.0) are reserved for project milestones. No major poi
## 2.1.x series
### Master
### 2.1.17
**Date**: 26th Jan 2013
* Support proper 401 Unauthorized responses where appropriate, instead of always using 403 Forbidden.
* Support json encoding of timedelta objects.
* `format_suffix_patterns()` now supports `include` style URL patterns.
* Bugfix: Fix issues with custom pagination serializers.
* Bugfix: Nested serializers now accept `source='*'` argument.
* Bugfix: Return proper validation errors when incorrect types supplied for relational fields.
* Bugfix: Support nullable FKs with `SlugRelatedField`.
* Bugfix: Don't call custom validation methods if the field has an error.
**Note**: If the primary authentication class is `TokenAuthentication` or `BasicAuthentication`, a view will now correctly return 401 responses to unauthenticated access, with an appropriate `WWW-Authenticate` header, instead of 403 responses.
### 2.1.16

View File

@ -109,7 +109,7 @@ The first thing we need to get started on our Web API is provide a way of serial
from django.forms import widgets
from rest_framework import serializers
from snippets import models
from snippets.models import Snippet
class SnippetSerializer(serializers.Serializer):
@ -138,7 +138,7 @@ The first thing we need to get started on our Web API is provide a way of serial
return instance
# Create new instance
return models.Snippet(**attrs)
return Snippet(**attrs)
The first part of serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data.

View File

@ -22,7 +22,7 @@ We'd also need to make sure that when the model is saved, that we populate the h
We'll need some extra imports:
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from pygments.formatters.html import HtmlFormatter
from pygments import highlight
And now we can add a `.save()` method to our model class:
@ -54,6 +54,8 @@ You might also want to create a few different users, to use for testing the API.
Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy:
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
snippets = serializers.ManyPrimaryKeyRelatedField()
@ -164,7 +166,8 @@ In the snippets app, create a new file, `permissions.py`
if obj is None:
return True
# Read permissions are allowed to any request
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
@ -188,4 +191,4 @@ We've now got a fairly fine-grained set of permissions on our Web API, and end p
In [part 5][tut-5] of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our hightlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.
[tut-5]: 5-relationships-and-hyperlinked-apis.md
[tut-5]: 5-relationships-and-hyperlinked-apis.md

View File

@ -165,7 +165,7 @@ We've reached the end of our tutorial. If you want to get more involved in the
* Contribute on [GitHub][github] by reviewing and submitting issues, and making pull requests.
* Join the [REST framework discussion group][group], and help build the community.
* [Follow the author on Twitter][twitter] and say hi.
* Follow [the author][twitter] on Twitter and say hi.
**Now go build awesome things.**

View File

@ -1,3 +1,3 @@
__version__ = '2.1.16'
__version__ = '2.1.17'
VERSION = __version__ # synonym

View File

@ -21,32 +21,46 @@ class BaseAuthentication(object):
"""
raise NotImplementedError(".authenticate() must be overridden.")
def authenticate_header(self, request):
"""
Return a string to be used as the value of the `WWW-Authenticate`
header in a `401 Unauthenticated` response, or `None` if the
authentication scheme should return `403 Permission Denied` responses.
"""
pass
class BasicAuthentication(BaseAuthentication):
"""
HTTP Basic authentication against username/password.
"""
www_authenticate_realm = 'api'
def authenticate(self, request):
"""
Returns a `User` if a correct username and password have been supplied
using HTTP Basic authentication. Otherwise returns `None`.
"""
if 'HTTP_AUTHORIZATION' in request.META:
auth = request.META['HTTP_AUTHORIZATION'].split()
if len(auth) == 2 and auth[0].lower() == "basic":
try:
auth_parts = base64.b64decode(auth[1]).partition(':')
except TypeError:
return None
auth = request.META.get('HTTP_AUTHORIZATION', '').split()
try:
userid = smart_unicode(auth_parts[0])
password = smart_unicode(auth_parts[2])
except DjangoUnicodeDecodeError:
return None
if not auth or auth[0].lower() != "basic":
return None
return self.authenticate_credentials(userid, password)
if len(auth) != 2:
raise exceptions.AuthenticationFailed('Invalid basic header')
try:
auth_parts = base64.b64decode(auth[1]).partition(':')
except TypeError:
raise exceptions.AuthenticationFailed('Invalid basic header')
try:
userid = smart_unicode(auth_parts[0])
password = smart_unicode(auth_parts[2])
except DjangoUnicodeDecodeError:
raise exceptions.AuthenticationFailed('Invalid basic header')
return self.authenticate_credentials(userid, password)
def authenticate_credentials(self, userid, password):
"""
@ -55,6 +69,10 @@ class BasicAuthentication(BaseAuthentication):
user = authenticate(username=userid, password=password)
if user is not None and user.is_active:
return (user, None)
raise exceptions.AuthenticationFailed('Invalid username/password')
def authenticate_header(self, request):
return 'Basic realm="%s"' % self.www_authenticate_realm
class SessionAuthentication(BaseAuthentication):
@ -74,7 +92,7 @@ class SessionAuthentication(BaseAuthentication):
# Unauthenticated, CSRF validation not required
if not user or not user.is_active:
return
return None
# Enforce CSRF validation for session based authentication.
class CSRFCheck(CsrfViewMiddleware):
@ -85,7 +103,7 @@ class SessionAuthentication(BaseAuthentication):
reason = CSRFCheck().process_view(http_request, None, (), {})
if reason:
# CSRF failed, bail with explicit error message
raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)
raise exceptions.AuthenticationFailed('CSRF Failed: %s' % reason)
# CSRF passed with authenticated user
return (user, None)
@ -112,14 +130,26 @@ class TokenAuthentication(BaseAuthentication):
def authenticate(self, request):
auth = request.META.get('HTTP_AUTHORIZATION', '').split()
if len(auth) == 2 and auth[0].lower() == "token":
key = auth[1]
try:
token = self.model.objects.get(key=key)
except self.model.DoesNotExist:
return None
if not auth or auth[0].lower() != "token":
return None
if len(auth) != 2:
raise exceptions.AuthenticationFailed('Invalid token header')
return self.authenticate_credentials(auth[1])
def authenticate_credentials(self, key):
try:
token = self.model.objects.get(key=key)
except self.model.DoesNotExist:
raise exceptions.AuthenticationFailed('Invalid token')
if token.user.is_active:
return (token.user, token)
raise exceptions.AuthenticationFailed('User inactive or deleted')
def authenticate_header(self, request):
return 'Token'
if token.user.is_active:
return (token.user, token)
# TODO: OAuthAuthentication

View File

@ -1,4 +1,5 @@
from rest_framework.views import APIView
import types
def api_view(http_method_names):
@ -23,6 +24,14 @@ def api_view(http_method_names):
# pass
# WrappedAPIView.__doc__ = func.doc <--- Not possible to do this
# api_view applied without (method_names)
assert not(isinstance(http_method_names, types.FunctionType)), \
'@api_view missing list of allowed HTTP methods'
# api_view applied with eg. string instead of list of strings
assert isinstance(http_method_names, (list, tuple)), \
'@api_view expected a list of strings, recieved %s' % type(http_method_names).__name__
allowed_methods = set(http_method_names) | set(('options',))
WrappedAPIView.http_method_names = [method.lower() for method in allowed_methods]

View File

@ -23,6 +23,22 @@ class ParseError(APIException):
self.detail = detail or self.default_detail
class AuthenticationFailed(APIException):
status_code = status.HTTP_401_UNAUTHORIZED
default_detail = 'Incorrect authentication credentials.'
def __init__(self, detail=None):
self.detail = detail or self.default_detail
class NotAuthenticated(APIException):
status_code = status.HTTP_401_UNAUTHORIZED
default_detail = 'Authentication credentials were not provided.'
def __init__(self, detail=None):
self.detail = detail or self.default_detail
class PermissionDenied(APIException):
status_code = status.HTTP_403_FORBIDDEN
default_detail = 'You do not have permission to perform this action.'

View File

@ -34,6 +34,17 @@ class PreviousPageField(serializers.Field):
return replace_query_param(url, self.page_field, page)
class DefaultObjectSerializer(serializers.Field):
"""
If no object serializer is specified, then this serializer will be applied
as the default.
"""
def __init__(self, source=None, context=None):
# Note: Swallow context kwarg - only required for eg. ModelSerializer.
super(DefaultObjectSerializer, self).__init__(source=source)
class PaginationSerializerOptions(serializers.SerializerOptions):
"""
An object that stores the options that may be provided to a
@ -44,7 +55,7 @@ class PaginationSerializerOptions(serializers.SerializerOptions):
def __init__(self, meta):
super(PaginationSerializerOptions, self).__init__(meta)
self.object_serializer_class = getattr(meta, 'object_serializer_class',
serializers.Field)
DefaultObjectSerializer)
class BasePaginationSerializer(serializers.Serializer):
@ -62,14 +73,13 @@ class BasePaginationSerializer(serializers.Serializer):
super(BasePaginationSerializer, self).__init__(*args, **kwargs)
results_field = self.results_field
object_serializer = self.opts.object_serializer_class
self.fields[results_field] = object_serializer(source='object_list')
def to_native(self, obj):
"""
Prevent default behaviour of iterating over elements, and serializing
each in turn.
"""
return self.convert_object(obj)
if 'context' in kwargs:
context_kwarg = {'context': kwargs['context']}
else:
context_kwarg = {}
self.fields[results_field] = object_serializer(source='object_list', **context_kwarg)
class PaginationSerializer(BasePaginationSerializer):

View File

@ -86,6 +86,7 @@ class Request(object):
self._method = Empty
self._content_type = Empty
self._stream = Empty
self._authenticator = None
if self.parser_context is None:
self.parser_context = {}
@ -166,7 +167,7 @@ class Request(object):
by the authentication classes provided to the request.
"""
if not hasattr(self, '_user'):
self._user, self._auth = self._authenticate()
self._authenticator, self._user, self._auth = self._authenticate()
return self._user
@user.setter
@ -185,7 +186,7 @@ class Request(object):
request, such as an authentication token.
"""
if not hasattr(self, '_auth'):
self._user, self._auth = self._authenticate()
self._authenticator, self._user, self._auth = self._authenticate()
return self._auth
@auth.setter
@ -196,6 +197,14 @@ class Request(object):
"""
self._auth = value
@property
def successful_authenticator(self):
"""
Return the instance of the authentication instance class that was used
to authenticate the request, or `None`.
"""
return self._authenticator
def _load_data_and_files(self):
"""
Parses the request content into self.DATA and self.FILES.
@ -299,21 +308,23 @@ class Request(object):
def _authenticate(self):
"""
Attempt to authenticate the request using each authentication instance in turn.
Returns a two-tuple of (user, authtoken).
Attempt to authenticate the request using each authentication instance
in turn.
Returns a three-tuple of (authenticator, user, authtoken).
"""
for authenticator in self.authenticators:
user_auth_tuple = authenticator.authenticate(self)
if not user_auth_tuple is None:
return user_auth_tuple
user, auth = user_auth_tuple
return (authenticator, user, auth)
return self._not_authenticated()
def _not_authenticated(self):
"""
Return a two-tuple of (user, authtoken), representing an
unauthenticated request.
Return a three-tuple of (authenticator, user, authtoken), representing
an unauthenticated request.
By default this will be (AnonymousUser, None).
By default this will be (None, AnonymousUser, None).
"""
if api_settings.UNAUTHENTICATED_USER:
user = api_settings.UNAUTHENTICATED_USER()
@ -325,7 +336,7 @@ class Request(object):
else:
auth = None
return (user, auth)
return (None, user, auth)
def __getattr__(self, attr):
"""

View File

@ -2,6 +2,7 @@ import copy
import datetime
import types
from decimal import Decimal
from django.core.paginator import Page
from django.db import models
from django.forms import widgets
from django.utils.datastructures import SortedDict
@ -227,6 +228,8 @@ class BaseSerializer(Field):
Run `validate_<fieldname>()` and `validate()` methods on the serializer
"""
for field_name, field in self.fields.items():
if field_name in self._errors:
continue
try:
validate_method = getattr(self, 'validate_%s' % field_name, None)
if validate_method:
@ -271,7 +274,11 @@ class BaseSerializer(Field):
"""
Serialize objects -> primitives.
"""
if hasattr(obj, '__iter__'):
# Note: At the moment we have an ugly hack to determine if we should
# walk over iterables. At some point, serializers will require an
# explicit `many=True` in order to iterate over a set, and this hack
# will disappear.
if hasattr(obj, '__iter__') and not isinstance(obj, Page):
return [self.convert_object(item) for item in obj]
return self.convert_object(obj)
@ -298,6 +305,9 @@ class BaseSerializer(Field):
Override default so that we can apply ModelSerializer as a nested
field to relationships.
"""
if self.source == '*':
return self.to_native(obj)
try:
if self.source:
for component in self.source.split('.'):

View File

@ -4,7 +4,7 @@ from django.test import Client, TestCase
from rest_framework import permissions
from rest_framework.authtoken.models import Token
from rest_framework.authentication import TokenAuthentication
from rest_framework.authentication import TokenAuthentication, BasicAuthentication, SessionAuthentication
from rest_framework.compat import patterns
from rest_framework.views import APIView
@ -21,10 +21,10 @@ class MockView(APIView):
def put(self, request):
return HttpResponse({'a': 1, 'b': 2, 'c': 3})
MockView.authentication_classes += (TokenAuthentication,)
urlpatterns = patterns('',
(r'^$', MockView.as_view()),
(r'^session/$', MockView.as_view(authentication_classes=[SessionAuthentication])),
(r'^basic/$', MockView.as_view(authentication_classes=[BasicAuthentication])),
(r'^token/$', MockView.as_view(authentication_classes=[TokenAuthentication])),
(r'^auth-token/$', 'rest_framework.authtoken.views.obtain_auth_token'),
)
@ -43,24 +43,25 @@ class BasicAuthTests(TestCase):
def test_post_form_passing_basic_auth(self):
"""Ensure POSTing json over basic auth with correct credentials passes and does not require CSRF"""
auth = 'Basic %s' % base64.encodestring('%s:%s' % (self.username, self.password)).strip()
response = self.csrf_client.post('/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
response = self.csrf_client.post('/basic/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200)
def test_post_json_passing_basic_auth(self):
"""Ensure POSTing form over basic auth with correct credentials passes and does not require CSRF"""
auth = 'Basic %s' % base64.encodestring('%s:%s' % (self.username, self.password)).strip()
response = self.csrf_client.post('/', json.dumps({'example': 'example'}), 'application/json', HTTP_AUTHORIZATION=auth)
response = self.csrf_client.post('/basic/', json.dumps({'example': 'example'}), 'application/json', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200)
def test_post_form_failing_basic_auth(self):
"""Ensure POSTing form over basic auth without correct credentials fails"""
response = self.csrf_client.post('/', {'example': 'example'})
self.assertEqual(response.status_code, 403)
response = self.csrf_client.post('/basic/', {'example': 'example'})
self.assertEqual(response.status_code, 401)
def test_post_json_failing_basic_auth(self):
"""Ensure POSTing json over basic auth without correct credentials fails"""
response = self.csrf_client.post('/', json.dumps({'example': 'example'}), 'application/json')
self.assertEqual(response.status_code, 403)
response = self.csrf_client.post('/basic/', json.dumps({'example': 'example'}), 'application/json')
self.assertEqual(response.status_code, 401)
self.assertEqual(response['WWW-Authenticate'], 'Basic realm="api"')
class SessionAuthTests(TestCase):
@ -83,7 +84,7 @@ class SessionAuthTests(TestCase):
Ensure POSTing form over session authentication without CSRF token fails.
"""
self.csrf_client.login(username=self.username, password=self.password)
response = self.csrf_client.post('/', {'example': 'example'})
response = self.csrf_client.post('/session/', {'example': 'example'})
self.assertEqual(response.status_code, 403)
def test_post_form_session_auth_passing(self):
@ -91,7 +92,7 @@ class SessionAuthTests(TestCase):
Ensure POSTing form over session authentication with logged in user and CSRF token passes.
"""
self.non_csrf_client.login(username=self.username, password=self.password)
response = self.non_csrf_client.post('/', {'example': 'example'})
response = self.non_csrf_client.post('/session/', {'example': 'example'})
self.assertEqual(response.status_code, 200)
def test_put_form_session_auth_passing(self):
@ -99,14 +100,14 @@ class SessionAuthTests(TestCase):
Ensure PUTting form over session authentication with logged in user and CSRF token passes.
"""
self.non_csrf_client.login(username=self.username, password=self.password)
response = self.non_csrf_client.put('/', {'example': 'example'})
response = self.non_csrf_client.put('/session/', {'example': 'example'})
self.assertEqual(response.status_code, 200)
def test_post_form_session_auth_failing(self):
"""
Ensure POSTing form over session authentication without logged in user fails.
"""
response = self.csrf_client.post('/', {'example': 'example'})
response = self.csrf_client.post('/session/', {'example': 'example'})
self.assertEqual(response.status_code, 403)
@ -127,24 +128,24 @@ class TokenAuthTests(TestCase):
def test_post_form_passing_token_auth(self):
"""Ensure POSTing json over token auth with correct credentials passes and does not require CSRF"""
auth = "Token " + self.key
response = self.csrf_client.post('/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
response = self.csrf_client.post('/token/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200)
def test_post_json_passing_token_auth(self):
"""Ensure POSTing form over token auth with correct credentials passes and does not require CSRF"""
auth = "Token " + self.key
response = self.csrf_client.post('/', json.dumps({'example': 'example'}), 'application/json', HTTP_AUTHORIZATION=auth)
response = self.csrf_client.post('/token/', json.dumps({'example': 'example'}), 'application/json', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200)
def test_post_form_failing_token_auth(self):
"""Ensure POSTing form over token auth without correct credentials fails"""
response = self.csrf_client.post('/', {'example': 'example'})
self.assertEqual(response.status_code, 403)
response = self.csrf_client.post('/token/', {'example': 'example'})
self.assertEqual(response.status_code, 401)
def test_post_json_failing_token_auth(self):
"""Ensure POSTing json over token auth without correct credentials fails"""
response = self.csrf_client.post('/', json.dumps({'example': 'example'}), 'application/json')
self.assertEqual(response.status_code, 403)
response = self.csrf_client.post('/token/', json.dumps({'example': 'example'}), 'application/json')
self.assertEqual(response.status_code, 401)
def test_token_has_auto_assigned_key_if_none_provided(self):
"""Ensure creating a token with no key will auto-assign a key"""

View File

@ -28,13 +28,27 @@ class DecoratorTestCase(TestCase):
response.request = request
return APIView.finalize_response(self, request, response, *args, **kwargs)
def test_wrap_view(self):
def test_api_view_incorrect(self):
"""
If @api_view is not applied correct, we should raise an assertion.
"""
@api_view(['GET'])
@api_view
def view(request):
return Response({})
return Response()
self.assertTrue(isinstance(view.cls_instance, APIView))
request = self.factory.get('/')
self.assertRaises(AssertionError, view, request)
def test_api_view_incorrect_arguments(self):
"""
If @api_view is missing arguments, we should raise an assertion.
"""
with self.assertRaises(AssertionError):
@api_view('GET')
def view(request):
return Response()
def test_calling_method(self):

View File

@ -1,25 +1,61 @@
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.generic import GenericRelation, GenericForeignKey
from django.db import models
from django.test import TestCase
from rest_framework import serializers
from rest_framework.tests.models import *
class Tag(models.Model):
"""
Tags have a descriptive slug, and are attached to an arbitrary object.
"""
tag = models.SlugField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
tagged_item = GenericForeignKey('content_type', 'object_id')
def __unicode__(self):
return self.tag
class Bookmark(models.Model):
"""
A URL bookmark that may have multiple tags attached.
"""
url = models.URLField()
tags = GenericRelation(Tag)
def __unicode__(self):
return 'Bookmark: %s' % self.url
class Note(models.Model):
"""
A textual note that may have multiple tags attached.
"""
text = models.TextField()
tags = GenericRelation(Tag)
def __unicode__(self):
return 'Note: %s' % self.text
class TestGenericRelations(TestCase):
def setUp(self):
bookmark = Bookmark(url='https://www.djangoproject.com/')
bookmark.save()
django = Tag(tag_name='django')
django.save()
python = Tag(tag_name='python')
python.save()
t1 = TaggedItem(content_object=bookmark, tag=django)
t1.save()
t2 = TaggedItem(content_object=bookmark, tag=python)
t2.save()
self.bookmark = bookmark
self.bookmark = Bookmark.objects.create(url='https://www.djangoproject.com/')
Tag.objects.create(tagged_item=self.bookmark, tag='django')
Tag.objects.create(tagged_item=self.bookmark, tag='python')
self.note = Note.objects.create(text='Remember the milk')
Tag.objects.create(tagged_item=self.note, tag='reminder')
def test_generic_relation(self):
"""
Test a relationship that spans a GenericRelation field.
IE. A reverse generic relationship.
"""
def test_reverse_generic_relation(self):
class BookmarkSerializer(serializers.ModelSerializer):
tags = serializers.ManyRelatedField(source='tags')
tags = serializers.ManyRelatedField()
class Meta:
model = Bookmark
@ -31,3 +67,33 @@ class TestGenericRelations(TestCase):
'url': u'https://www.djangoproject.com/'
}
self.assertEquals(serializer.data, expected)
def test_generic_fk(self):
"""
Test a relationship that spans a GenericForeignKey field.
IE. A forward generic relationship.
"""
class TagSerializer(serializers.ModelSerializer):
tagged_item = serializers.RelatedField()
class Meta:
model = Tag
exclude = ('id', 'content_type', 'object_id')
serializer = TagSerializer(Tag.objects.all())
expected = [
{
'tag': u'django',
'tagged_item': u'Bookmark: https://www.djangoproject.com/'
},
{
'tag': u'python',
'tagged_item': u'Bookmark: https://www.djangoproject.com/'
},
{
'tag': u'reminder',
'tagged_item': u'Note: Remember the milk'
}
]
self.assertEquals(serializer.data, expected)

View File

@ -86,27 +86,6 @@ class ReadOnlyManyToManyModel(RESTFrameworkModel):
text = models.CharField(max_length=100, default='anchor')
rel = models.ManyToManyField(Anchor)
# Models to test generic relations
class Tag(RESTFrameworkModel):
tag_name = models.SlugField()
class TaggedItem(RESTFrameworkModel):
tag = models.ForeignKey(Tag, related_name='items')
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
def __unicode__(self):
return self.tag.tag_name
class Bookmark(RESTFrameworkModel):
url = models.URLField()
tags = GenericRelation(TaggedItem)
# Model to test filtering.
class FilterableItem(RESTFrameworkModel):

View File

@ -252,6 +252,8 @@ class TestCustomPaginateByParam(TestCase):
self.assertEquals(response.data['results'], self.data[:5])
### Tests for context in pagination serializers
class CustomField(serializers.Field):
def to_native(self, value):
if not 'view' in self.context:
@ -262,6 +264,11 @@ class CustomField(serializers.Field):
class BasicModelSerializer(serializers.Serializer):
text = CustomField()
def __init__(self, *args, **kwargs):
super(BasicModelSerializer, self).__init__(*args, **kwargs)
if not 'view' in self.context:
raise RuntimeError("context isn't getting passed into serializer init")
class TestContextPassedToCustomField(TestCase):
def setUp(self):
@ -279,3 +286,39 @@ class TestContextPassedToCustomField(TestCase):
self.assertEquals(response.status_code, status.HTTP_200_OK)
### Tests for custom pagination serializers
class LinksSerializer(serializers.Serializer):
next = pagination.NextPageField(source='*')
prev = pagination.PreviousPageField(source='*')
class CustomPaginationSerializer(pagination.BasePaginationSerializer):
links = LinksSerializer(source='*') # Takes the page object as the source
total_results = serializers.Field(source='paginator.count')
results_field = 'objects'
class TestCustomPaginationSerializer(TestCase):
def setUp(self):
objects = ['john', 'paul', 'george', 'ringo']
paginator = Paginator(objects, 2)
self.page = paginator.page(1)
def test_custom_pagination_serializer(self):
request = RequestFactory().get('/foobar')
serializer = CustomPaginationSerializer(
instance=self.page,
context={'request': request}
)
expected = {
'links': {
'next': 'http://testserver/foobar?page=2',
'prev': None
},
'total_results': 4,
'objects': ['john', 'paul']
}
self.assertEquals(serializer.data, expected)

View File

@ -163,7 +163,6 @@ class BasicTests(TestCase):
"""
Attempting to update fields set as read_only should have no effect.
"""
serializer = PersonSerializer(self.person, data={'name': 'dwight', 'age': 99})
self.assertEquals(serializer.is_valid(), True)
instance = serializer.save()
@ -184,8 +183,7 @@ class ValidationTests(TestCase):
'content': 'x' * 1001,
'created': datetime.datetime(2012, 1, 1)
}
self.actionitem = ActionItem(title='Some to do item',
)
self.actionitem = ActionItem(title='Some to do item',)
def test_create(self):
serializer = CommentSerializer(data=self.data)
@ -217,31 +215,6 @@ class ValidationTests(TestCase):
self.assertEquals(serializer.is_valid(), True)
self.assertEquals(serializer.errors, {})
def test_field_validation(self):
class CommentSerializerWithFieldValidator(CommentSerializer):
def validate_content(self, attrs, source):
value = attrs[source]
if "test" not in value:
raise serializers.ValidationError("Test not in value")
return attrs
data = {
'email': 'tom@example.com',
'content': 'A test comment',
'created': datetime.datetime(2012, 1, 1)
}
serializer = CommentSerializerWithFieldValidator(data=data)
self.assertTrue(serializer.is_valid())
data['content'] = 'This should not validate'
serializer = CommentSerializerWithFieldValidator(data=data)
self.assertFalse(serializer.is_valid())
self.assertEquals(serializer.errors, {'content': [u'Test not in value']})
def test_bad_type_data_is_false(self):
"""
Data of the wrong type is not valid.
@ -311,12 +284,69 @@ class ValidationTests(TestCase):
self.assertEquals(serializer.errors, {'info': [u'Ensure this value has at most 12 characters (it has 13).']})
class CustomValidationTests(TestCase):
class CommentSerializerWithFieldValidator(CommentSerializer):
def validate_email(self, attrs, source):
value = attrs[source]
return attrs
def validate_content(self, attrs, source):
value = attrs[source]
if "test" not in value:
raise serializers.ValidationError("Test not in value")
return attrs
def test_field_validation(self):
data = {
'email': 'tom@example.com',
'content': 'A test comment',
'created': datetime.datetime(2012, 1, 1)
}
serializer = self.CommentSerializerWithFieldValidator(data=data)
self.assertTrue(serializer.is_valid())
data['content'] = 'This should not validate'
serializer = self.CommentSerializerWithFieldValidator(data=data)
self.assertFalse(serializer.is_valid())
self.assertEquals(serializer.errors, {'content': [u'Test not in value']})
def test_missing_data(self):
"""
Make sure that validate_content isn't called if the field is missing
"""
incomplete_data = {
'email': 'tom@example.com',
'created': datetime.datetime(2012, 1, 1)
}
serializer = self.CommentSerializerWithFieldValidator(data=incomplete_data)
self.assertFalse(serializer.is_valid())
self.assertEquals(serializer.errors, {'content': [u'This field is required.']})
def test_wrong_data(self):
"""
Make sure that validate_content isn't called if the field input is wrong
"""
wrong_data = {
'email': 'not an email',
'content': 'A test comment',
'created': datetime.datetime(2012, 1, 1)
}
serializer = self.CommentSerializerWithFieldValidator(data=wrong_data)
self.assertFalse(serializer.is_valid())
self.assertEquals(serializer.errors, {'email': [u'Enter a valid e-mail address.']})
class PositiveIntegerAsChoiceTests(TestCase):
def test_positive_integer_in_json_is_correctly_parsed(self):
data = {'some_integer':1}
data = {'some_integer': 1}
serializer = PositiveIntegerAsChoiceSerializer(data=data)
self.assertEquals(serializer.is_valid(), True)
class ModelValidationTests(TestCase):
def test_validate_unique(self):
"""

View File

@ -0,0 +1,78 @@
from collections import namedtuple
from django.core import urlresolvers
from django.test import TestCase
from django.test.client import RequestFactory
from rest_framework.compat import patterns, url, include
from rest_framework.urlpatterns import format_suffix_patterns
# A container class for test paths for the test case
URLTestPath = namedtuple('URLTestPath', ['path', 'args', 'kwargs'])
def dummy_view(request, *args, **kwargs):
pass
class FormatSuffixTests(TestCase):
"""
Tests `format_suffix_patterns` against different URLPatterns to ensure the URLs still resolve properly, including any captured parameters.
"""
def _resolve_urlpatterns(self, urlpatterns, test_paths):
factory = RequestFactory()
try:
urlpatterns = format_suffix_patterns(urlpatterns)
except:
self.fail("Failed to apply `format_suffix_patterns` on the supplied urlpatterns")
resolver = urlresolvers.RegexURLResolver(r'^/', urlpatterns)
for test_path in test_paths:
request = factory.get(test_path.path)
try:
callback, callback_args, callback_kwargs = resolver.resolve(request.path_info)
except:
self.fail("Failed to resolve URL: %s" % request.path_info)
self.assertEquals(callback_args, test_path.args)
self.assertEquals(callback_kwargs, test_path.kwargs)
def test_format_suffix(self):
urlpatterns = patterns(
'',
url(r'^test$', dummy_view),
)
test_paths = [
URLTestPath('/test', (), {}),
URLTestPath('/test.api', (), {'format': 'api'}),
URLTestPath('/test.asdf', (), {'format': 'asdf'}),
]
self._resolve_urlpatterns(urlpatterns, test_paths)
def test_default_args(self):
urlpatterns = patterns(
'',
url(r'^test$', dummy_view, {'foo': 'bar'}),
)
test_paths = [
URLTestPath('/test', (), {'foo': 'bar', }),
URLTestPath('/test.api', (), {'foo': 'bar', 'format': 'api'}),
URLTestPath('/test.asdf', (), {'foo': 'bar', 'format': 'asdf'}),
]
self._resolve_urlpatterns(urlpatterns, test_paths)
def test_included_urls(self):
nested_patterns = patterns(
'',
url(r'^path$', dummy_view)
)
urlpatterns = patterns(
'',
url(r'^test/', include(nested_patterns), {'foo': 'bar'}),
)
test_paths = [
URLTestPath('/test/path', (), {'foo': 'bar', }),
URLTestPath('/test/path.api', (), {'foo': 'bar', 'format': 'api'}),
URLTestPath('/test/path.asdf', (), {'foo': 'bar', 'format': 'asdf'}),
]
self._resolve_urlpatterns(urlpatterns, test_paths)

View File

@ -1,5 +1,35 @@
from rest_framework.compat import url
from rest_framework.compat import url, include
from rest_framework.settings import api_settings
from django.core.urlresolvers import RegexURLResolver
def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required):
ret = []
for urlpattern in urlpatterns:
if isinstance(urlpattern, RegexURLResolver):
# Set of included URL patterns
regex = urlpattern.regex.pattern
namespace = urlpattern.namespace
app_name = urlpattern.app_name
kwargs = urlpattern.default_kwargs
# Add in the included patterns, after applying the suffixes
patterns = apply_suffix_patterns(urlpattern.url_patterns,
suffix_pattern,
suffix_required)
ret.append(url(regex, include(patterns, namespace, app_name), kwargs))
else:
# Regular URL pattern
regex = urlpattern.regex.pattern.rstrip('$') + suffix_pattern
view = urlpattern._callback or urlpattern._callback_str
kwargs = urlpattern.default_args
name = urlpattern.name
# Add in both the existing and the new urlpattern
if not suffix_required:
ret.append(urlpattern)
ret.append(url(regex, view, kwargs, name))
return ret
def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None):
@ -28,15 +58,4 @@ def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None):
else:
suffix_pattern = r'\.(?P<%s>[a-z]+)$' % suffix_kwarg
ret = []
for urlpattern in urlpatterns:
# Form our complementing '.format' urlpattern
regex = urlpattern.regex.pattern.rstrip('$') + suffix_pattern
view = urlpattern._callback or urlpattern._callback_str
kwargs = urlpattern.default_args
name = urlpattern.name
# Add in both the existing and the new urlpattern
if not suffix_required:
ret.append(urlpattern)
ret.append(url(regex, view, kwargs, name))
return ret
return apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required)

View File

@ -148,6 +148,8 @@ class APIView(View):
"""
If request is not permitted, determine what kind of exception to raise.
"""
if not self.request.successful_authenticator:
raise exceptions.NotAuthenticated()
raise exceptions.PermissionDenied()
def throttled(self, request, wait):
@ -156,6 +158,15 @@ class APIView(View):
"""
raise exceptions.Throttled(wait)
def get_authenticate_header(self, request):
"""
If a request is unauthenticated, determine the WWW-Authenticate
header to use for 401 responses, if any.
"""
authenticators = self.get_authenticators()
if authenticators:
return authenticators[0].authenticate_header(request)
def get_parser_context(self, http_request):
"""
Returns a dict that is passed through to Parser.parse(),
@ -319,6 +330,16 @@ class APIView(View):
# Throttle wait header
self.headers['X-Throttle-Wait-Seconds'] = '%d' % exc.wait
if isinstance(exc, (exceptions.NotAuthenticated,
exceptions.AuthenticationFailed)):
# WWW-Authenticate header for 401 responses, else coerce to 403
auth_header = self.get_authenticate_header(self.request)
if auth_header:
self.headers['WWW-Authenticate'] = auth_header
else:
exc.status_code = status.HTTP_403_FORBIDDEN
if isinstance(exc, exceptions.APIException):
return Response({'detail': exc.detail},
status=exc.status_code,