Ejemplo n.º 1
0
    def test_that_initialize_server_request_when_custom_content_type(self):
        """Chceck if post data is not included in params when constent type
        is not application/x-www-form-urlencoded. It would cause problems only when signature method is
        HMAC-SHA1
         """

        data = json.dumps({"data": {"foo": "bar"}})
        content_type = "application/json"
        querystring = self.__make_querystring_with_HMAC_SHA1("POST", "/path/to/post", data, content_type)

        #we're just using the request, don't bother faking sending it
        rf = RequestFactory()
        request = rf.post(querystring, data, content_type)

        #this is basically a "remake" of the relevant parts of OAuthAuthentication in django-rest-framework
        oauth_request = utils.get_oauth_request(request)

        consumer_key = oauth_request.get_parameter('oauth_consumer_key')
        consumer = oauth_provider_store.get_consumer(request, oauth_request, consumer_key)

        token_param = oauth_request.get_parameter('oauth_token')
        token = oauth_provider_store.get_access_token(request, oauth_request, consumer, token_param)

        oauth_server, oauth_request = utils.initialize_server_request(request)

        #check that this does not throw an oauth.Error
        oauth_server.verify_request(oauth_request, consumer, token)
Ejemplo n.º 2
0
    def test_post_using_auth_in_body_content_type_and_application_x_www_form_urlencoded(self):
        """Opposite of test_that_initialize_server_request_when_custom_content_type,
        If content type is application/x-www-form-urlencoded, post data should be added to params,
        and it affects signature
        """
        self._request_token()
        self._authorize_and_access_token_using_form()

        data = {"foo": "bar"}
        content_type = "application/x-www-form-urlencoded"
        querystring = self._make_querystring_with_HMAC_SHA1("POST", "/path/to/post", data, content_type)

        #we're just using the request, don't bother faking sending it
        rf = RequestFactory()
        request = rf.post(querystring, urllib.urlencode(data), content_type)

        # this is basically a "remake" of the relevant parts of
        # OAuthAuthentication in django-rest-framework
        oauth_request = utils.get_oauth_request(request)

        consumer_key = oauth_request.get_parameter('oauth_consumer_key')
        consumer = oauth_provider_store.get_consumer(request, oauth_request, consumer_key)

        token_param = oauth_request.get_parameter('oauth_token')
        token = oauth_provider_store.get_access_token(request, oauth_request, consumer, token_param)

        oauth_server, oauth_request = utils.initialize_server_request(request)

        #check that this does not throw an oauth.Error
        oauth_server.verify_request(oauth_request, consumer, token)
Ejemplo n.º 3
0
    def test_that_initialize_server_request_when_custom_content_type(self):
        """Chceck if post data is not included in params when constent type
        is not application/x-www-form-urlencoded. It would cause problems only when signature method is
        HMAC-SHA1
         """

        data = json.dumps({"data": {"foo": "bar"}})
        content_type = "application/json"
        querystring = self._make_querystring_with_HMAC_SHA1("POST", "/path/to/post", data, content_type)

        #we're just using the request, don't bother faking sending it
        rf = RequestFactory()
        request = rf.post(querystring, data, content_type)

        #this is basically a "remake" of the relevant parts of OAuthAuthentication in django-rest-framework
        oauth_request = utils.get_oauth_request(request)

        consumer_key = oauth_request.get_parameter('oauth_consumer_key')
        consumer = oauth_provider_store.get_consumer(request, oauth_request, consumer_key)

        token_param = oauth_request.get_parameter('oauth_token')
        token = oauth_provider_store.get_access_token(request, oauth_request, consumer, token_param)

        oauth_server, oauth_request = utils.initialize_server_request(request)

        #check that this does not throw an oauth.Error
        oauth_server.verify_request(oauth_request, consumer, token)
Ejemplo n.º 4
0
def authenticate_user(*args, **kwargs):
    request = args[1]
    try:
        oauth_request = get_oauth_request(request)
        consumer = store.get_consumer(request, oauth_request,
                                      oauth_request['oauth_consumer_key'])
        verify_oauth_request(request, oauth_request, consumer)

        # Allow a trusted client to either give us a user via header, or do the
        # 3-legged oauth
        user = None
        try:
            trusted_client = TrustedOAuthClient.objects.get(consumer=consumer)
            if trusted_client and trusted_client.is_trusted:
                user = request.META["HTTP_X_OAUTH_USER"]
        except Exception as e:
            pass

        if not user:
            access_token = store.get_access_token(
                request, oauth_request, consumer,
                oauth_request[u'oauth_token'])
            user = store.get_user_for_access_token(request, oauth_request,
                                                   access_token).username

        request.META['SS_OAUTH_CONSUMER_NAME'] = consumer.name
        request.META['SS_OAUTH_CONSUMER_PK'] = consumer.pk
        request.META['SS_OAUTH_USER'] = user

        return
    except Exception as e:
        response = HttpResponse("Error authorizing user: %s" % e)
        response.status_code = 401
        return response
Ejemplo n.º 5
0
def set_normal_authorization(request, r_dict):
    auth_params = r_dict['headers']['Authorization']
    # OAuth1 and basic http auth come in as string
    r_dict['auth']['endpoint'] = get_endpoint(request)
    if auth_params[:6] == 'OAuth ':
        oauth_request = get_oauth_request(request)
        # Returns HttpBadRequest if missing any params
        missing = require_params(oauth_request)
        if missing:
            raise missing

        check = CheckOauth()
        e_type, error = check.check_access_token(request)
        if e_type and error:
            if e_type == 'auth':
                raise OauthUnauthorized(error)
            else:
                raise OauthBadRequest(error)
        # Consumer and token should be clean by now
        consumer = store.get_consumer(
            request, oauth_request, oauth_request['oauth_consumer_key'])
        token = store.get_access_token(
            request, oauth_request, consumer, oauth_request.get_parameter('oauth_token'))

        # Set consumer and token for authentication piece
        r_dict['auth']['oauth_consumer'] = consumer
        r_dict['auth']['oauth_token'] = token
        r_dict['auth']['type'] = 'oauth'
    else:
        r_dict['auth']['type'] = 'http'
Ejemplo n.º 6
0
    def test_post_using_auth_in_body_content_type_and_application_x_www_form_urlencoded(self):
        """Opposite of test_that_initialize_server_request_when_custom_content_type,
        If content type is application/x-www-form-urlencoded, post data should be added to params,
        and it affects signature
        """
        self._request_token()
        self._authorize_and_access_token_using_form()

        data={"foo": "bar"}
        content_type = "application/x-www-form-urlencoded"
        querystring = self.__make_querystring_with_HMAC_SHA1("POST", "/path/to/post", data, content_type)

        #we're just using the request, don't bother faking sending it
        rf = RequestFactory()
        request = rf.post(querystring, urllib.urlencode(data), content_type)

        #this is basically a "remake" of the relevant parts of OAuthAuthentication in django-rest-framework
        oauth_request = utils.get_oauth_request(request)

        consumer_key = oauth_request.get_parameter('oauth_consumer_key')
        consumer = oauth_provider_store.get_consumer(request, oauth_request, consumer_key)

        token_param = oauth_request.get_parameter('oauth_token')
        token = oauth_provider_store.get_access_token(request, oauth_request, consumer, token_param)

        oauth_server, oauth_request = utils.initialize_server_request(request)

        #check that this does not throw an oauth.Error
        oauth_server.verify_request(oauth_request, consumer, token)
Ejemplo n.º 7
0
def authenticate_user(*args, **kwargs):
    request = args[1]
    try:
        oauth_request = get_oauth_request(request)
        consumer = store.get_consumer(request, oauth_request,
                                      oauth_request['oauth_consumer_key'])
        verify_oauth_request(request, oauth_request, consumer)

        # Allow a trusted client to either give us a user via header, or do the
        # 3-legged oauth
        user = None
        try:
            trusted_client = TrustedOAuthClient.objects.get(consumer=consumer)
            if trusted_client and trusted_client.is_trusted:
                user = request.META["HTTP_XOAUTH_USER"]
        except Exception as e:
            pass


        if not user:
            access_token = store.get_access_token(request, oauth_request, consumer, oauth_request[u'oauth_token'])
            user = store.get_user_for_access_token(request, oauth_request, access_token).username


        request.META['SS_OAUTH_CONSUMER_NAME'] = consumer.name
        request.META['SS_OAUTH_CONSUMER_PK'] = consumer.pk
        request.META['SS_OAUTH_USER'] = user

        return
    except Exception as e:
        response = HttpResponse("Error authorizing application")
        response.status_code = 401
        return response
Ejemplo n.º 8
0
    def is_authenticated(self, request, **kwargs):
        if is_valid_request(request, ['oauth_consumer_key']):
            # Just checking if you're allowed to be there
            oauth_request = get_oauth_request(request)
            try:
                consumer = store.get_consumer(
                    request, oauth_request,
                    oauth_request.get_parameter('oauth_consumer_key'))

                try:
                    if oauth_request.get_parameter('oauth_token'):
                        try:
                            token = store.get_access_token(
                                request, oauth_request, consumer,
                                oauth_request.get_parameter('oauth_token'))

                            if not verify_oauth_request(
                                    request, oauth_request, consumer,
                                    token=token):
                                return False

                            if consumer and token:
                                request.user = token.user

                        except InvalidTokenError:
                            return False
                except:
                    pass

                return True

            except InvalidConsumerError:
                return False
        return False
Ejemplo n.º 9
0
    def is_authenticated(self, request, **kwargs):
        from oauth_provider.store import store, InvalidTokenError

        if self.is_valid_request(request):
            oauth_request = oauth_provider.utils.get_oauth_request(request)
            consumer = store.get_consumer(
                request, oauth_request,
                oauth_request.get_parameter('oauth_consumer_key'))

            try:
                token = store.get_access_token(
                    request, oauth_request, consumer,
                    oauth_request.get_parameter('oauth_token'))
            except oauth_provider.store.InvalidTokenError:
                return oauth_provider.utils.send_oauth_error(
                    oauth2.Error(
                        _('Invalid access token: %s') %
                        oauth_request.get_parameter('oauth_token')))

            try:
                self.validate_token(request, consumer, token)
            except oauth2.Error, e:
                return oauth_provider.utils.send_oauth_error(e)

            if consumer and token:
                if not self.check_active(token.user):
                    return False

                request.user = token.user
                return True

            return oauth_provider.utils.send_oauth_error(
                oauth2.Error(
                    _('You are not allowed to access this resource.')))
Ejemplo n.º 10
0
def set_normal_authorization(request, r_dict):
    auth_params = r_dict['headers']['Authorization']
    # OAuth1 and basic http auth come in as string
    r_dict['auth']['endpoint'] = get_endpoint(request)
    if auth_params[:6] == 'OAuth ':
        oauth_request = get_oauth_request(request)
        # Returns HttpBadRequest if missing any params
        missing = require_params(oauth_request)
        if missing:
            raise missing

        check = CheckOauth()
        e_type, error = check.check_access_token(request)
        if e_type and error:
            if e_type == 'auth':
                raise OauthUnauthorized(error)
            else:
                raise OauthBadRequest(error)
        # Consumer and token should be clean by now
        consumer = store.get_consumer(request, oauth_request,
                                      oauth_request['oauth_consumer_key'])
        token = store.get_access_token(
            request, oauth_request, consumer,
            oauth_request.get_parameter('oauth_token'))

        # Set consumer and token for authentication piece
        r_dict['auth']['oauth_consumer'] = consumer
        r_dict['auth']['oauth_token'] = token
        r_dict['auth']['type'] = 'oauth'
    else:
        r_dict['auth']['type'] = 'http'
Ejemplo n.º 11
0
    def is_authenticated(self, request, **kwargs):
        from oauth_provider.store import store

        if self.is_valid_request(request):
            oauth_request = oauth_provider.utils.get_oauth_request(request)
            consumer = store.get_consumer(request, oauth_request, oauth_request.get_parameter('oauth_consumer_key'))

            try:
                token = store.get_access_token(request, oauth_request, consumer, oauth_request.get_parameter('oauth_token'))
            except oauth_provider.store.InvalidTokenError:
                return oauth_provider.utils.send_oauth_error(oauth2.Error(_('Invalid access token: %s') % oauth_request.get_parameter('oauth_token')))

            try:
                self.validate_token(request, consumer, token)
            except oauth2.Error as e:
                return oauth_provider.utils.send_oauth_error(e)

            if consumer and token:
                if not self.check_active(token.user):
                    return False

                request.user = token.user
                return True

            return oauth_provider.utils.send_oauth_error(oauth2.Error(_('You are not allowed to access this resource.')))

        return oauth_provider.utils.send_oauth_error(oauth2.Error(_('Invalid request parameters.')))
Ejemplo n.º 12
0
    def inner(request, *args, **kwargs):
        auth = None
        if 'HTTP_AUTHORIZATION' in request.META:
            auth = request.META.get('HTTP_AUTHORIZATION')
        elif 'Authorization' in request.META:
            auth = request.META.get('Authorization')
        elif request.user:
            auth = request.user
        if auth:
            if isinstance(auth, basestring):
                if auth[:6] == 'OAuth ':
                    oauth_request = get_oauth_request(request)
                    # Returns HttpBadRequest if missing any params
                    missing = require_params(oauth_request)
                    if missing:
                        raise missing

                    check = CheckOauth()
                    e_type, error = check.check_access_token(request)
                    if e_type and error:
                        if e_type == 'auth':
                            raise OauthUnauthorized(error)
                        else:
                            raise OauthBadRequest(error)
                    # Consumer and token should be clean by now
                    consumer = store.get_consumer(
                        request, oauth_request, oauth_request['oauth_consumer_key'])
                    token = store.get_access_token(
                        request, oauth_request, consumer, oauth_request.get_parameter('oauth_token'))
                    request.META['lrs-user'] = token.user
                else:
                    auth = auth.split()
                    if len(auth) == 2:
                        if auth[0].lower() == 'basic':
                            uname, passwd = base64.b64decode(
                                auth[1]).split(':')
                            if uname and passwd:
                                user = authenticate(
                                    username=uname, password=passwd)
                                if not user:
                                    request.META[
                                        'lrs-user'] = (False, "Unauthorized: Authorization failed, please verify your username and password")
                                request.META['lrs-user'] = (True, user)
                            else:
                                request.META[
                                    'lrs-user'] = (False, "Unauthorized: The format of the HTTP Basic Authorization Header value is incorrect")
                        else:
                            request.META[
                                'lrs-user'] = (False, "Unauthorized: HTTP Basic Authorization Header must start with Basic")
                    else:
                        request.META[
                            'lrs-user'] = (False, "Unauthorized: The format of the HTTP Basic Authorization Header value is incorrect")
            else:
                request.META['lrs-user'] = (True, '')
        else:
            request.META[
                'lrs-user'] = (False, "Unauthorized: Authorization must be supplied")
        return func(request, *args, **kwargs)
Ejemplo n.º 13
0
    def inner(request, *args, **kwargs):
        auth = None
        if 'HTTP_AUTHORIZATION' in request.META:
            auth = request.META.get('HTTP_AUTHORIZATION')
        elif 'Authorization' in request.META:
            auth = request.META.get('Authorization')
        elif request.user:
            auth = request.user
        if auth:
            if isinstance(auth, basestring):
                if auth[:6] == 'OAuth ':
                    oauth_request = get_oauth_request(request)
                    # Returns HttpBadRequest if missing any params
                    missing = require_params(oauth_request)
                    if missing:
                        raise missing

                    check = CheckOauth()
                    e_type, error = check.check_access_token(request)
                    if e_type and error:
                        if e_type == 'auth':
                            raise OauthUnauthorized(error)
                        else:
                            raise OauthBadRequest(error)
                    # Consumer and token should be clean by now
                    consumer = store.get_consumer(
                        request, oauth_request, oauth_request['oauth_consumer_key'])
                    token = store.get_access_token(
                        request, oauth_request, consumer, oauth_request.get_parameter('oauth_token'))
                    request.META['lrs-user'] = token.user
                else:
                    auth = auth.split()
                    if len(auth) == 2:
                        if auth[0].lower() == 'basic':
                            uname, passwd = base64.b64decode(
                                auth[1]).split(':')
                            if uname and passwd:
                                user = authenticate(
                                    username=uname, password=passwd)
                                if not user:
                                    request.META[
                                        'lrs-user'] = (False, "Unauthorized: Authorization failed, please verify your username and password")
                                request.META['lrs-user'] = (True, user)
                            else:
                                request.META[
                                    'lrs-user'] = (False, "Unauthorized: The format of the HTTP Basic Authorization Header value is incorrect")
                        else:
                            request.META[
                                'lrs-user'] = (False, "Unauthorized: HTTP Basic Authorization Header must start with Basic")
                    else:
                        request.META[
                            'lrs-user'] = (False, "Unauthorized: The format of the HTTP Basic Authorization Header value is incorrect")
            else:
                request.META['lrs-user'] = (True, '')
        else:
            request.META[
                'lrs-user'] = (False, "Unauthorized: Authorization must be supplied")
        return func(request, *args, **kwargs)
Ejemplo n.º 14
0
 def _wrapper(*args, **kwargs):
     request = args[0]
     try:
         oauth_request = get_oauth_request(request)
         consumer = store.get_consumer(request, oauth_request,
                                       oauth_request['oauth_consumer_key'])
         verify_oauth_request(request, oauth_request, consumer)
         request.META['OAUTH_CONSUMER_NAME'] = consumer.name
         request.META['OAUTH_CONSUMER_PK'] = consumer.pk
         return func(*args, **kwargs)
     except Exception as e:
         print "Error: ", e
         response = HttpResponse("Error authorizing application")
         response.status_code = 401
     return response
Ejemplo n.º 15
0
def authenticate_application(*args, **kwargs):
    request = args[1]
    try:
        oauth_request = get_oauth_request(request)
        consumer = store.get_consumer(request, oauth_request,
                                      oauth_request['oauth_consumer_key'])
        verify_oauth_request(request, oauth_request, consumer)

        request.META['SS_OAUTH_CONSUMER_NAME'] = consumer.name
        request.META['SS_OAUTH_CONSUMER_PK'] = consumer.pk

        return
    except Exception as e:
        response = HttpResponse("Error authorizing application: %s" % e)
        response.status_code = 401
        return response
Ejemplo n.º 16
0
def authenticate_application(*args, **kwargs):
    request = args[1]
    try:
        oauth_request = get_oauth_request(request)
        consumer = store.get_consumer(request, oauth_request,
                                      oauth_request['oauth_consumer_key'])
        verify_oauth_request(request, oauth_request, consumer)

        request.META['SS_OAUTH_CONSUMER_NAME'] = consumer.name
        request.META['SS_OAUTH_CONSUMER_PK'] = consumer.pk

        return
    except Exception as e:
        response = HttpResponse("Error authorizing application: %s" % e)
        response.status_code = 401
        return response
Ejemplo n.º 17
0
 def wrapper(request, *args, **kwargs):
     try:
         oauth_request = get_oauth_request(request)
         if (oauth_request is None):
             raise ValueError('No Oauth Request')
         consumer = store.get_consumer(
             request, oauth_request, oauth_request['oauth_consumer_key'])
         verify_oauth_request(request, oauth_request, consumer)
         request.META['OAUTH_CONSUMER_NAME'] = consumer.name
         request.META['OAUTH_CONSUMER_PK'] = consumer.pk
         return func(request, *args, **kwargs)
     except ValueError as e:
         if is_member_of_group(request, settings.NAGIOS_ADMIN_GROUP):
             return func(request, *args, **kwargs)
         return HttpResponse("Access Denied", status_code=401)
     except (InvalidConsumerError, InvalidTokenError) as e:
         return HttpResponse("Access Denied", status_code=401)
Ejemplo n.º 18
0
    def is_authorized(self, request):

        if is_valid_request(request, ['oauth_consumer_key']):  # Read-only part
            oauth_request = get_oauth_request(request)

            klass = self.resource_meta.object_class
            # Allow GET access to products and POST access to Patron for unlogged users
            if (issubclass(klass, Patron) and request.method == 'POST')\
                or (issubclass(klass, Product) and request.method == 'GET'):
                try:
                    consumer = store.get_consumer(
                        request, oauth_request,
                        oauth_request.get_parameter('oauth_consumer_key'))
                    return True
                except InvalidConsumerError:
                    return False

            return self._is_valid(request)
Ejemplo n.º 19
0
def set_authorization(r_dict, request):
    auth_params = r_dict['headers']['Authorization']
    # OAuth1 and basic http auth come in as string
    r_dict['auth']['endpoint'] = get_endpoint(request)
    if auth_params[:6] == 'OAuth ':
        oauth_request = get_oauth_request(request)

        # Returns HttpBadRequest if missing any params
        missing = require_params(oauth_request)
        if missing:
            raise missing

        check = CheckOauth()
        e_type, error = check.check_access_token(request)

        if e_type and error:
            if e_type == 'auth':
                raise OauthUnauthorized(error)
            else:
                raise OauthBadRequest(error)

        # Consumer and token should be clean by now
        consumer = store.get_consumer(request, oauth_request,
                                      oauth_request['oauth_consumer_key'])
        token = store.get_access_token(
            request, oauth_request, consumer,
            oauth_request.get_parameter('oauth_token'))

        # Set consumer and token for authentication piece
        r_dict['auth']['oauth_consumer'] = consumer
        r_dict['auth']['oauth_token'] = token
        r_dict['auth']['type'] = 'oauth'
    elif auth_params[:7] == 'Bearer ':
        try:
            access_token = AccessToken.objects.get(token=auth_params[7:])
        except AccessToken.DoesNotExist:
            raise OauthUnauthorized("Access Token does not exist")
        else:
            if access_token.get_expire_delta() <= 0:
                raise OauthUnauthorized('Access Token has expired')
            r_dict['auth']['oauth_token'] = access_token
            r_dict['auth']['type'] = 'oauth2'
    else:
        r_dict['auth']['type'] = 'http'
Ejemplo n.º 20
0
def set_authorization(r_dict, request):
    auth_params = r_dict['headers']['Authorization']
    # OAuth1 and basic http auth come in as string
    r_dict['auth']['endpoint'] = get_endpoint(request)
    if auth_params[:6] == 'OAuth ':
        oauth_request = get_oauth_request(request)
        
        # Returns HttpBadRequest if missing any params
        missing = require_params(oauth_request)            
        if missing:
            raise missing

        check = CheckOauth()
        e_type, error = check.check_access_token(request)

        if e_type and error:
            if e_type == 'auth':
                raise OauthUnauthorized(error)
            else:
                raise OauthBadRequest(error)

        # Consumer and token should be clean by now
        consumer = store.get_consumer(request, oauth_request, oauth_request['oauth_consumer_key'])
        token = store.get_access_token(request, oauth_request, consumer, oauth_request.get_parameter('oauth_token'))
        
        # Set consumer and token for authentication piece
        r_dict['auth']['oauth_consumer'] = consumer
        r_dict['auth']['oauth_token'] = token
        r_dict['auth']['type'] = 'oauth'
    elif auth_params[:7] == 'Bearer ':
        try:
            access_token = AccessToken.objects.get(token=auth_params[7:])
        except AccessToken.DoesNotExist:
            raise OauthUnauthorized("Access Token does not exist")
        else:
            if access_token.get_expire_delta() <= 0:
                raise OauthUnauthorized('Access Token has expired')
            r_dict['auth']['oauth_token'] = access_token
            r_dict['auth']['type'] = 'oauth2'
    else:        
        r_dict['auth']['type'] = 'http'    
    def authenticate(self, request):
        """
        Returns two-tuple of (user, token) if authentication succeeds,
        or None otherwise.
        """
        try:
            oauth_request = oauth_provider.utils.get_oauth_request(request)
        except oauth.Error as err:
            raise exceptions.AuthenticationFailed(err.message)

        if not oauth_request:
            return None

        oauth_params = oauth_provider.consts.OAUTH_PARAMETERS_NAMES

        found = any(param for param in oauth_params if param in oauth_request)
        missing = list(param for param in oauth_params if param not in oauth_request)

        if not found:
            # OAuth authentication was not attempted.
            return None

        if missing:
            # OAuth was attempted but missing parameters.
            msg = 'Missing parameters: %s' % (', '.join(missing))
            raise exceptions.AuthenticationFailed(msg)

        if not self.check_nonce(request, oauth_request):
            msg = 'Nonce check failed'
            raise exceptions.AuthenticationFailed(msg)

        try:
            consumer_key = oauth_request.get_parameter('oauth_consumer_key')
            consumer = oauth_provider_store.get_consumer(request, oauth_request, consumer_key)
        except oauth_provider.store.InvalidConsumerError:
            msg = 'Invalid consumer token: %s' % oauth_request.get_parameter('oauth_consumer_key')
            raise exceptions.AuthenticationFailed(msg)

        if consumer.status != oauth_provider.consts.ACCEPTED:
            msg = 'Invalid consumer key status: %s' % consumer.get_status_display()
            raise exceptions.AuthenticationFailed(msg)

        try:
            token_param = oauth_request.get_parameter('oauth_token')
            token = oauth_provider_store.get_access_token(request, oauth_request, consumer, token_param)
        except oauth_provider.store.InvalidTokenError:
            msg = 'Invalid access token: %s' % oauth_request.get_parameter('oauth_token')
            raise exceptions.AuthenticationFailed(msg)

        try:
            self.validate_token(request, consumer, token)
        except oauth.Error as err:
            raise exceptions.AuthenticationFailed(err.message)

        user = token.user

        if not user.is_active:
            msg = 'User inactive or deleted: %s' % user.username
            raise exceptions.AuthenticationFailed(msg)

        return (token.user, token)
Ejemplo n.º 22
0
    def authenticate(self, request):
        """
        Returns two-tuple of (user, token) if authentication succeeds,
        or None otherwise.
        """
        try:
            oauth_request = oauth_provider.utils.get_oauth_request(request)
        except oauth.Error as err:
            raise exceptions.AuthenticationFailed(err.message)

        if not oauth_request:
            return None

        oauth_params = oauth_provider.consts.OAUTH_PARAMETERS_NAMES

        found = any(param for param in oauth_params if param in oauth_request)
        missing = list(param for param in oauth_params
                       if param not in oauth_request)

        if not found:
            # OAuth authentication was not attempted.
            return None

        if missing:
            # OAuth was attempted but missing parameters.
            msg = 'Missing parameters: %s' % (', '.join(missing))
            raise exceptions.AuthenticationFailed(msg)

        if not self.check_nonce(request, oauth_request):
            msg = 'Nonce check failed'
            raise exceptions.AuthenticationFailed(msg)

        try:
            consumer_key = oauth_request.get_parameter('oauth_consumer_key')
            consumer = oauth_provider_store.get_consumer(
                request, oauth_request, consumer_key)
        except oauth_provider.store.InvalidConsumerError:
            msg = 'Invalid consumer token: %s' % oauth_request.get_parameter(
                'oauth_consumer_key')
            raise exceptions.AuthenticationFailed(msg)

        if consumer.status != oauth_provider.consts.ACCEPTED:
            msg = 'Invalid consumer key status: %s' % consumer.get_status_display(
            )
            raise exceptions.AuthenticationFailed(msg)

        try:
            token_param = oauth_request.get_parameter('oauth_token')
            token = oauth_provider_store.get_access_token(
                request, oauth_request, consumer, token_param)
        except oauth_provider.store.InvalidTokenError:
            msg = 'Invalid access token: %s' % oauth_request.get_parameter(
                'oauth_token')
            raise exceptions.AuthenticationFailed(msg)

        try:
            self.validate_token(request, consumer, token)
        except oauth.Error as err:
            raise exceptions.AuthenticationFailed(err.message)

        user = token.user

        if not user.is_active:
            msg = 'User inactive or deleted: %s' % user.username
            raise exceptions.AuthenticationFailed(msg)

        return (token.user, token)