From bd8360c826b7a922eeb6226beb17853cfadb466c Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 17 Oct 2012 14:02:30 +0100 Subject: [PATCH 01/44] Highlight use of permissions alnog with authentication --- docs/api-guide/authentication.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 71f481637..959feaa6d 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -16,6 +16,12 @@ 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 wont 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. From 4c17d1441f184eabea9000155f07445bcc2aa14c Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 17 Oct 2012 14:59:37 +0100 Subject: [PATCH 02/44] Add `Unauthenticated` exception. --- docs/api-guide/exceptions.md | 13 +++++++++++-- rest_framework/exceptions.py | 8 ++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index c3bdb7b92..f5dff94af 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -49,11 +49,19 @@ 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". +## Unauthenticated + +**Signature:** `Unauthenticated(detail=None)` + +Raised when an unauthenticated incoming 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 incoming request fails the permission checks. By default this exception results in a response with the HTTP status code "403 Forbidden". @@ -81,4 +89,5 @@ 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 \ No newline at end of file +[cite]: http://www.doughellmann.com/articles/how-tos/python-exception-handling/index.html +[authentication]: authentication.md \ No newline at end of file diff --git a/rest_framework/exceptions.py b/rest_framework/exceptions.py index 572425b99..1597da612 100644 --- a/rest_framework/exceptions.py +++ b/rest_framework/exceptions.py @@ -23,6 +23,14 @@ class ParseError(APIException): self.detail = detail or self.default_detail +class Unauthenticated(APIException): + status_code = status.HTTP_401_UNAUTHENTICATED + default_detail = 'Incorrect or absent authentication credentials.' + + 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.' From 5ae49a4ec4ccfdab13bc848ecd175d44ecaf4ed1 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 17 Oct 2012 14:59:53 +0100 Subject: [PATCH 03/44] Add docs for 401 vs 403 responses --- docs/api-guide/authentication.md | 72 +++++++++++++++++++++++++------- rest_framework/authentication.py | 8 ++++ 2 files changed, 66 insertions(+), 14 deletions(-) diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 959feaa6d..9c61c25f7 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -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. @@ -18,21 +18,21 @@ The `request.auth` property is used for any additional authentication informatio --- -**Note:** Don't forget that authentication by itself wont 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]. +**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` setting. For example. +The default authentication schemes may be set globally, using the `DEFAULT_AUTHENTICATION` setting. For example. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION': ( @@ -41,7 +41,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, UserBasicAuthentication) @@ -66,24 +66,43 @@ 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] + +The kind of response that will be used depends on the type of authentication scheme in use, and the ordering of the authentication classes. + +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 given priority when determining the type of response**. + +Note that when a *successfully authenticated* request is denied permission, a `403 Permission Denied` response will always be used, regardless of the authentication scheme. + +--- + # 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.contrib.auth.models.User` instance. * `request.auth` will be `None`. +Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthenticated` 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. @@ -101,31 +120,56 @@ If successfully authenticated, `TokenAuthentication` provides the following cred * `request.user` will be a `django.contrib.auth.models.User` instance. * `request.auth` will be a `rest_framework.tokenauth.models.BasicToken` instance. +Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthenticated` 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. -## OAuthAuthentication +## OAuth2Authentication -This policy uses the [OAuth 2.0][oauth] protocol to authenticate requests. OAuth is appropriate for server-server setups, such as when you want to allow a third-party service to access your API on a user's behalf. +This authentication scheme uses the [OAuth 2.0][oauth] protocol to authenticate requests. OAuth is appropriate for server-server setups, such as when you want to allow a third-party service to access your API on a user's behalf. -If successfully authenticated, `OAuthAuthentication` provides the following credentials. +If successfully authenticated, `OAuth2Authentication` provides the following credentials. * `request.user` will be a `django.contrib.auth.models.User` instance. * `request.auth` will be a `rest_framework.models.OAuthToken` instance. +**TODO**: Note type of response (401 vs 403) + +**TODO**: Implement OAuth2Authentication, using django-oauth2-provider. + ## 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.contrib.auth.models.User` instance. * `request.auth` will be `None`. +Unauthenticated responses that are denied permission will result in an `HTTP 403 Forbidden` response. + +--- + # 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 `Unauthenticated` 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 an `Unauthenticated` 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 Unauthenticated` 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 diff --git a/rest_framework/authentication.py b/rest_framework/authentication.py index 30c78ebc8..e557abedf 100644 --- a/rest_framework/authentication.py +++ b/rest_framework/authentication.py @@ -21,6 +21,14 @@ 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): """ From dc9384f9b4321f099e380f6b4a04fbe2eeb2b743 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 17 Oct 2012 15:09:20 +0100 Subject: [PATCH 04/44] Use correct status code --- rest_framework/exceptions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/exceptions.py b/rest_framework/exceptions.py index 1597da612..2461cacdf 100644 --- a/rest_framework/exceptions.py +++ b/rest_framework/exceptions.py @@ -24,7 +24,7 @@ class ParseError(APIException): class Unauthenticated(APIException): - status_code = status.HTTP_401_UNAUTHENTICATED + status_code = status.HTTP_401_UNAUTHORIZED default_detail = 'Incorrect or absent authentication credentials.' def __init__(self, detail=None): From a4d500ba107466e8d44a82ed8ca632a3ea81a016 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 17 Oct 2012 15:10:11 +0100 Subject: [PATCH 05/44] Use correct status code --- docs/api-guide/authentication.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 9c61c25f7..06f428c0c 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -92,7 +92,7 @@ If successfully authenticated, `BasicAuthentication` provides the following cred * `request.user` will be a `django.contrib.auth.models.User` instance. * `request.auth` will be `None`. -Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthenticated` response with an appropriate WWW-Authenticate header. For example: +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" @@ -120,7 +120,7 @@ If successfully authenticated, `TokenAuthentication` provides the following cred * `request.user` will be a `django.contrib.auth.models.User` instance. * `request.auth` will be a `rest_framework.tokenauth.models.BasicToken` instance. -Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthenticated` response with an appropriate WWW-Authenticate header. For example: +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 @@ -163,7 +163,7 @@ 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 an `Unauthenticated` 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 Unauthenticated` response. +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. From b78872b7dbb55f1aa2d21f15fbb952f0c7156326 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 17 Oct 2012 15:23:36 +0100 Subject: [PATCH 06/44] Use two seperate exceptions - `AuthenticationFailed`, and `NotAuthenticated` Cleaner seperation of exception and resulting HTTP response. Should result in more obvious error messages. --- docs/api-guide/authentication.md | 4 ++-- docs/api-guide/exceptions.md | 16 ++++++++++++---- rest_framework/exceptions.py | 12 ++++++++++-- 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 06f428c0c..3ace6519b 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -156,12 +156,12 @@ Unauthenticated responses that are denied permission will result in an `HTTP 403 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 `Unauthenticated` exception from the `.authenticate()` method. +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 an `Unauthenticated` exception. An error response will be returned immediately, without checking any other authentication schemes. +* 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. diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index f5dff94af..c30f586a2 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -49,11 +49,19 @@ 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". -## Unauthenticated +## AuthenticationFailed -**Signature:** `Unauthenticated(detail=None)` +**Signature:** `AuthenticationFailed(detail=None)` -Raised when an unauthenticated incoming request fails the permission checks. +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. @@ -61,7 +69,7 @@ By default this exception results in a response with the HTTP status code "401 U **Signature:** `PermissionDenied(detail=None)` -Raised when an authenticated 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". diff --git a/rest_framework/exceptions.py b/rest_framework/exceptions.py index 2461cacdf..6ae0c95c8 100644 --- a/rest_framework/exceptions.py +++ b/rest_framework/exceptions.py @@ -23,9 +23,17 @@ class ParseError(APIException): self.detail = detail or self.default_detail -class Unauthenticated(APIException): +class AuthenticationFailed(APIException): status_code = status.HTTP_401_UNAUTHORIZED - default_detail = 'Incorrect or absent authentication credentials.' + 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 From 957700ecfb36322a8ea40ea473dc43ff1e92592f Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 13 Nov 2012 11:26:45 +0000 Subject: [PATCH 07/44] Remove OAuth2 from docs --- docs/api-guide/authentication.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index c87ba83e8..b2323d627 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -126,7 +126,7 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401 **Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https` only. -## OAuth2Authentication + ## SessionAuthentication From 873a142af2f63084fd10bf35c13e79131837da07 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 13 Nov 2012 11:27:09 +0000 Subject: [PATCH 08/44] Implementing 401 vs 403 responses --- rest_framework/authentication.py | 68 +++++++++++++++++++++----------- rest_framework/request.py | 29 +++++++++----- rest_framework/views.py | 2 + 3 files changed, 67 insertions(+), 32 deletions(-) diff --git a/rest_framework/authentication.py b/rest_framework/authentication.py index e557abedf..6dc804983 100644 --- a/rest_framework/authentication.py +++ b/rest_framework/authentication.py @@ -34,27 +34,33 @@ 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): """ @@ -63,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): + return 'Basic realm="%s"' % self.www_authenticate_realm class SessionAuthentication(BaseAuthentication): @@ -82,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): @@ -93,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) @@ -120,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): + return 'Token' - if token.user.is_active: - return (token.user, token) # TODO: OAuthAuthentication diff --git a/rest_framework/request.py b/rest_framework/request.py index a1827ba48..38ee36dd7 100644 --- a/rest_framework/request.py +++ b/rest_framework/request.py @@ -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 @property @@ -176,9 +177,17 @@ 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 + @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. @@ -282,21 +291,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() @@ -308,7 +319,7 @@ class Request(object): else: auth = None - return (user, auth) + return (None, user, auth) def __getattr__(self, attr): """ diff --git a/rest_framework/views.py b/rest_framework/views.py index 1afbd6974..c470817a4 100644 --- a/rest_framework/views.py +++ b/rest_framework/views.py @@ -148,6 +148,8 @@ class APIView(View): """ If request is not permitted, determine what kind of exception to raise. """ + if self.request.successful_authenticator: + raise exceptions.NotAuthenticated() raise exceptions.PermissionDenied() def throttled(self, request, wait): From a98049c5de9a4ac9e93eac9798e00df9c93caf81 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 19 Jan 2013 15:25:32 +0000 Subject: [PATCH 09/44] Drop unneeded test --- rest_framework/tests/decorators.py | 8 -------- 1 file changed, 8 deletions(-) diff --git a/rest_framework/tests/decorators.py b/rest_framework/tests/decorators.py index 5e6bce4ef..4012188d6 100644 --- a/rest_framework/tests/decorators.py +++ b/rest_framework/tests/decorators.py @@ -28,14 +28,6 @@ class DecoratorTestCase(TestCase): response.request = request return APIView.finalize_response(self, request, response, *args, **kwargs) - def test_wrap_view(self): - - @api_view(['GET']) - def view(request): - return Response({}) - - self.assertTrue(isinstance(view.cls_instance, APIView)) - def test_calling_method(self): @api_view(['GET']) From af3fd098459fb559788735cb6b49a7108e11b18e Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 19 Jan 2013 15:31:21 +0000 Subject: [PATCH 10/44] Tweak imports in tutorial. Fixes #597. --- docs/tutorial/1-serialization.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index d3ada9e3a..f5ff167f0 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -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. From 37d49429ca34eed86ea142e5dceea4cd9536df2d Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 19 Jan 2013 15:51:14 +0000 Subject: [PATCH 11/44] Raise assertion errors if @api_view decorator is applied incorrectly. Fixes #596. --- rest_framework/decorators.py | 9 +++++++++ rest_framework/tests/decorators.py | 22 ++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/rest_framework/decorators.py b/rest_framework/decorators.py index 1b710a03c..7a4103e16 100644 --- a/rest_framework/decorators.py +++ b/rest_framework/decorators.py @@ -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] diff --git a/rest_framework/tests/decorators.py b/rest_framework/tests/decorators.py index 4012188d6..82f912e98 100644 --- a/rest_framework/tests/decorators.py +++ b/rest_framework/tests/decorators.py @@ -28,6 +28,28 @@ class DecoratorTestCase(TestCase): response.request = request return APIView.finalize_response(self, request, response, *args, **kwargs) + def test_api_view_incorrect(self): + """ + If @api_view is not applied correct, we should raise an assertion. + """ + + @api_view + def view(request): + return Response() + + 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): @api_view(['GET']) From 2c05faa52ae65f96fdcc73efceb6c44511698261 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 19 Jan 2013 16:56:48 +0000 Subject: [PATCH 12/44] `format_suffix_patterns` now support `include`-style nested URL patterns. Fixes #593 --- rest_framework/urlpatterns.py | 44 ++++++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 13 deletions(-) diff --git a/rest_framework/urlpatterns.py b/rest_framework/urlpatterns.py index 143928c99..0aaad3344 100644 --- a/rest_framework/urlpatterns.py +++ b/rest_framework/urlpatterns.py @@ -1,5 +1,34 @@ -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 not isinstance(urlpattern, RegexURLResolver): + # Regular URL pattern + + # 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)) + else: + # Set of included URL patterns + print(type(urlpattern)) + regex = urlpattern.regex.pattern + namespace = urlpattern.namespace + app_name = urlpattern.app_name + patterns = apply_suffix_patterns(urlpattern.url_patterns, + suffix_pattern, + suffix_required) + ret.append(url(regex, include(patterns, namespace, app_name))) + return ret def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None): @@ -28,15 +57,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) From 199fa766ff7b5c7606e8f835dcf2d1d979da38b1 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 19 Jan 2013 17:00:20 +0000 Subject: [PATCH 13/44] Update release notes --- docs/topics/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/topics/release-notes.md b/docs/topics/release-notes.md index bbe11face..58471a790 100644 --- a/docs/topics/release-notes.md +++ b/docs/topics/release-notes.md @@ -19,6 +19,7 @@ Major version numbers (x.0.0) are reserved for project milestones. No major poi ### Master * Support json encoding of timedelta objects. +* `format_suffix_patterns()` now supports `include` style URL patterns. * Bugfix: Return proper validation errors when incorrect types supplied for relational fields. * Bugfix: Support nullable FKs with `SlugRelatedField`. From 69083c3668b363bd9cb85674255d260808bbeeff Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 19 Jan 2013 18:36:25 +0000 Subject: [PATCH 14/44] Drop print statement --- rest_framework/urlpatterns.py | 1 - 1 file changed, 1 deletion(-) diff --git a/rest_framework/urlpatterns.py b/rest_framework/urlpatterns.py index 0aaad3344..162f23143 100644 --- a/rest_framework/urlpatterns.py +++ b/rest_framework/urlpatterns.py @@ -20,7 +20,6 @@ def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required): ret.append(url(regex, view, kwargs, name)) else: # Set of included URL patterns - print(type(urlpattern)) regex = urlpattern.regex.pattern namespace = urlpattern.namespace app_name = urlpattern.app_name From 771821af7d8eb6751d6ea37eabae7108cebc0df0 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 19 Jan 2013 18:39:39 +0000 Subject: [PATCH 15/44] Include kwargs in included URLs --- rest_framework/urlpatterns.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/rest_framework/urlpatterns.py b/rest_framework/urlpatterns.py index 162f23143..0f210e66e 100644 --- a/rest_framework/urlpatterns.py +++ b/rest_framework/urlpatterns.py @@ -23,10 +23,11 @@ def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required): regex = urlpattern.regex.pattern namespace = urlpattern.namespace app_name = urlpattern.app_name + kwargs = urlpattern.default_kwargs patterns = apply_suffix_patterns(urlpattern.url_patterns, suffix_pattern, suffix_required) - ret.append(url(regex, include(patterns, namespace, app_name))) + ret.append(url(regex, include(patterns, namespace, app_name), kwargs)) return ret From 9b9b6529bcf3c3f39abf398597684962e5710e57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Reni=C3=A9?= Date: Sun, 20 Jan 2013 14:49:07 +0100 Subject: [PATCH 16/44] Fixed reference to authtoken in the docs --- docs/api-guide/authentication.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index c0f9c072e..1b56cf449 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -102,7 +102,7 @@ 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. **Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https` only. From 42fcc3599c7d6aff2b50e534af4a5efbe3ce8c47 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 20 Jan 2013 15:50:16 +0000 Subject: [PATCH 17/44] Added @brutasse for docs fix #600. Thanks! --- docs/topics/credits.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/topics/credits.md b/docs/topics/credits.md index 6529813f1..490501968 100644 --- a/docs/topics/credits.md +++ b/docs/topics/credits.md @@ -93,6 +93,7 @@ The following people have helped make REST framework great. * James Cleveland - [radiosilence] * Steve Gregory - [steve-gregory] * Federico Capoano - [nemesisdesign] +* Bruno Renié - [brutasse] Many thanks to everyone who's contributed to the project. @@ -221,3 +222,4 @@ 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 From 2c76212e5454efa4d4d02c7051055c7957497d52 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 20 Jan 2013 16:38:32 +0000 Subject: [PATCH 18/44] Add missing import to tutorial. Fixes #599 --- docs/tutorial/4-authentication-and-permissions.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index f6daebb7a..35aca8c63 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -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() @@ -188,4 +190,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 \ No newline at end of file +[tut-5]: 5-relationships-and-hyperlinked-apis.md From 71bd2faa792569c9f4c83a06904b927616bfdbf1 Mon Sep 17 00:00:00 2001 From: Kevin Stone Date: Sun, 20 Jan 2013 12:59:27 -0800 Subject: [PATCH 19/44] Added test case for format_suffix_patterns to validate changes introduced with issue #593. Signed-off-by: Kevin Stone --- rest_framework/tests/urlpatterns.py | 75 +++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 rest_framework/tests/urlpatterns.py diff --git a/rest_framework/tests/urlpatterns.py b/rest_framework/tests/urlpatterns.py new file mode 100644 index 000000000..e96e7cf35 --- /dev/null +++ b/rest_framework/tests/urlpatterns.py @@ -0,0 +1,75 @@ +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 test_view(request, *args, **kwargs): + pass + + +class FormatSuffixTests(TestCase): + def _test_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$', test_view), + ) + test_paths = [ + URLTestPath('/test', (), {}), + URLTestPath('/test.api', (), {'format': 'api'}), + URLTestPath('/test.asdf', (), {'format': 'asdf'}), + ] + self._test_urlpatterns(urlpatterns, test_paths) + + def test_default_args(self): + urlpatterns = patterns( + '', + url(r'^test$', test_view, {'foo': 'bar'}), + ) + test_paths = [ + URLTestPath('/test', (), {'foo': 'bar', }), + URLTestPath('/test.api', (), {'foo': 'bar', 'format': 'api'}), + URLTestPath('/test.asdf', (), {'foo': 'bar', 'format': 'asdf'}), + ] + self._test_urlpatterns(urlpatterns, test_paths) + + def test_included_urls(self): + nested_patterns = patterns( + '', + url(r'^path$', test_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._test_urlpatterns(urlpatterns, test_paths) From dc1c57d595c3917e3fed9076894d5fa88ec083c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stephan=20Gro=C3=9F?= Date: Mon, 21 Jan 2013 12:45:30 +0100 Subject: [PATCH 20/44] Add failed testcase for fieldvalidation --- rest_framework/tests/serializer.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/rest_framework/tests/serializer.py b/rest_framework/tests/serializer.py index bd96ba23e..0ba4e7650 100644 --- a/rest_framework/tests/serializer.py +++ b/rest_framework/tests/serializer.py @@ -241,6 +241,14 @@ class ValidationTests(TestCase): self.assertFalse(serializer.is_valid()) self.assertEquals(serializer.errors, {'content': [u'Test not in value']}) + incomplete_data = { + 'email': 'tom@example.com', + 'created': datetime.datetime(2012, 1, 1) + } + serializer = CommentSerializerWithFieldValidator(data=incomplete_data) + self.assertFalse(serializer.is_valid()) + self.assertEquals(serializer.errors, {'content': [u'This field is required.']}) + def test_bad_type_data_is_false(self): """ Data of the wrong type is not valid. From 2250ab6418d3cf99719ea7c5e3b3a861afa850bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stephan=20Gro=C3=9F?= Date: Mon, 21 Jan 2013 12:50:39 +0100 Subject: [PATCH 21/44] Add possible solution for field validation error --- rest_framework/serializers.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 27458f968..0c60d17f5 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -227,13 +227,14 @@ class BaseSerializer(Field): Run `validate_()` and `validate()` methods on the serializer """ for field_name, field in self.fields.items(): - try: - validate_method = getattr(self, 'validate_%s' % field_name, None) - if validate_method: - source = field.source or field_name - attrs = validate_method(attrs, source) - except ValidationError as err: - self._errors[field_name] = self._errors.get(field_name, []) + list(err.messages) + if field_name not in self._errors: + try: + validate_method = getattr(self, 'validate_%s' % field_name, None) + if validate_method: + source = field.source or field_name + attrs = validate_method(attrs, source) + except ValidationError as err: + self._errors[field_name] = self._errors.get(field_name, []) + list(err.messages) # If there are already errors, we don't run .validate() because # field-validation failed and thus `attrs` may not be complete. From e7916ae0b1c4af35c55dc21e0d882f3f8ff3121e Mon Sep 17 00:00:00 2001 From: Kevin Stone Date: Mon, 21 Jan 2013 09:37:50 -0800 Subject: [PATCH 22/44] Tweaked some method names to be more clear and added a docstring to the test case class. Signed-off-by: Kevin Stone --- rest_framework/tests/urlpatterns.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/rest_framework/tests/urlpatterns.py b/rest_framework/tests/urlpatterns.py index e96e7cf35..43e8ef692 100644 --- a/rest_framework/tests/urlpatterns.py +++ b/rest_framework/tests/urlpatterns.py @@ -13,12 +13,15 @@ from rest_framework.urlpatterns import format_suffix_patterns URLTestPath = namedtuple('URLTestPath', ['path', 'args', 'kwargs']) -def test_view(request, *args, **kwargs): +def dummy_view(request, *args, **kwargs): pass class FormatSuffixTests(TestCase): - def _test_urlpatterns(self, urlpatterns, test_paths): + """ + 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) @@ -37,31 +40,31 @@ class FormatSuffixTests(TestCase): def test_format_suffix(self): urlpatterns = patterns( '', - url(r'^test$', test_view), + url(r'^test$', dummy_view), ) test_paths = [ URLTestPath('/test', (), {}), URLTestPath('/test.api', (), {'format': 'api'}), URLTestPath('/test.asdf', (), {'format': 'asdf'}), ] - self._test_urlpatterns(urlpatterns, test_paths) + self._resolve_urlpatterns(urlpatterns, test_paths) def test_default_args(self): urlpatterns = patterns( '', - url(r'^test$', test_view, {'foo': 'bar'}), + 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._test_urlpatterns(urlpatterns, test_paths) + self._resolve_urlpatterns(urlpatterns, test_paths) def test_included_urls(self): nested_patterns = patterns( '', - url(r'^path$', test_view) + url(r'^path$', dummy_view) ) urlpatterns = patterns( '', @@ -72,4 +75,4 @@ class FormatSuffixTests(TestCase): URLTestPath('/test/path.api', (), {'foo': 'bar', 'format': 'api'}), URLTestPath('/test/path.asdf', (), {'foo': 'bar', 'format': 'asdf'}), ] - self._test_urlpatterns(urlpatterns, test_paths) + self._resolve_urlpatterns(urlpatterns, test_paths) From 98bffa68e655e530c16e4622658541940b3891f0 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 21 Jan 2013 17:42:33 +0000 Subject: [PATCH 23/44] Don't do an inverted if test. --- rest_framework/urlpatterns.py | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/rest_framework/urlpatterns.py b/rest_framework/urlpatterns.py index 0f210e66e..47789026f 100644 --- a/rest_framework/urlpatterns.py +++ b/rest_framework/urlpatterns.py @@ -6,10 +6,20 @@ from django.core.urlresolvers import RegexURLResolver def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required): ret = [] for urlpattern in urlpatterns: - if not isinstance(urlpattern, RegexURLResolver): - # Regular URL pattern + 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)) - # Form our complementing '.format' urlpattern + else: + # Regular URL pattern regex = urlpattern.regex.pattern.rstrip('$') + suffix_pattern view = urlpattern._callback or urlpattern._callback_str kwargs = urlpattern.default_args @@ -18,16 +28,7 @@ def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required): if not suffix_required: ret.append(urlpattern) ret.append(url(regex, view, kwargs, name)) - else: - # Set of included URL patterns - regex = urlpattern.regex.pattern - namespace = urlpattern.namespace - app_name = urlpattern.app_name - kwargs = urlpattern.default_kwargs - patterns = apply_suffix_patterns(urlpattern.url_patterns, - suffix_pattern, - suffix_required) - ret.append(url(regex, include(patterns, namespace, app_name), kwargs)) + return ret From e29ba356f054222893655901923811bd9675d4cc Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 21 Jan 2013 17:53:27 +0000 Subject: [PATCH 24/44] Added @kevinastone, for work on extra test cases in #602. Thanks! --- docs/topics/credits.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/topics/credits.md b/docs/topics/credits.md index 490501968..b033ecba5 100644 --- a/docs/topics/credits.md +++ b/docs/topics/credits.md @@ -94,6 +94,7 @@ The following people have helped make REST framework great. * Steve Gregory - [steve-gregory] * Federico Capoano - [nemesisdesign] * Bruno Renié - [brutasse] +* Kevin Stone - [kevinastone] Many thanks to everyone who's contributed to the project. @@ -223,3 +224,4 @@ You can also contact [@_tomchristie][twitter] directly on twitter. [steve-gregory]: https://github.com/steve-gregory [nemesisdesign]: https://github.com/nemesisdesign [brutasse]: https://github.com/brutasse +[kevinastone]: https://github.com/kevinastone From 65b62d64ec54b528b62a1500b8f6ffe216d45c09 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 21 Jan 2013 21:29:49 +0000 Subject: [PATCH 25/44] WWW-Authenticate responses --- docs/api-guide/authentication.md | 12 ++++---- rest_framework/authentication.py | 4 +-- rest_framework/tests/authentication.py | 41 +++++++++++++------------- rest_framework/views.py | 21 ++++++++++++- 4 files changed, 49 insertions(+), 29 deletions(-) diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 4dfcb0f12..59dc4a308 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -18,7 +18,9 @@ The `request.auth` property is used for any additional authentication informatio --- -**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]. +**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]. --- @@ -73,11 +75,11 @@ When an unauthenticated request is denied permission there are two different err * [HTTP 401 Unauthorized][http401] * [HTTP 403 Permission Denied][http403] -The kind of response that will be used depends on the type of authentication scheme in use, and the ordering of the authentication classes. +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. -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 given priority when determining the type of response**. +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 *successfully authenticated* request is denied permission, a `403 Permission Denied` response will always be used, regardless of the authentication scheme. +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. --- @@ -126,8 +128,6 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401 **Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https` only. -<<<<<<< HEAD -