Esempio n. 1
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)
Esempio n. 2
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'
Esempio 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)
    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)
Esempio n. 5
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.')))
Esempio n. 6
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
    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)
Esempio n. 8
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
Esempio n. 9
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
Esempio 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'
Esempio 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.')))
Esempio 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)
Esempio 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)
Esempio n. 14
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'
Esempio n. 15
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'    
Esempio n. 16
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)
    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)