From f513db714db76849448bf2e2412428ee7121ebf6 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 12 Mar 2013 19:07:30 +0000 Subject: [PATCH] Clean up TokenHasReadWriteScope slightly --- rest_framework/compat.py | 8 ++------ rest_framework/permissions.py | 31 ++++++++++++------------------- 2 files changed, 14 insertions(+), 25 deletions(-) diff --git a/rest_framework/compat.py b/rest_framework/compat.py index e9570a080..7b2ef7384 100644 --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -445,19 +445,15 @@ except ImportError: # OAuth 2 support is optional try: import provider.oauth2 as oauth2_provider - # # Hack to fix submodule import issues - # submodules = ['backends', 'forms', 'managers', 'models', 'urls', 'views'] - # for s in submodules: - # mod = __import__('provider.oauth2.%s.*' % s) - # setattr(oauth2_provider, s, mod) from provider.oauth2 import backends as oauth2_provider_backends from provider.oauth2 import models as oauth2_provider_models from provider.oauth2 import forms as oauth2_provider_forms from provider import scope as oauth2_provider_scope - + from provider import constants as oauth2_constants except ImportError: oauth2_provider = None oauth2_provider_backends = None oauth2_provider_models = None oauth2_provider_forms = None oauth2_provider_scope = None + oauth2_constants = None diff --git a/rest_framework/permissions.py b/rest_framework/permissions.py index 92f8215ac..f026850a0 100644 --- a/rest_framework/permissions.py +++ b/rest_framework/permissions.py @@ -7,7 +7,7 @@ import warnings SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] -from rest_framework.compat import oauth2_provider_scope +from rest_framework.compat import oauth2_provider_scope, oauth2_constants class BasePermission(object): @@ -142,25 +142,18 @@ class TokenHasReadWriteScope(BasePermission): """ def has_permission(self, request, view): - if not request.auth: - return False - + token = request.auth read_only = request.method in SAFE_METHODS - if hasattr(request.auth, 'resource'): # oauth 1 - if read_only: - return True - elif request.auth.resource.is_readonly is False: - return True - return False - elif hasattr(request.auth, 'scope'): # oauth 2 - scope_valid = lambda scope_wanted_key, scope_had: oauth2_provider_scope.check( - oauth2_provider_scope.SCOPE_NAME_DICT[scope_wanted_key], scope_had) - if read_only and scope_valid('read', request.auth.scope): - return True - elif scope_valid('write', request.auth.scope): - return True + if not token: return False + + if hasattr(token, 'resource'): # OAuth 1 + return read_only or not request.auth.resource.is_readonly + elif hasattr(token, 'scope'): # OAuth 2 + required = oauth2_constants.READ if read_only else oauth2_constants.WRITE + return oauth2_provider_scope.check(required, request.auth.scope) else: - # Improperly configured! - pass + assert False, ('TokenHasReadWriteScope requires either the' + '`OAuthAuthentication` or `OAuth2Authentication` authentication ' + 'class to be used.')