Пример #1
0
    def test_init(self):
        server = oauth.Server(
            signature_methods={'HMAC-SHA1': oauth.SignatureMethod_HMAC_SHA1()})
        self.assertTrue('HMAC-SHA1' in server.signature_methods)
        self.assertTrue(
            isinstance(server.signature_methods['HMAC-SHA1'],
                       oauth.SignatureMethod_HMAC_SHA1))

        server = oauth.Server()
        self.assertEquals(server.signature_methods, {})
def initialize_oauth_server_request(request):
    """
    OAuth initialization.
    """

    # Since 'Authorization' header comes through as 'HTTP_AUTHORIZATION', convert it back
    auth_header = {}
    if 'HTTP_AUTHORIZATION' in request.META:
        auth_header = {'Authorization': request.META.get('HTTP_AUTHORIZATION')}

    absolute_uri = request.build_absolute_uri()
    url = absolute_uri
    if absolute_uri.find('?') != -1:
        url = absolute_uri[:absolute_uri.find('?')]

    oauth_request = oauth2.Request.from_request(request.method,
                                                url,
                                                headers=auth_header,
                                                parameters=dict(
                                                    request.REQUEST.items()))

    if oauth_request:
        oauth_server = oauth2.Server(
            signature_methods={
                # Supported signature methods
                'HMAC-SHA1': oauth2.SignatureMethod_HMAC_SHA1()
            })

    else:
        oauth_server = None

    return oauth_server, oauth_request
Пример #3
0
def verify_oauth_request(request, oauth_request, consumer, token=None):
    """ Helper function to verify requests. """
    from store import store

    # Check nonce
    if not store.check_nonce(request, oauth_request,
                             oauth_request['oauth_nonce']):
        return False

    # Verify request
    try:
        oauth_server = oauth.Server()
        oauth_server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
        oauth_server.add_signature_method(oauth.SignatureMethod_PLAINTEXT())

        # Ensure the passed keys and secrets are ascii, or HMAC will complain.
        consumer = oauth.Consumer(consumer.key.encode('ascii', 'ignore'),
                                  consumer.secret.encode('ascii', 'ignore'))
        if token is not None:
            token = oauth.Token(token.key.encode('ascii', 'ignore'),
                                token.secret.encode('ascii', 'ignore'))

        oauth_server.verify_request(oauth_request, consumer, token)
    except oauth.Error, err:
        logger.error('OAuth-request verification error',
                     extra={'data': {
                         'error': err.message
                     }})
        return False
Пример #4
0
def initialize_oauth_server_request(request):
    """
    OAuth initialization.
    """

    # Since 'Authorization' header comes through as 'HTTP_AUTHORIZATION',
    # convert it back.
    auth_header = {}
    if 'HTTP_AUTHORIZATION' in request.META:
        auth_header = {'Authorization': request.META.get('HTTP_AUTHORIZATION')}

    url = urljoin(settings.SITE_URL, request.path)

    # Note: we are only signing using the QUERY STRING. We are not signing the
    # body yet. According to the spec we should be including an oauth_body_hash
    # as per:
    #
    # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/drafts/1/spec.html
    #
    # There is no support in python-oauth2 for this yet. There is an
    # outstanding pull request for this:
    #
    # https://github.com/simplegeo/python-oauth2/pull/110
    #
    # Or time to move to a better OAuth implementation.
    oauth_request = oauth2.Request.from_request(
            request.method, url, headers=auth_header,
            query_string=request.META['QUERY_STRING'])
    oauth_server = oauth2.Server(signature_methods={
        'HMAC-SHA1': oauth2.SignatureMethod_HMAC_SHA1()
        })
    return oauth_server, oauth_request
Пример #5
0
    def _validate_lti_Irequest_signature(self, i_req):
        """
        Function that validates an LTI request by
        recreating the signature and comparing
        this with the provided signature.
        For this we require that the LTI request
        is wrapped in a Irequest(Internal request)
        object.
        For this it uses the python3-oauth2 libary.
        source:
        https://github.com/i-kiwamu/python3-oauth2/blob/master/oauth2/__init__.py

        If the LTI request is invalid, we throw an
        InvalidLTIRequest exception and log the error.
        """
        oauth_server = oauth2.Server()
        signature_method = oauth2.SignatureMethod_HMAC_SHA1()
        oauth_server.add_signature_method(signature_method)
        consumer = oauth2.Consumer('consumerKey', 'test')  # Test values
        oauth_request = oauth2.Request.from_request(i_req.method, i_req.url,
                                                    i_req.headers, i_req.body)

        try:
            oauth_server.verify_request(oauth_request, consumer, {})
        except Exception as e:
            print(e)  # debug
            raise InvalidLTIRequest
Пример #6
0
def initialize_server_request(request):
    """Shortcut for initialization."""
    # Django converts Authorization header in HTTP_AUTHORIZATION
    # Warning: it doesn't happen in tests but it's useful, do not remove!
    auth_header = {}
    if 'Authorization' in request.META:
        auth_header = {'Authorization': request.META['Authorization']}
    elif 'HTTP_AUTHORIZATION' in request.META:
        auth_header =  {'Authorization': request.META['HTTP_AUTHORIZATION']}
   
    # Don't include extra parameters when request.method is POST and 
    # request.MIME['CONTENT_TYPE'] is "application/x-www-form-urlencoded" 
    # (See http://oauth.net/core/1.0a/#consumer_req_param).
    # But there is an issue with Django's test Client and custom content types
    # so an ugly test is made here, if you find a better solution...
    parameters = {}
    if request.method == "POST" and \
        (request.META.get('CONTENT_TYPE') == "application/x-www-form-urlencoded" \
            or request.META.get('SERVER_NAME') == 'testserver'):
        parameters = dict((k, v.encode('utf-8')) for (k, v) in request.REQUEST.iteritems())

    oauth_request = oauth.Request.from_request(request.method, 
                                              request.build_absolute_uri(request.path), 
                                              headers=auth_header,
                                              parameters=parameters,
                                              query_string=request.META.get('QUERY_STRING', ''))
    if oauth_request:
        oauth_server = oauth.Server()
        if 'plaintext' in OAUTH_SIGNATURE_METHODS:
            oauth_server.add_signature_method(oauth.SignatureMethod_PLAINTEXT())
        if 'hmac-sha1' in OAUTH_SIGNATURE_METHODS:
            oauth_server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
    else:
        oauth_server = None
    return oauth_server, oauth_request
Пример #7
0
    def test_no_version(self):
        url = "http://sp.example.com/"

        params = {
            'oauth_nonce': "4572616e48616d6d65724c61686176",
            'oauth_timestamp': int(time.time()),
            'bar': 'blerg',
            'multi': ['FOO', 'BAR'],
            'foo': 59
        }

        self.consumer = oauth.Consumer(key="consumer-key",
                                       secret="consumer-secret")
        self.token = oauth.Token(key="token-key", secret="token-secret")

        params['oauth_token'] = self.token.key
        params['oauth_consumer_key'] = self.consumer.key
        self.request = oauth.Request(method="GET", url=url, parameters=params)

        signature_method = oauth.SignatureMethod_HMAC_SHA1()
        self.request.sign_request(signature_method, self.consumer, self.token)

        server = oauth.Server()
        server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())

        parameters = server.verify_request(self.request, self.consumer,
                                           self.token)
Пример #8
0
    def test_missing_signature(self):
        url = "http://sp.example.com/"

        params = {
            'oauth_version': '1.0',
            'oauth_nonce': "4572616e48616d6d65724c61686176",
            'oauth_timestamp': int(time.time()),
            'bar': 'blerg',
            'multi': ['FOO', 'BAR'],
            'foo': 59
        }

        consumer = oauth.Consumer(key="consumer-key", secret="consumer-secret")
        token = oauth.Token(key="token-key", secret="token-secret")

        params['oauth_token'] = token.key
        params['oauth_consumer_key'] = consumer.key
        request = oauth.Request(method="GET", url=url, parameters=params)

        signature_method = oauth.SignatureMethod_HMAC_SHA1()
        request.sign_request(signature_method, consumer, token)
        del request['oauth_signature']

        server = oauth.Server()
        server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())

        self.assertRaises(oauth.MissingSignature, server.verify_request,
                          request, consumer, token)
Пример #9
0
def verify_oauth_request(request, oauth_request, consumer, token=None):
    """ Helper function to verify requests. """
    from treeio.core.api.auth.store import store

    # Check nonce
    if not store.check_nonce(request, oauth_request,
                             oauth_request['oauth_nonce']):
        return False

    # Verify request
    try:
        oauth_server = oauth.Server()
        oauth_server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
        oauth_server.add_signature_method(oauth.SignatureMethod_PLAINTEXT())

        # Ensure the passed keys and secrets are ascii, or HMAC will complain.
        consumer = oauth.Consumer(consumer.key.encode('ascii', 'ignore'),
                                  consumer.secret.encode('ascii', 'ignore'))
        if token is not None:
            token = oauth.Token(token.key.encode('ascii', 'ignore'),
                                token.secret.encode('ascii', 'ignore'))

        oauth_server.verify_request(oauth_request, consumer, token)
    except oauth.Error:
        return False

    return True
Пример #10
0
 def getInstance(cls):
     if cls._instance == None:
         cls._instance = oauth.Server()
         cls._instance.add_signature_method(
             oauth.SignatureMethod_PLAINTEXT())
         cls._instance.add_signature_method(
             oauth.SignatureMethod_HMAC_SHA1())
     return cls._instance
Пример #11
0
    def __init__(self):
        super(RequestValidatorMixin, self).__init__()

        self.oauth_server = oauth2.Server()
        signature_method = oauth2.SignatureMethod_HMAC_SHA1()
        self.oauth_server.add_signature_method(signature_method)
        self.oauth_consumer = oauth2.Consumer(self.consumer_key,
                                              self.consumer_secret)
Пример #12
0
    def index(self, *args, **kwargs):
        try:
            server = oauth2.Server()
            server.add_signature_method(oauth2.SignatureMethod_HMAC_SHA1())
            req = oauth2.Request.from_request(request.method, request.url,
                                              request.headers, request.params,
                                              request.query_string)
            params = server.verify_request(
                req, oauth2.Consumer(self.key, self.secret), None)
        except:
            log.debug('LTI Tool Provider OAuth Error', exc_info=True)
            flash('LTI Tool Provider OAuth Error', 'error')
            abort(403)
        else:
            log.debug(params)

        user_name = (
            params.get('tool_consumer_info_product_family_code', 'external') +
            '_' + params.get('tool_consumer_instance_guid', 'external') + '_' +
            params.get('user_id'))

        user = User.query.filter_by(user_name=user_name).first()
        if not user:
            log.info('New user %s', user_name)
            user = User(
                user_name=user_name,
                display_name=params.get('lis_person_name_full'),
                email_address=params.get('lis_person_contact_email_primary'),
            )
            DBSession.add(user)

        submission = Submission.query.filter(
            Submission.assignment == self.assignment,
            Submission.user == user).first()
        if not submission:
            submission = Submission(
                assignment=self.assignment,
                filename=self.assignment.submission_filename or None,
                source=self.assignment.submission_template or None,
                language=self.assignment.allowed_languages[0],
                user=user,
                created=datetime.now(),
                modified=datetime.now(),
            )
            DBSession.add(submission)

            DBSession.flush()

        session['lti'] = True
        session['params'] = params
        session['user'] = user.id
        session['submission'] = submission.id
        session.save()

        redirect('/lti/%d/edit' % self.assignment.id)
Пример #13
0
    def _wrap_oauth(request, *args, **kwargs):
        project = kwargs.get('project', None)

        ###
        # Until the production environment for talos can make use of
        # OAuth or use API/Keys we need to bypass OAuth to injest data.
        # This needs to be removed as soon as talos can support OAuth.
        ###
        if project in ['talos', 'views']:
            return func(request, *args, **kwargs)

        dm = PerformanceTestModel(project)

        #Get the consumer key
        key = request.REQUEST.get('oauth_consumer_key', None)

        if key is None:
            result = {"status": "No OAuth credentials provided."}
            return HttpResponse(json.dumps(result),
                                content_type=APP_JS,
                                status=403)

        try:
            #Get the consumer secret stored with this key
            ds_consumer_secret = dm.get_oauth_consumer_secret(key)
        except DatasetNotFoundError:
            result = {"status": "Unknown project '%s'" % project}
            return HttpResponse(json.dumps(result),
                                content_type=APP_JS,
                                status=404)

        #Construct the OAuth request based on the django request object
        req_obj = oauth.Request(request.method, request.build_absolute_uri(),
                                request.REQUEST, '', False)

        server = oauth.Server()

        #Get the consumer object
        cons_obj = oauth.Consumer(key, ds_consumer_secret)

        #Set the signature method
        server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())

        try:
            #verify oauth django request and consumer object match
            server.verify_request(req_obj, cons_obj, None)
        except oauth.Error:
            status = 403
            result = {"status": "Oauth verification error."}
            return HttpResponse(json.dumps(result),
                                content_type=APP_JS,
                                status=status)

        return func(request, *args, **kwargs)
Пример #14
0
    def test_verify_request(self):
        server = oauth.Server()
        server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())

        parameters = server.verify_request(self.request, self.consumer,
                                           self.token)

        self.assertTrue('bar' in parameters)
        self.assertTrue('foo' in parameters)
        self.assertEquals(parameters['bar'], 'blerg')
        self.assertEquals(parameters['foo'], 59)
Пример #15
0
    def check_oauth(self, username, method, url, auth, query):
        """
        Check OAuth header credentials.
        Return None if the credentials are invalid

        :type username: str
        :param username: username corresponding to credentials

        :type method: str
        :param method: http method

        :type url: str
        :param url: request url

        :type auth: str
        :param auth: http authorization header value

        :type query: str
        :param query: http request query string

        :rtype: str or None
        :return: user login corresponding to the credentials
        """
        is_consumer = False
        headers = {'Authorization': auth}
        req = oauth2.Request.from_request(method,
                                          url,
                                          headers,
                                          query_string=query)

        if not req:
            return None, is_consumer

        if not (config.has_option('oauth', 'oauth_key')
                and config.has_option('oauth', 'oauth_secret')):
            _logger.error(
                _("Attempting OAuth authentication and you do not have oauth_key and "
                  "oauth_secret in pulp.conf"))
            return None, is_consumer

        key = config.get('oauth', 'oauth_key')
        secret = config.get('oauth', 'oauth_secret')

        consumer = oauth2.Consumer(key=key, secret=secret)
        server = oauth2.Server()
        server.add_signature_method(oauth2.SignatureMethod_HMAC_SHA1())

        try:
            # this call has a return value, but failures are noted by the exception
            server.verify_request(req, consumer, None)
        except oauth2.Error, e:
            _logger.error('error verifying OAuth signature: %s' % e)
            return None, is_consumer
Пример #16
0
    def view(request, *args, **kwargs):
        authorized = False
        json_params = {}
        oauth_params = {}

        try:
            for key in request.GET:
                if key.startswith("oauth"):
                    oauth_params[key] = request.GET.get(key)
                else:
                    json_params = json.loads(key)

            for key in request.POST:
                if key.startswith("oauth"):
                    oauth_params[key] = request.POST.get(key)

            key = oauth_params.get("oauth_consumer_key", None)
            host = "%s://%s" % (
                'https' if request.is_secure() else 'http',
                request.get_host(),
            )
            uurl = host + request.path

            oreq = oauth.Request(request.method, uurl, oauth_params, '', False)
            server = oauth.Server()

            secret = None
            rpctoken = RPCToken.objects.get(key=key)
            if rpctoken:
                secret = rpctoken.secret

            if not key or not secret:
                raise Exception

            try:
                cons = oauth.Consumer(key, secret)
                server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
                server.verify_request(oreq, cons, None)
                authorized = True

            except Exception, e:
                log.debug("auth error = %s" % e)
                authorized = False

            if request.method == "POST":
                method = json_params.get("method")

                if method in ('plugins.is_authenticated', ):
                    authorized = True

            if authorized:
                return func(request, *args, **kwargs)
Пример #17
0
    def __init__(self, handlers):
                
        settings = {
            'template_path': os.path.abspath(os.path.join(os.path.dirname(__main__.__file__), "templates")),
            'static_path': os.path.abspath(os.path.join(os.path.dirname(__main__.__file__), "static"))
        }
        
        if 'tornado' in config:
            tornado_settings = config['tornado']
            for key in tornado_settings.keys():
                settings[key] = tornado_settings[key]        

        tornado.web.Application.__init__(self, handlers, **settings)
        
        if 'mysql' in config:
            log.info("--> tornado initializing mysql")
            import database
            try:
                self.db = database.Connection()
            except Exception as e:
                log.error("Could not connect to MySQL: %s" % log.exc(e))   
        elif 'mongo' in config:    
            log.info("--> tornado initializing mongo")
            try:
                mongo = config['mongo']
                import pymongo                
                connection = pymongo.Connection(mongo['host'])
                self.db = connection[mongo['database']]
            except Exception as e:
                log.error("Could not connect to mongo: %s" % log.exc(e))
        if 'redis' in config:
            log.info("--> tornado initializing redis")
            import redis
            self.redis = redis.StrictRedis()
        if 'memcache' in config:
            log.info("--> torando initializing memcache")
            import memcache
            self.cache = memcache.Client([config['memcache']['address'] + ":" + str(config['memcache']['port'])])
            
        self.jobs = None    
        if 'beanstalk' in config:    
            log.info("--> tornado initializing beanstalk")
            import jobs
            self.jobs = jobs.Jobs()  
            
        # intialize oauth server
        try:
            self.oauth_server = oauth2.Server(signature_methods={'HMAC-SHA1': oauth2.SignatureMethod_HMAC_SHA1()})                                                    
        except ImportError:
            self.oauth_server = None
            
        Application.instance = self          
Пример #18
0
def is_valid_request(consumer_key, consumer_secret, request):
    oauth_server = oauth2.Server()
    oauth_server.add_signature_method(Python3SignatureMethodHMACSHA1())
    oauth_consumer = oauth2.Consumer(consumer_key, consumer_secret)
    try:
        oauth_request = oauth2.Request.from_request(
            request.method, request.build_absolute_uri(),
            headers=request.META, parameters=request.POST.dict()
        )
        oauth_server.verify_request(oauth_request, oauth_consumer, {})
    except oauth2.MissingSignature:
        return False
    return True
Пример #19
0
    def __init__(self, key, secret):
        """
        Constructor which creates a consumer object with the given key and
        secret.
        """
        super(OAuthRequestValidater, self).__init__()
        self.consumer_key = key
        self.consumer_secret = secret

        self.oauth_server = oauth2.Server()
        signature_method = oauth2.SignatureMethod_HMAC_SHA1()
        self.oauth_server.add_signature_method(signature_method)
        self.oauth_consumer = oauth2.Consumer(self.consumer_key, self.consumer_secret)
Пример #20
0
    def test_add_signature_method(self):
        server = oauth.Server()
        res = server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
        self.assertTrue(len(res) == 1)
        self.assertTrue('HMAC-SHA1' in res)
        self.assertTrue(
            isinstance(res['HMAC-SHA1'], oauth.SignatureMethod_HMAC_SHA1))

        res = server.add_signature_method(oauth.SignatureMethod_PLAINTEXT())
        self.assertTrue(len(res) == 2)
        self.assertTrue('PLAINTEXT' in res)
        self.assertTrue(
            isinstance(res['PLAINTEXT'], oauth.SignatureMethod_PLAINTEXT))
Пример #21
0
def initialize_server_request(request):
    """Shortcut for initialization."""
    oauth_request = get_oauth_request(request)

    if oauth_request:
        oauth_server = oauth.Server()
        if 'plaintext' in OAUTH_SIGNATURE_METHODS:
            oauth_server.add_signature_method(oauth.SignatureMethod_PLAINTEXT())
        if 'hmac-sha1' in OAUTH_SIGNATURE_METHODS:
            oauth_server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
    else:
        oauth_server = None
    return oauth_server, oauth_request
Пример #22
0
    def authenticate(self, request):

        if not self.auth_detected(request):
            return None

        user = request.resolver_match.kwargs.get(
            'project') or request.query_params['user']
        project_credentials = OAuthCredentials.get_credentials(user)

        if not project_credentials:
            raise exceptions.ValidationError(
                'project {0} has no OAuth credentials'.format(user))
        parameters = OAuthCredentials.get_parameters(request.query_params)

        oauth_consumer_key = parameters['oauth_consumer_key']

        if oauth_consumer_key != project_credentials['consumer_key']:
            raise exceptions.AuthenticationFailed(
                'oauth_consumer_key does not match credentials for project {0}'
                .format(user))

        uri = '{0}://{1}{2}'.format(settings.TREEHERDER_REQUEST_PROTOCOL,
                                    request.get_host(), request.path)
        # Construct the OAuth request based on the django request object
        json_renderer = JSONRenderer()
        req_obj = oauth.Request(
            method=request.method,
            url=uri,
            parameters=parameters,
            body=json_renderer.render(request.DATA),
        )
        server = oauth.Server()
        token = oauth.Token(key='', secret='')
        # Get the consumer object
        cons_obj = oauth.Consumer(oauth_consumer_key,
                                  project_credentials['consumer_secret'])
        # Set the signature method
        server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())

        try:
            # verify oauth django request and consumer object match
            server.verify_request(req_obj, cons_obj, token)
        except oauth.Error:
            raise exceptions.AuthenticationFailed(
                'Client authentication failed for project {0}'.format(user))
        request.legacy_oauth_authenticated = True
        return (DummyUser(), None)
Пример #23
0
def initialize_oauth_server_request(request):
    """
    OAuth initialization.
    """

    # Since 'Authorization' header comes through as 'HTTP_AUTHORIZATION',
    # convert it back.
    auth_header = {}
    if 'HTTP_AUTHORIZATION' in request.META:
        auth_header = {'Authorization': request.META.get('HTTP_AUTHORIZATION')}

    if not settings.SITE_URL:
        raise ValueError('SITE_URL cannot be blank')

    # Do this check on a combination of protocol, domain and path ignoring
    # querystrings.
    url = urljoin(settings.SITE_URL, request.path)
    parsed = list(urlparse(request.build_absolute_uri()))
    check = urlunparse(parsed[:3] + ['', '', ''])
    if check != url:
        log.warning('SITE_URL: {0} does not match request: {1} '
                    'This may cause OAuth failures.'.format(check, url))

    # Note: we are only signing using the QUERY STRING. We are not signing the
    # body yet. According to the spec we should be including an oauth_body_hash
    # as per:
    #
    # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/drafts/1/spec.html
    #
    # There is no support in python-oauth2 for this yet. There is an
    # outstanding pull request for this:
    #
    # https://github.com/simplegeo/python-oauth2/pull/110
    #
    # Or time to move to a better OAuth implementation.
    method = getattr(request, 'signed_method', request.method)
    oauth_request = oauth2.Request.from_request(
        method,
        url,
        headers=auth_header,
        query_string=request.META['QUERY_STRING'])
    oauth_server = oauth2.Server(
        signature_methods={'HMAC-SHA1': oauth2.SignatureMethod_HMAC_SHA1()})

    return oauth_server, oauth_request
Пример #24
0
    def check_request(self, request, mapper=None):

        http_method = request.method
        http_url = request.host_url + request.path_info
        headers = request.headers
        query_string = request.query_string
        info = None
        parameters = None

        # log.error("*** CHECK_REQUEST *** "+json.dumps({
        #     "query_string": query_string,
        #     "headers": {}.update(headers),
        #     "http_method": http_method,
        #     "http_url": http_url
        #     }))
        

        oa_request = oauth2.Request.from_request(http_method, http_url, headers, query_string=query_string)


        if oa_request and all([ x in oa_request for x in ['oauth_consumer_key', 'oauth_token']]):
            server = oauth2.Server()
            server.add_signature_method(oauth2.SignatureMethod_HMAC_SHA1())

            
            last_exc = None
            for row in self.find_possible(oa_request['oauth_consumer_key'], oa_request['oauth_token'], mapper):
                try:
                    parameters = server.verify_request(oa_request, row["consumer"], row["token"])
                except oauth2.Error as e:
                    last_exc = BadOAuthSignature("OAuth2 Error: %s" % e.message)
                except:
                    import sys
                    log.exception("Caught Exception in CouchDBOAuthUtil")
                    last_exc = BadOAuthSignature(sys.exc_info()[1])

                if parameters != None:
                    info = row
                    break

            if parameters == None and last_exc != None:
                raise last_exc

        return (parameters, info)
Пример #25
0
    def verify_access_token(self, request, key):

        uurl = "%s://%s%s" % (
            'https' if request.is_secure() else 'http',
            request.get_host(),
            request.path,
        )

        auth_header = {}
        if 'Authorization' in request.META:
            auth_header = {'Authorization': request.META['Authorization']}
        elif 'HTTP_AUTHORIZATION' in request.META:
            auth_header = {'Authorization': request.META['HTTP_AUTHORIZATION']}

        oreq = oauth2.Request.from_request(
            request.method,
            uurl,
            headers=auth_header,
            query_string=request.META.get('QUERY_STRING', None),
        )

        key = oreq.get("oauth_consumer_key", None)

        secret = None
        client = APIClient.objects.get(name=key)
        if client:
            secret = client.secret

        if not key or not secret:
            return False

        try:
            server = oauth2.Server()
            cons = oauth2.Consumer(key, secret)
            server.add_signature_method(oauth2.SignatureMethod_HMAC_SHA1())
            server.verify_request(oreq, cons, None)
            authorized = True
        except Exception:
            log.exception("auth2 error")
            authorized = False
        request.oauth2 = authorized

        return authorized
Пример #26
0
    def validate(self, request, params={}):
        oauth_server = oauth.Server()
        oauth_server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())

        oauth_request = oauth.Request.from_request(
            request.method,
            request.build_absolute_uri(),
            headers=request.META,
            parameters=params)

        if oauth_request:
            try:
                key = oauth_request.get_parameter('oauth_consumer_key')
                consumer = self.get_consumer(key)
                oauth_server._check_signature(oauth_request, consumer, None)
                return oauth_request.get_nonoauth_parameters()
            except oauth.Error as err:
                raise BLTIException(str(err))

        raise BLTIException('Invalid OAuth Request')
Пример #27
0
def validate_two_leg_oauth():
    """
  Verify 2-legged oauth request using values in "Authorization" header.
  """
    log.loggit('validate_two_leg_oauth()')
    parameters = web.input()
    if web.ctx.env.has_key('HTTP_AUTHORIZATION') and web.ctx.env[
            'HTTP_AUTHORIZATION'].startswith('OAuth '):
        parameters = split_header(web.ctx.env['HTTP_AUTHORIZATION'])

    # We have to reconstruct the original full URL used when signing
    # so if there are ever 401 errors verifying a request, look here first.
    req = oauth2.Request(web.ctx.env['REQUEST_METHOD'],
                         web.ctx['homedomain'] + web.ctx.env['REQUEST_URI'],
                         parameters=parameters)

    if not req.has_key('oauth_consumer_key'):
        raise web.unauthorized()

    # Verify the account referenced in the request is valid
    adb = accountdb.AccountDB()
    account = adb.review_account_using_info('consumer_key',
                                            req['oauth_consumer_key'])
    if not account:
        raise web.unauthorized(UNAUTHORIZED_MESSAGE)

    # Create an oauth2 Consumer with an account's consumer_key and consumer_secret
    # to be used to verify the request
    consumer = oauth2.Consumer(account['consumer_key'],
                               account['consumer_secret'])

    # Create our oauth2 Server and add hmac-sha1 signature method
    server = oauth2.Server()
    server.add_signature_method(oauth2.SignatureMethod_HMAC_SHA1())

    # Attempt to verify the authorization request via oauth2
    try:
        server.verify_request(req, consumer, None)
    except oauth2.Error, e:
        log.loggit('validate_two_leg_oauth() - %s %s' % (repr(e), str(e)))
        raise web.unauthorized(e)
Пример #28
0
    def __init__(self,
                 manager=DefaultManager,
                 realm='',
                 request_token_path='/oauth/request_token',
                 access_token_path='/oauth/access_token',
                 **kwargs):

        self.realm = realm
        # The oauth2 server implementation to handle signatures
        self.server = oauth2.Server(
            signature_methods={
                # Supported signature methods
                'HMAC-SHA1': oauth2.SignatureMethod_HMAC_SHA1(),
                'RSA-SHA1': SignatureMethod_RSA_SHA1(),
            })

        # Remember the paths to serve the tokens on
        self.paths = dict(request=request_token_path, access=access_token_path)

        # Allow manager to be provided as an entry point from config
        if isinstance(manager, (str, unicode)):
            manager = _resolve(manager)
        self.manager = manager(**kwargs)
Пример #29
0
def verify_oauth_request(request, oauth_request, consumer, token=None):
    """ Helper function to verify requests. """
    from store import store

    # Check nonce
    #print 'Nonce: %s' % store.check_nonce(request, oauth_request, oauth_request['oauth_nonce'], oauth_request['oauth_timestamp'])
    if not store.check_nonce(request, oauth_request,
                             oauth_request['oauth_nonce'],
                             oauth_request['oauth_timestamp']):
        #print 'nonce check fail'
        return False

    print 'Nonce: true'

    # Verify request
    try:
        oauth_server = oauth.Server()
        oauth_server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
        oauth_server.add_signature_method(oauth.SignatureMethod_PLAINTEXT())
        oauth_server.add_signature_method(SignatureMethod_RSA_SHA1())

        # Ensure the passed keys and secrets are ascii, or HMAC will complain.
        consumer = oauth.Consumer(consumer.key.encode('ascii', 'ignore'),
                                  consumer.secret.encode('ascii', 'ignore'))
        if token is not None:
            token = oauth.Token(token.key.encode('ascii', 'ignore'),
                                token.secret.encode('ascii', 'ignore'))

        print 'normalized parameters: %s' % oauth_request.get_normalized_parameters(
        )

        oauth_server.verify_request(oauth_request, consumer, token)
    except oauth.Error as o:
        print o.message
        return False

    return True
Пример #30
0
class OAuth2LeggedAuthentication(object):
    """
    Two-leggeed OAuth authentication.

    Based on:

    piston.authentication.OAuthAuthentication
    http://philipsoutham.com/post/2172924723/two-legged-oauth-in-python
    https://github.com/simplegeo/python-oauth2/blob/master/oauth2/__init__.py
    http://status.smugmug.com/documentation/examples
    http://stackoverflow.com/questions/3587454/oauth-posting-json
    http://oauth.net/core/1.0/#anchor14
    http://sites.google.com/site/oauthgoog/2leggedoauth/2opensocialrestapi

    """

    oauth_server = oauth2.Server(
        signature_methods={
            # Supported signature methods
            'HMAC-SHA1': oauth2.SignatureMethod_HMAC_SHA1(),
            #'PLAINTEXT': oauth2.SignatureMethod_PLAINTEXT(),
        })

    def __init__(self, realm='API'):
        self.realm = realm
        #self.builder = oauth.build_authenticate_header

    def is_authenticated(self, request):
        """
        Checks whether the required parameters are either in
        the http-authorization header sent by some clients,
        which is by the way the preferred method according to
        OAuth spec, but otherwise fall back to `GET` and `POST`.

        Checks whether a means of specifying authentication
        is provided, and if so, if it is a valid token.

        If authenticate successful, the user attribute on request
        is set.
        """
        auth_header = request.META
        if 'HTTP_AUTHORIZATION' in auth_header and not 'Authorization' in auth_header:
            auth_header['Authorization'] = auth_header['HTTP_AUTHORIZATION']

        req = oauth2.Request.from_request(
            request.method, request.build_absolute_uri(request.path),
            auth_header, dict(request.REQUEST))
        if not req:
            return False

        try:
            consumer = Consumer.objects.get(key=req.get('oauth_consumer_key'))
        except Consumer.DoesNotExist:
            msg = 'OAuth2Legged failed to find the Consumer with key %s' % req.get(
                'oauth_consumer_key')
            logger.error(msg)
            return False

        try:
            self.oauth_server.verify_request(req, consumer, None)
        except oauth2.Error, e:
            msg = 'OAuth2Legged failed verify signed request for consumer(key=%s, secret=%s) error: %s' % (
                consumer.key, consumer.secret, e)
            logger.error(msg)
            return False
        request.user = consumer.user
        return True