def run_example():

    # setup
    print '** OAuth Python Library Example **'
    client = SimpleOAuthClient(REQUEST_TOKEN_URL, ACCESS_TOKEN_URL,
                               AUTHORIZATION_URL)
    consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
    signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT()
    signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
    pause()

    # get request token
    print '* Obtain a request token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer, callback=CALLBACK_URL, http_url=client.request_token_url)
    oauth_request.sign_request(signature_method_plaintext, consumer, None)
    print 'REQUEST (via headers)'
    pause()
    token = client.fetch_request_token(oauth_request)
    print 'GOT'
    print 'key: %s' % str(token.key)
    print 'secret: %s' % str(token.secret)
    print 'callback confirmed? %s' % str(token.callback_confirmed)
    pause()

    print '* Authorize the request token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_token_and_callback(
        token=token, http_url=client.authorization_url)
    print 'REQUEST (via url query string)'
    pause()

    response = client.authorize_token(oauth_request)
    print 'GOT'
    print response
    #  get the verifier
    query = urlparse.urlparse(response)[4]
    params = cgi.parse_qs(query, keep_blank_values=False)
    verifier = params['oauth_verifier'][0]
    print 'verifier: %s' % verifier
    pause()

    # get access token
    print '* Obtain an access token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer,
        token=token,
        verifier=verifier,
        http_url=client.access_token_url)
    oauth_request.sign_request(signature_method_plaintext, consumer, token)
    print 'REQUEST (via headers)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    token = client.fetch_access_token(oauth_request)
    print 'GOT'
    print 'key: %s' % str(token.key)
    print 'secret: %s' % str(token.secret)
    pause()

    # access some protected resources
    print '* Access protected resources ...'
    pause()

    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer, token=token, http_method='GET', http_url=RESOURCE_URL)
    oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)

    print 'REQUEST (via get)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()

    resource = client.access_resource(oauth_request)

    print 'GOT'
    print 'resource:\n %s' % resource
    pause()
Exemplo n.º 2
0
import urllib
import mimetypes
import mimetools
import logging

from oauth import oauth

from twisted.application import service
from twisted.internet import defer, reactor, endpoints
from twisted.internet import error as ierror
from twisted.python import failure, log
from twisted.web import client, error, http_headers

from twittytwister import streaming, txml

SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1()

BASE_URL = "https://api.twitter.com"
SEARCH_URL = "http://search.twitter.com/search.atom"

logger = logging.getLogger('twittytwister.twitter')


##### ugly hack to work around a bug on HTTPDownloader on Twisted 8.2.0 (fixed on 9.0.0)
def install_twisted_fix():
    orig_method = client.HTTPDownloader.gotHeaders

    def gotHeaders(self, headers):
        client.HTTPClientFactory.gotHeaders(self, headers)
        orig_method(self, headers)
Exemplo n.º 3
0
def run_example():

    # setup
    print '** OAuth Python Library Example **'
    client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL,
                               ACCESS_TOKEN_URL, AUTHORIZATION_URL)
    consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
    signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT()
    signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
    pause()

    # get request token
    print '* Obtain a request token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer, callback=CALLBACK_URL, http_url=client.request_token_url)
    oauth_request.sign_request(signature_method_plaintext, consumer, None)
    print 'REQUEST (via headers)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    token = client.fetch_request_token(oauth_request)
    print 'GOT'
    print 'key: %s' % str(token.key)
    print 'secret: %s' % str(token.secret)
    print 'callback confirmed? %s' % str(token.callback_confirmed)
    pause()

    print '* Authorize the request token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_token_and_callback(
        token=token, http_url=client.authorization_url)
    print 'REQUEST (via url query string)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    # this will actually occur only on some callback
    response = client.authorize_token(oauth_request)
    print 'GOT'
    print response
    # sad way to get the verifier
    import urlparse, cgi
    query = urlparse.urlparse(response)[4]
    params = cgi.parse_qs(query, keep_blank_values=False)
    verifier = params['oauth_verifier'][0]
    print 'verifier: %s' % verifier
    pause()

    # get access token
    print '* Obtain an access token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer,
        token=token,
        verifier=verifier,
        http_url=client.access_token_url)
    oauth_request.sign_request(signature_method_plaintext, consumer, token)
    print 'REQUEST (via headers)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    token = client.fetch_access_token(oauth_request)
    print 'GOT'
    print 'key: %s' % str(token.key)
    print 'secret: %s' % str(token.secret)
    pause()

    # access some protected resources
    print '* Access protected resources ...'
    pause()
    parameters = {
        'file': 'vacation.jpg',
        'size': 'original'
    }  # resource specific params
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer,
        token=token,
        http_method='POST',
        http_url=RESOURCE_URL,
        parameters=parameters)
    oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
    print 'REQUEST (via post body)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    params = client.access_resource(oauth_request)
    print 'GOT'
    print 'non-oauth parameters: %s' % params
    pause()
Exemplo n.º 4
0
    def decorator(*args, **kwargs):
        """
        Actual wrapper to handle LTI/OAuth
        """
        # pylint: disable=W0212

        # Get lti GET or POST params as dict
        if request.method == 'POST':
            params = request.form.to_dict()
        else:
            params = request.args.to_dict()
        log.debug(params)

        # If we are already authenticated and not requesting oauth, return
        if (session.get(LTI_SESSION_KEY, False)
                and not params.get('oauth_consumer_key', None)):
            return func(*args, **kwargs)

        # Clear session to ensure authorization is happening fresh for
        # each lti instance.
        for prop in LTI_PROPERTY_LIST:
            if session.get(prop, None):
                del session[prop]

        # Try and authentication if session is being initiated
        oauth_server = oauth.OAuthServer(LTIOAuthDataStore())
        oauth_server.add_signature_method(
            oauth.OAuthSignatureMethod_PLAINTEXT())
        oauth_server.add_signature_method(
            oauth.OAuthSignatureMethod_HMAC_SHA1())

        # Check header for SSL before selecting the url
        url = request.url
        if request.headers.get('X-Forwarded-Proto', 'http') == 'https':
            url = request.url.replace('http', 'https', 1)

        oauth_request = oauth.OAuthRequest.from_request(
            request.method,
            url,
            headers=dict(request.headers),
            parameters=params
        )

        if not oauth_request:
            log.info('Received non oauth request on oauth protected page')
            raise LTIException('This page requires a valid oauth session '
                               'or request')
        try:
            consumer = oauth_server._get_consumer(oauth_request)
            oauth_server._check_signature(oauth_request, consumer, None)
        except oauth.OAuthError as err:
            # Rethrow our own for nice error handling (don't print
            # error message as it will contain the key
            log.info(err.message)
            raise LTIException("OAuth error: Please check your key and secret")

        # All good to go, store all of the LTI params into a
        # session dict for use in views
        for prop in LTI_PROPERTY_LIST:
            if params.get(prop, None):
                session[prop] = params[prop]

        # Set logged in session key
        session[LTI_SESSION_KEY] = True

        return func(*args, **kwargs)
Exemplo n.º 5
0
#!/usr/bin/env python
# -*- coding=utf-8 -*-

import urllib2

import oauth.oauth as oauth
from requests import get, post

consumer_key = "9eab891a46e90644738442f4c03d461b"
consumer_secret = "acce8a65db9d239e8ba5d9865ac6a1d6"
oauth_token_key = "1436156-3139ae61a2a46f72254ea00f1fbcfda1"
oauth_token_secret = "706fcb982ed0e5e21de71cf62c176006"
token = ("oauth_token_secret=706fcb982ed0e5e21de71cf62c176006&"
         "oauth_token=1436156-3139ae61a2a46f72254ea00f1fbcfda1")

signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
oauth_token = oauth.OAuthToken(oauth_token_key, oauth_token_secret)


def request_to_header(request, realm=''):
    """Serialize as a header for an HTTPAuth request."""
    auth_header = 'OAuth realm="%s"' % realm
    if request.parameters:
        for k, v in request.parameters.iteritems():
            if k.startswith('oauth_') or k.startswith('x_auth_'):
                auth_header += ', %s="%s"' % (k, oauth.escape(str(v)))
    return {'Authorization': auth_header}


def fanfou_get(url="statuses/user_timeline", **kwargs):
Exemplo n.º 6
0
 def __init__(self, consumer, sig=oauth.OAuthSignatureMethod_HMAC_SHA1()):
     self.consumer = consumer
     self.signature_method = sig # TODO: support RSA_SHA1
     self.scopes = []
     self.access_token = self.req_token = None
Exemplo n.º 7
0
class FatSecretClient(object):
    SERVER = 'platform.fatsecret.com'
    PORT = 80
    SIGNER = oauth.OAuthSignatureMethod_HMAC_SHA1()
    HTTP_METHOD = 'GET'
    HTTP_HEADERS = {}
    HTTP_HEADERS_POST = {
        "Content-type": "application/x-www-form-urlencoded",
    }
    HTTP_HEADERS_GET = {}
    HTTP_URL = 'http://platform.fatsecret.com/rest/server.api'
    HTTP_RELURL = 'rest/server.api'

    OAUTH_REQTOK_URL = 'http://www.fatsecret.com/oauth/request_token'
    OAUTH_UAUTH_URL = 'http://www.fatsecret.com/oauth/authorize'
    OAUTH_ACCESS_URL = 'http://www.fatsecret.com/oauth/access_token'

    class _MethodProxy(object):
        def __init__(self, client, path):
            self.__client, self.__path = client, path

        def __getattr__(self, name):
            return FatSecretClient._MethodProxy(self.__client,
                                                self.__path + '.' + name)

        def __call__(self, *args, **kwargs):
            return self.request(self.__path, *args, **kwargs)

    def __getattr__(self, name):
        return self.__dict__.get(name,
                                 FatSecretClient._MethodProxy(self, name))

    def authorize(self, key=None):
        if not self.loadToken(key):
            token = self.getRequestToken()
            verifier = self.getUserAuthentication(token)
            self.authorizeRequestToken(verifier)
        result = self.profile.get()
        self.saveToken(key, self.token)
        return result

    def getRequestTokenCallback(self):
        #return 'http://localhost:56711'
        return 'oob'

    def getRequestToken(self):
        result = self._auth_request(
            OAUTH_CALLBACK=self.getRequestTokenCallback(),
            HTTP_METHOD='GET',
            HTTP_URL=self.OAUTH_REQTOK_URL)
        return self.token

    def getUserAuthentication(self, token):
        import webbrowser
        webbrowser.open('%s?%s' % (self.OAUTH_UAUTH_URL, token))
        return raw_input('Enter verification code: ')

    def authorizeRequestToken(self, verifier):
        result = self._auth_request(HTTP_METHOD='GET',
                                    VERIFIER=verifier,
                                    HTTP_URL=self.OAUTH_ACCESS_URL)
        return self.token

    AUTH_NONE = 0
    AUTH_SIGNED = 1
    AUTH_DELEGATE = 2
    __methods__ = {
        'food.add_favorite': AUTH_DELEGATE,
        'food.delete_favorite': AUTH_DELEGATE,
        'food.get': AUTH_SIGNED,
        'foods.get_favorites': AUTH_DELEGATE,
        'foods.get_most_eaten': AUTH_DELEGATE,
        'foods.get_recently_eaten': AUTH_DELEGATE,
        'foods.search': AUTH_SIGNED,
        'recipe.add_favorite': AUTH_DELEGATE,
        'recipe.delete_favorite': AUTH_DELEGATE,
        'recipe.get': AUTH_SIGNED,
        'recipes.get_favorites': AUTH_DELEGATE,
        'recipes.search': AUTH_SIGNED,
        'recipe_types.get': AUTH_SIGNED,
        'saved_meal.create': AUTH_DELEGATE,
        'saved_meal.delete': AUTH_DELEGATE,
        'saved_meal.edit': AUTH_DELEGATE,
        'saved_meals.get': AUTH_DELEGATE,
        'saved_meal_item.create': AUTH_DELEGATE,
        'saved_meal_item.create': AUTH_DELEGATE,
        'saved_meal_items.create': AUTH_DELEGATE,
        'exercises.get': AUTH_SIGNED,
        'profile.create': AUTH_SIGNED,
        'profile.get': AUTH_DELEGATE,
        'profile.get_auth': AUTH_SIGNED,
        'profile.request_script_session_key': AUTH_SIGNED,
        'food_entries.copy': AUTH_DELEGATE,
        'food_entries.copy_saved_meal': AUTH_DELEGATE,
        'food_entries.get': AUTH_DELEGATE,
        'food_entries.get_month': AUTH_DELEGATE,
        'food_entry.create': AUTH_DELEGATE,
        'food_entry.delete': AUTH_DELEGATE,
        'food_entry.edit': AUTH_DELEGATE,
        'exercise_entries.commit_day': AUTH_DELEGATE,
        'exercise_entries.get': AUTH_DELEGATE,
        'exercise_entries.get_month': AUTH_DELEGATE,
        'exercise_entries.save_template': AUTH_DELEGATE,
        'exercies_entry.edit': AUTH_DELEGATE,
        'weight.update': AUTH_SIGNED,
        'weights.get_month': AUTH_DELEGATE,
    }

    def __init__(self):
        self.application = None
        self.token = None
        self.datastore = None
        self._adjustAuthLevel()

    def setDatastore(self, datastore):
        self.datastore = datastore
        return self

    def getDatastore(self):
        return self.datastore

    def loadToken(self, key):
        if key and self.datastore:
            token = self.datastore.getToken(key)
            if token:
                self.setToken(token)
                return token
        return None

    def saveToken(self, key, token=None):
        if key and self.datastore:
            token = token or self.token
            self.datastore.putToken(key, token)
        return self

    def connect(self):
        self.connection = httplib.HTTPConnection('%s:%d' %
                                                 (self.SERVER, self.PORT))
        return self

    def setApplication(self, application):
        assert (issubclass(application, FatSecretApplication)
                or isinstance(application, FatSecretApplication)
                or application == None)

        if application:
            assert application.key != None
            assert application.secret != None

        self.application = application
        self._adjustAuthLevel()
        return self

    def setToken(self, token):
        assert (isinstance(token, oauth.OAuthToken) or token == None)
        self.token = token
        self._adjustAuthLevel()
        return self

    def _adjustAuthLevel(self):
        if self.token:
            self._authLevel = FatSecretClient.AUTH_DELEGATE
        elif self.application:
            self._authLevel = FatSecretClient.AUTH_SIGNED
        else:
            self._authLevel = FatSecretClient.AUTH_NONE

    def getMethods(self, current_auth=None):
        current_auth = current_auth or self.getCurrentAuthLevel()
        return [
            method for method, required_auth in self.__methods__.iteritems()
            if required_auth <= current_auth
        ]

    def getCurrentAuthLevel(self):
        return self._authLevel

    def _rpath(self, result, *args):
        args = list(args)
        while len(args):
            arg = args.pop(0)
            if arg in result:
                result = result[arg]
            else:
                return None

        if not len(args):
            return result
        else:
            return None

    def _auth_request(self, **parameters):
        http_method = parameters.pop('HTTP_METHOD', self.HTTP_METHOD)
        http_url = parameters.pop('HTTP_URL', self.HTTP_URL)
        http_headers = parameters.pop('HTTP_HEADERS', self.HTTP_HEADERS)
        callback = parameters.pop('OAUTH_CALLBACK', None)
        verifier = parameters.pop('VERIFIER', None)

        # Generate OAuth Request
        req = FSRequest.from_consumer_and_token(self.application,
                                                token=self.token,
                                                verifier=verifier,
                                                callback=callback,
                                                http_method=http_method,
                                                http_url=http_url,
                                                parameters=parameters)

        # Sign It
        req.sign_request(self.SIGNER, self.application, self.token)

        # Build HTTP Headers from OAuth + POST (if necessary)
        headers = req.to_header()
        headers.update(getattr(self, 'HTTP_HEADERS_%s' % self.HTTP_METHOD))

        # Customize httplib parameters as necessary
        if self.HTTP_METHOD in ['POST']:
            http_url = req.http_url
            postdata = req.to_postdata()
        else:
            http_url = req.to_url()
            postdata = None

        # Let's go!
        follow_redirects = 3
        arrived = False
        while not arrived and follow_redirects:
            self.connection.request(req.http_method, http_url, postdata,
                                    headers)
            resp = self.connection.getresponse()
            if resp.status in [301, 307]:
                resp.read()
                http_url = resp.getheader('Location', http_url)
                follow_redirects -= 1
            else:
                # All other codes either we're good or we failed...
                arrived = True

        result = resp.read()
        try:
            if result.find('oauth_token') != -1:
                self.setToken(FSToken.from_string(result))
        except:
            # TODO: Figure out why we got this exception and how to fix it...
            raise

        return result

    def request(self, method, **parameters):
        #assert method in self.getMethods()
        parameters['method'] = method
        parameters['format'] = 'json'

        if self.getCurrentAuthLevel() <= FatSecretClient.AUTH_NONE:
            req = FSRequest(self.HTTP_METHOD, self.HTTP_URL, parameters)
        else:
            req = FSRequest.from_consumer_and_token(
                self.application,
                token=self.token,
                http_method=self.HTTP_METHOD,
                http_url=self.HTTP_URL,
                parameters=parameters)

            req.sign_request(self.SIGNER, self.application, self.token)

        # Generate httplib arguments
        headers = req.to_header()
        headers.update(getattr(self, 'HTTP_HEADERS_%s' % self.HTTP_METHOD))
        if self.HTTP_METHOD in ['POST']:
            http_url = req.http_url
            postdata = req.to_postdata()
        else:
            http_url = req.to_url()
            postdata = None

        # Make the request
        self.connection.request(req.http_method, http_url, postdata, headers)
        resp = self.connection.getresponse()

        # Post-process the result
        result = json.load(resp)
        _rp = self._rpath
        if 'error' in result:
            raise BuildError(result)
        if _rp(result, 'profile', 'auth_token') and _rp(
                result, 'profile', 'auth_secret'):
            self.setToken(
                FSToken(
                    _rp(result, 'profile', 'auth_token').encode('utf8'),
                    _rp(result, 'profile', 'auth_secret').encode('utf8')))

        return result
Exemplo n.º 8
0
class Netflix(object):
    protocol = "http://"
    host = 'api.netflix.com'
    port = '80'
    request_token_url = 'http://api.netflix.com/oauth/request_token'
    access_token_url = 'http://api.netflix.com/oauth/access_token'
    authorization_url = 'https://api-user.netflix.com/oauth/login'
    signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
    http = urllib3.HTTPConnectionPool(host)

    def __init__(self, key, secret, application_name=None):
        self.consumer = oauth.OAuthConsumer(key, secret)
        self.application_name = application_name

    def object_hook(self, d):
        d = dict((str(k), v) for k, v in d.iteritems())

        def isa(label):
            return label in d and len(d) == 1

        if 'catalog_titles' in d:
            try:
                catalog_titles = d['catalog_titles']['catalog_title']
                if not isinstance(catalog_titles, list):
                    catalog_titles = [catalog_titles]
                return [CatalogTitle(di) for di in catalog_titles]
            except (KeyError, TypeError):
                return d['catalog_titles']
        elif isa('catalog_title'):
            try:
                return CatalogTitle(d['catalog_title'])
            except TypeError:
                return [CatalogTitle(i) for i in d['catalog_title']]
        elif isa('synopsis'):
            return d['synopsis']
        elif isa('delivery_formats'):
            availabilities = d['delivery_formats']['availability']
            if not isinstance(availabilities, list):
                availabilities = [availabilities]
            return [NetflixAvailability(o) for o in availabilities]
        elif isa('user'):
            return NetflixUser(d['user'])
        elif isa('rental_history'):
            return RentalHistory(d['rental_history'])
        elif isa('at_home'):
            return NetflixAtHome(d['at_home'])
        elif isa('queue'):
            return NetflixQueue(d['queue'])
        else:
            return d

    def get_request_token(self):
        oa_req = OAuthRequest.from_consumer_and_token(
            self.consumer, http_url=self.request_token_url)
        oa_req.sign_request(self.signature_method, self.consumer, None)
        req = self.http.get_url(self.request_token_url,
                                headers=oa_req.to_header())
        if not str(req.status).startswith('2'):
            self.analyze_error(req)
        return OAuthToken.from_string(req.data)

    def get_authorization_url(self, callback=None):
        """Return the authorization url and token."""
        token = self.get_request_token()
        parameters = dict(application_name=self.application_name)
        if callback:
            parameters['oauth_callback'] = callback
        oauth_request = OAuthRequest.from_consumer_and_token(
            self.consumer,
            token=token,
            parameters=parameters,
            http_url=self.authorization_url,
        )
        oauth_request.sign_request(self.signature_method, self.consumer, token)
        return oauth_request.to_url(), token

    def authorize(self, token):
        """Authorize a user with netflix and return a user id and an
        access token."""
        oa_req = OAuthRequest.from_consumer_and_token(
            self.consumer,
            token=token,
            parameters={'application_name': self.application_name}
            if self.application_name else None,
            http_url=self.access_token_url)

        oa_req.sign_request(self.signature_method, self.consumer, token)
        req = self.http.get_url(oa_req.to_url())
        if not str(req.status).startswith('2'):
            self.analyze_error(req)
        res = req.data
        logging.debug(res)
        id = cgi.parse_qs(res)['user_id'][0]

        return id, OAuthToken.from_string(res)

    def analyze_error(self, exc):
        error = exc.data
        try:
            error = json.loads(error)
            code = int(error['status']['status_code'])
            message = error['status']['message']
        except (KeyError, ValueError):
            code = exc.status
            message = error
        if code == 401:
            if message == "Access Token Validation Failed":
                raise AuthError(message)
            elif message == 'Invalid Signature':
                raise InvalidSignature(message)
            elif message == 'Invalid Or Expired Token':
                raise InvalidOrExpiredToken(message)
        elif code == 403:
            if 'Service is over queries per second limit' in message:
                raise TooManyRequestsPerSecondError()
            elif 'Over queries per day limit' in message:
                raise TooManyRequestsPerDayError()
        elif code == 404:
            raise NotFound(message)
        elif code == 400 and message == 'Missing Required Access Token':
            raise MissingAccessTokenError(message)
        elif code == 412 and message == 'Title is already in queue':
            raise TitleAlreadyInQueue()
        elif code >= 500:
            raise InternalNetflixError(message)

        raise NetflixError(code, message)

    @call_interval(0.25)
    def request(self, url, token=None, verb='GET', filename=None, **args):
        """`url` may be relative with regard to Netflix. Verb is a
        HTTP verb.

        """
        if isinstance(url, NetflixObject) and not isinstance(url, basestring):
            url = url.id
        if not url.startswith('http://'):
            url = self.protocol + self.host + url
        if 'output' not in args:
            args['output'] = 'json'
        args['method'] = verb.upper()

        # we don't want unicode in the parameters
        for k, v in args.iteritems():
            try:
                args[k] = v.encode('utf-8')
            except AttributeError:
                pass

        oa_req = OAuthRequest.from_consumer_and_token(self.consumer,
                                                      http_url=url,
                                                      parameters=args,
                                                      token=token)
        oa_req.sign_request(self.signature_method, self.consumer, token)
        if filename is None:

            def do_request():
                req = self.http.urlopen('GET', oa_req.to_url())
                if not str(req.status).startswith('2'):
                    self.analyze_error(req)
                return req
        else:

            def do_request():
                try:
                    subprocess.check_call([
                        "curl",
                        oa_req.to_url(), "--location", "--compressed",
                        "--output", filename
                    ])
                    sys.stderr.write('\nSaved to: %s\n' % filename)
                except OSError:
                    raise RuntimeError, "You need to have curl installed to use this command"

        try:
            req = do_request()
        except TooManyRequestsPerSecondError:
            time.sleep(1)
            req = do_request()
        if filename:
            return
        o = json.loads(req.data, object_hook=self.object_hook)
        return o

    def index(self, filename):
        self.request('/catalog/titles/index', output='xml', filename=filename)

    def full(self, filename):
        self.request('/catalog/titles/full',
                     output='xml',
                     v='1.5',
                     filename=filename)
Exemplo n.º 9
0
 def oauth_server(self):
     if  not hasattr(self, '_oauth_server'):
         self._oauth_server = oauth.OAuthServer(OAuthDataStore())
         self._oauth_server.add_signature_method(oauth.OAuthSignatureMethod_PLAINTEXT())
         self._oauth_server.add_signature_method(oauth.OAuthSignatureMethod_HMAC_SHA1())
     return self._oauth_server
Exemplo n.º 10
0
def run_example():
    import sys
    user_signature_method = (len(sys.argv) > 1 and sys.argv[1].lower()
                             or 'plaintext')

    # setup
    print '** OAuth Python Library Example **'
    client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL,
                               ACCESS_TOKEN_URL, AUTHORIZATION_URL)
    consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)

    signature_methods = {
        "plaintext": oauth.OAuthSignatureMethod_PLAINTEXT(),
        "hmac-sha1": oauth.OAuthSignatureMethod_HMAC_SHA1()
    }
    if USE_RSA:
        signature_methods[
            'rsa-sha1'] = oauth_rsa.TestOAuthSignatureMethod_RSA_SHA1()

    signature_method = signature_methods[user_signature_method]

    pause()

    # get request token
    print '* Obtain a request token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer, http_url=client.request_token_url)
    oauth_request.sign_request(signature_method, consumer, None)
    print 'REQUEST (via headers)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    token = client.fetch_request_token(oauth_request)
    print 'GOT'
    print 'key: %s' % str(token.key)
    print 'secret: %s' % str(token.secret)
    pause()

    print '* Authorize the request token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_token_and_callback(
        token=token, callback=CALLBACK_URL, http_url=client.authorization_url)
    print 'REQUEST (via url query string)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    # this will actually occur only on some callback
    response = client.authorize_token(oauth_request)
    print 'GOT'
    print response
    pause()

    # get access token
    print '* Obtain an access token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer, token=token, http_url=client.access_token_url)
    oauth_request.sign_request(signature_method, consumer, token)
    print 'REQUEST (via headers)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    token = client.fetch_access_token(oauth_request)
    print 'GOT'
    print 'key: %s' % str(token.key)
    print 'secret: %s' % str(token.secret)
    pause()

    # access some protected resources
    print '* Access protected resources ...'
    pause()
    parameters = {
        'file': 'vacation.jpg',
        'size': 'original',
        'oauth_callback': CALLBACK_URL
    }  # resource specific params
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer,
        token=token,
        http_method='POST',
        http_url=RESOURCE_URL,
        parameters=parameters)
    oauth_request.sign_request(signature_method, consumer, token)
    print 'REQUEST (via post body)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    params = client.access_resource(oauth_request)
    print 'GOT'
    print 'non-oauth parameters: %s' % params
    pause()
Exemplo n.º 11
0
 def __init__(self, consumer_key, consumer_secret, user_key, user_secret):
     self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
     self.consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
     self.access_token = oauth.OAuthToken(user_key, user_secret)
Exemplo n.º 12
0
 def __init__(self):
     self.consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
     self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
     self.update_access_token()
Exemplo n.º 13
0
    def _get(self, path, parse="message", post=False, single=False, **args):
        if not self.account.has_key(
                "access_token") and not self.account.has_key("secret_token"):
            log.logger.error("%s unexpected result - %s",
                             PROTOCOL_INFO["name"],
                             _("Account needs to be re-authorized"))
            return [{
                "error": {
                    "type": "auth",
                    "account": self.account,
                    "message": _("Account needs to be re-authorized")
                }
            }]

        url = "/".join((self.account["url_prefix"], "api", path))

        self.sigmethod = oauth.OAuthSignatureMethod_HMAC_SHA1()
        self.consumer = oauth.OAuthConsumer("anonymous", "anonymous")
        self.token = oauth.OAuthToken(self.account["access_token"],
                                      self.account["secret_token"])

        parameters = util.compact(args)
        request = oauth.OAuthRequest.from_consumer_and_token(
            self.consumer,
            self.token,
            http_method=post and "POST" or "GET",
            http_url=url,
            parameters=parameters)
        request.sign_request(self.sigmethod, self.consumer, self.token)

        if post:
            data = network.Download(request.to_url(), parameters,
                                    post).get_json()
        else:
            data = network.Download(request.to_url(), None, post).get_json()

        resources.dump(self.account["service"], self.account["id"], data)

        if isinstance(data, dict) and data.get("error", 0):
            log.logger.error("%s failure - %s", PROTOCOL_INFO["name"],
                             data["error"])
            if "authenticate" in data["error"]:
                return [{
                    "error": {
                        "type": "auth",
                        "account": self.account,
                        "message": data["error"]
                    }
                }]
            else:
                return [{
                    "error": {
                        "type": "unknown",
                        "account": self.account,
                        "message": data["error"]
                    }
                }]
        elif isinstance(data, str):
            log.logger.error("%s unexpected result - %s",
                             PROTOCOL_INFO["name"], data)
            return [{
                "error": {
                    "type": "unknown",
                    "account": self.account,
                    "message": data
                }
            }]

        if single: return [getattr(self, "_%s" % parse)(data)]
        if parse: return [getattr(self, "_%s" % parse)(m) for m in data]
        else: return []

        return [self._result(m) for m in data]
Exemplo n.º 14
0
 def __init__(self, *args, **kwargs):
     self.oauth_server = oauth.OAuthServer(MockOAuthDataStore())
     self.oauth_server.add_signature_method(oauth.OAuthSignatureMethod_PLAINTEXT())
     self.oauth_server.add_signature_method(oauth.OAuthSignatureMethod_HMAC_SHA1())
     BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
Exemplo n.º 15
0
#!/usr/bin/python2
import oauth.oauth as oauth
import httplib
import urllib

consumer = oauth.OAuthConsumer(
    key='401a131e03357df2a563fba48f98749448ed63d37e007f7353608cf81fa70a2d',
    secret='ba3f5945ba6cfb18ca4869cef2c3daf9d4230e37629f3087b281be6ec8fda2bd')
token = oauth.OAuthToken(
    '9476f5130a07a7c0061de48bc19123f51636af704c5df369701960e0bc151255',
    'b96fc9e22532b6bdc2fb760465ea19fa373c520703877ef7e3f0b6a728cefcb1')
RESOURCE_URL = 'http://127.0.0.1:8080/1/clipboard/update'
parameters = {'data': 'Hai there :D Can I be on your clipboard please? :3'}
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
    consumer,
    token=token,
    http_method='POST',
    http_url=RESOURCE_URL,
    parameters=parameters)
oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer,
                           token)
conn = httplib.HTTPConnection("%s:%d" % ('127.0.0.1', 8080))
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
headers.update(oauth_request.to_header())
conn.request('POST',
             RESOURCE_URL,
             headers=headers,
             body=urllib.urlencode(parameters))
response = conn.getresponse()
print response.read()
Exemplo n.º 16
0
 def __init__(self, access_key, access_secret):
   self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
   consumer_key, consumer_secret = read_consumer_key_and_secret()
   self.consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
   self.access_token = oauth.OAuthToken(access_key, access_secret)
Exemplo n.º 17
0
    def __init__(self, consumer, api_key,
            sig=oauth.OAuthSignatureMethod_HMAC_SHA1()):

        GoogleOAuthClient.__init__(self, consumer, sig=sig)
        self.api_key = api_key
        self.scopes += [self.scope_url]
Exemplo n.º 18
0
class HTTPClientBase(object):
    """Base class to make requests to a remote HTTP server."""

    # by default use HMAC-SHA1 OAuth signature method to not disclose
    # tokens
    # NB: given that the content bodies are not covered by the
    # signatures though, to achieve security (against man-in-the-middle
    # attacks for example) one would need HTTPS
    oauth_signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()

    # Will use these delays to retry on 503 befor finally giving up. The final
    # 0 is there to not wait after the final try fails.
    _delays = (1, 1, 2, 4, 0)

    def __init__(self, url, creds=None):
        self._url = urlparse.urlsplit(url)
        self._conn = None
        self._creds = {}
        if creds is not None:
            if len(creds) != 1:
                raise errors.UnknownAuthMethod()
            auth_meth, credentials = creds.items()[0]
            try:
                set_creds = getattr(self, 'set_%s_credentials' % auth_meth)
            except AttributeError:
                raise errors.UnknownAuthMethod(auth_meth)
            set_creds(**credentials)

    def set_oauth_credentials(self, consumer_key, consumer_secret, token_key,
                              token_secret):
        self._creds = {
            'oauth': (oauth.OAuthConsumer(consumer_key, consumer_secret),
                      oauth.OAuthToken(token_key, token_secret))
        }

    def _ensure_connection(self):
        if self._conn is not None:
            return
        if self._url.scheme == 'https':
            connClass = _VerifiedHTTPSConnection
        else:
            connClass = httplib.HTTPConnection
        self._conn = connClass(self._url.hostname, self._url.port)

    def close(self):
        if self._conn:
            self._conn.close()
            self._conn = None

    # xxx retry mechanism?

    def _error(self, respdic):
        descr = respdic.get("error")
        exc_cls = errors.wire_description_to_exc.get(descr)
        if exc_cls is not None:
            message = respdic.get("message")
            raise exc_cls(message)

    def _response(self):
        resp = self._conn.getresponse()
        body = resp.read()
        headers = dict(resp.getheaders())
        if resp.status in (200, 201):
            return body, headers
        elif resp.status in http_errors.ERROR_STATUSES:
            try:
                respdic = json.loads(body)
            except ValueError:
                pass
            else:
                self._error(respdic)
        # special case
        if resp.status == 503:
            raise errors.Unavailable(body, headers)
        raise errors.HTTPError(resp.status, body, headers)

    def _sign_request(self, method, url_query, params):
        if 'oauth' in self._creds:
            consumer, token = self._creds['oauth']
            full_url = "%s://%s%s" % (self._url.scheme, self._url.netloc,
                                      url_query)
            oauth_req = oauth.OAuthRequest.from_consumer_and_token(
                consumer,
                token,
                http_method=method,
                parameters=params,
                http_url=full_url)
            oauth_req.sign_request(self.oauth_signature_method, consumer,
                                   token)
            # Authorization: OAuth ...
            return oauth_req.to_header().items()
        else:
            return []

    def _request(self,
                 method,
                 url_parts,
                 params=None,
                 body=None,
                 content_type=None):
        self._ensure_connection()
        unquoted_url = url_query = self._url.path
        if url_parts:
            if not url_query.endswith('/'):
                url_query += '/'
                unquoted_url = url_query
            url_query += '/'.join(
                urllib.quote(part, safe='') for part in url_parts)
            # oauth performs its own quoting
            unquoted_url += '/'.join(url_parts)
        encoded_params = {}
        if params:
            for key, value in params.items():
                key = unicode(key).encode('utf-8')
                encoded_params[key] = _encode_query_parameter(value)
            url_query += ('?' + urllib.urlencode(encoded_params))
        if body is not None and not isinstance(body, basestring):
            body = json.dumps(body)
            content_type = 'application/json'
        headers = {}
        if content_type:
            headers['content-type'] = content_type
        headers.update(self._sign_request(method, unquoted_url,
                                          encoded_params))
        for delay in self._delays:
            try:
                self._conn.request(method, url_query, body, headers)
                return self._response()
            except errors.Unavailable, e:
                sleep(delay)
        raise e
Exemplo n.º 19
0
def _post_patched_request(consumers, lti_key, body, url, method, content_type):
    """
    Authorization header needs to be capitalized for some LTI clients
    this function ensures that header is capitalized

    :param body: body of the call
    :param client: OAuth Client
    :param url: outcome url
    :return: response
    """

    oauth_store = LTIOAuthDataStore(consumers)
    oauth_server = oauth.OAuthServer(oauth_store)
    oauth_server.add_signature_method(oauth.OAuthSignatureMethod_HMAC_SHA1())
    lti_consumer = oauth_store.lookup_consumer(lti_key)
    lti_cert = oauth_store.lookup_cert(lti_key)

    secret = lti_consumer.secret

    consumer = oauth2.Consumer(key=lti_key, secret=secret)
    client = oauth2.Client(consumer)

    if lti_cert:
        client.add_certificate(key=lti_cert, cert=lti_cert, domain='')
        log.debug("cert {}".format(lti_cert))

    import httplib2

    http = httplib2.Http
    # pylint: disable=protected-access
    normalize = http._normalize_headers

    def my_normalize(self, headers):
        """ This function patches Authorization header """
        ret = normalize(self, headers)
        if 'authorization' in ret:
            ret['Authorization'] = ret.pop('authorization')
        log.debug("headers")
        log.debug(headers)
        return ret

    http._normalize_headers = my_normalize
    monkey_patch_function = normalize

    # pylint: disable=unused-variable
    response, content = client.request(url,
                                       method,
                                       body=body,
                                       headers={'Content-Type': content_type})

    http = httplib2.Http
    # pylint: disable=protected-access
    http._normalize_headers = monkey_patch_function

    log.debug("key {}".format(lti_key))
    log.debug("secret {}".format(secret))
    log.debug("url {}".format(url))
    log.debug("response {}".format(response))
    log.debug("content {}".format(content))

    return response, content
Exemplo n.º 20
0
	def __init__(self, consumerKey, consumerSecret, token = None, tokenSecret = None, signatureMethod = oauth.OAuthSignatureMethod_HMAC_SHA1()):
		self.oauthConsumer = oauth.OAuthConsumer(consumerKey, consumerSecret)

		if token is not None and tokenSecret is not None:
			self.oauthToken = oauth.OAuthToken(token, tokenSecret)
		else:
			self.oauthToken = None

		self.signatureMethod = signatureMethod
Exemplo n.º 21
0
from twisted.internet import defer
from twisted.web import client as twclient
import oauth.oauth as oauth

logger = logging.getLogger('passerd.oauth')
dbg = logger.debug

OAUTH_CONSUMER_KEY = '1K2bNGyqs7dtDKTaTlfnQ'
OAUTH_CONSUMER_SECRET = 'frpQHgjN21ajybwA0ZQ2utwlu9O6A36r8YLy6PxY5c'

OAUTH_REQUEST_TOKEN_URL = 'http://twitter.com/oauth/request_token'
OAUTH_ACCESS_TOKEN_URL = 'http://twitter.com/oauth/access_token'
OAUTH_AUTHORIZE_URL = 'http://twitter.com/oauth/authorize'

OAUTH_SIGN_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1()

oauth_consumer = oauth.OAuthConsumer(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET)


class OAuthClient:
    def __init__(self, url_cb=None, progress_cb=None):
        self.verifier_callback = None
        self.url_callback = url_cb
        self.progress_cb = progress_cb

    def progress(self, msg):
        """Can be overwritten, to show a status message"""
        if self.progress_cb:
            self.progress_cb(msg)
Exemplo n.º 22
0
 def setUp(self):
     super(OAuthTest, self).setUp()
     self.desktop_consumer = oauth.OAuthConsumer("TESTDESKTOPCONSUMER",
                                                 "secret")
     self.sig_hmac = oauth.OAuthSignatureMethod_HMAC_SHA1()
Exemplo n.º 23
0
    }

    tokens = {token1.key: token1, token2.key: token2}

    def lookup_consumer(self, key):
        return self.consumers.get(key)

    def lookup_token(self, token_type, token_token):
        return self.tokens.get(token_token)

    def lookup_nonce(self, oauth_consumer, oauth_token, nonce):
        return None


testingOAuthStore = TestingOAuthDataStore()

sign_meth_HMAC_SHA1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
sign_meth_PLAINTEXT = oauth.OAuthSignatureMethod_PLAINTEXT()


def load_with_scenarios(loader, standard_tests, pattern):
    """Load the tests in a given module.

    This just applies testscenarios.generate_scenarios to all the tests that
    are present. We do it at load time rather than at run time, because it
    plays nicer with various tools.
    """
    suite = loader.suiteClass()
    suite.addTests(testscenarios.generate_scenarios(standard_tests))
    return suite
Exemplo n.º 24
0
 def __init__(self, acct):
   self.account = acct
   self.sigmethod = oauth.OAuthSignatureMethod_HMAC_SHA1()
   self.consumer = oauth.OAuthConsumer("anonymous", "anonymous")
   self.token = oauth.OAuthToken(acct["access_token"], acct["secret_token"])
def main():
    #create a base consumer object
    oidconsumer = consumer.Consumer({}, None)

    #print page content type
    print 'Content-Type: text/plain'
    print ''

    #parse query string parameters into dictionary
    params = {}
    string_split = [s for s in os.environ['QUERY_STRING'].split('&') if s]
    for item in string_split:
        key, value = item.split('=')
        if key != 'domain_unverified':
            params[key] = urllib.unquote(value)

    #complete OpenID authentication and get identifier
    info = oidconsumer.complete(params, common.return_to)
    display_identifier = info.getDisplayIdentifier()

    #build attribute exchange response object
    ax_response = ax.FetchResponse.fromSuccessResponse(info)
    if ax_response:
        ax_items = {
            'email': ax_response.get('http://axschema.org/contact/email'),
            'picture':
            ax_response.get('http://axschema.org/media/image/default')
        }

        #print attribute exchange object
        print 'Attribute Exchange Response Object:'
        print ax_items

    #print openid display identifier
    print '\n\nOpenID Display Identifier: \n' + display_identifier

    #check the openid return status
    if info.status == consumer.FAILURE and display_identifier:
        message = "\n\nOpenID Response:\nVerification failed"
    elif info.status == consumer.CANCEL:
        message = '\n\nOpenID Response:\nVerification cancelled'
    elif info.status == consumer.SETUP_NEEDED:
        message = '\n\nOpenID Response:\nSetup needed'
    elif info.status == consumer.SUCCESS:
        message = '\n\nOpenID Response:\nSuccess'

        #build base consumer object with oauth keys and sign using HMAC-SHA1
        base_consumer = oauth.OAuthConsumer(common.consumer_key,
                                            common.consumer_secret)
        signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()

        #build dictionary of pre-authorized request token and blank secret to exchange for access token
        req_token = dotdict({
            'key': params['openid.oauth.request_token'],
            'secret': ''
        })

        #create new oauth request and sign using HMAC-SHA1 to access token endpoint to exchange request token for access token
        oauth_request = oauth.OAuthRequest.from_consumer_and_token(
            base_consumer,
            token=req_token,
            verifier=None,
            http_url=common.oauth_access_token_endpoint)
        oauth_request.sign_request(signature_method_hmac_sha1, base_consumer,
                                   req_token)

        #make request to exchange request token for access token string
        token_read = urllib.urlopen(oauth_request.to_url())
        token_string = token_read.read()

        #parse access token string into parameters and extract user guid
        token_params = cgi.parse_qs(token_string)
        guid = token_params['xoauth_yahoo_guid'][0]

        #create new access token object to make permissioned requests
        access_token = oauth.OAuthToken.from_string(token_string)

        #create url to Yahoo! servers to access user profile
        url = 'http://%s/v1/user/%s/profile' % ('social.yahooapis.com', guid)

        #create new oauth request and sign using HMAC-SHA1 to get profile of authorized user
        oauth_request = oauth.OAuthRequest.from_consumer_and_token(
            base_consumer, token=access_token, http_method='GET', http_url=url)
        oauth_request.sign_request(signature_method_hmac_sha1, base_consumer,
                                   access_token)

        #make request to get profile of user
        profile_read = urllib.urlopen(oauth_request.to_url())
        profile_string = profile_read.read()

        #print profile response object
        message += '\n\nProfile Response Object:\n' + profile_string
    else:
        message = '\n\nOpenID Response:\nVerification failed.'
    print message
def run_example():

    # setup
    print '** OAuth Python Library Example **'
    client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL,
                               ACCESS_TOKEN_URL, AUTHORIZATION_URL)
    consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
    signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT()
    signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
    pause()
    # get request token
    print '* Obtain a request token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer, http_url=client.request_token_url)
    #oauth_request.sign_request(signature_method_plaintext, consumer, None)
    oauth_request.sign_request(signature_method_hmac_sha1, consumer, None)

    print 'REQUEST (via headers)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    #import pdb; pdb.set_trace()

    token = client.fetch_request_token(oauth_request)
    print 'GOT'
    print 'key: %s' % str(token.key)
    print 'secret: %s' % str(token.secret)
    pause()

    print '* Authorize the request token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_token_and_callback(
        token=token, callback=CALLBACK_URL, http_url=client.authorization_url)
    print 'REQUEST (via url query string)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    # this will actually occur only on some callback
    response = client.authorize_token(oauth_request)
    print 'GOT'
    print response
    pause()

    # get access token
    print '* Obtain an access token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer, token=token, http_url=client.access_token_url)
    oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
    print 'REQUEST (via headers)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    token = client.fetch_access_token(oauth_request)
    print 'GOT'
    print 'key: %s' % str(token.key)
    print 'secret: %s' % str(token.secret)
    pause()

    # access some protected resources
    print '* Access protected resources ...'
    pause()
    parameters = {}
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer,
        token=token,
        http_method='GET',
        http_url=RESOURCE_URL,
        parameters=parameters)
    oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
    print 'REQUEST (via get body)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    params = client.access_resource(oauth_request)
    print 'GOT'
    print 'non-oauth parameters: %s' % params
    pause()
Exemplo n.º 27
0
    def __execute(self, method, args, kwargs):
        ## build request data
        req_data = method(*args, **kwargs)

        if 'just_return' in req_data:
            return req_data['just_return']

        ## play with request headers
        headers = copy.deepcopy(self._headers)
        if self.uagent:
            headers['User-Agent'] = self.uagent
        if self.referer:
            headers['Referer'] = self.referer

        headers['Content-Type'] = 'multipart/form-data'
        if 'boundary' in req_data:
            headers[
                'Content-Type'] += '; boundary="' + req_data['boundary'] + '"'
        if 'headers' in req_data:
            headers.update(req_data['headers'])

        req_body = req_data.get('data', '')
        headers['Content-Length'] = len(req_body)

        if not self._ch:
            self.connect()

        ## build url
        url = 'http://%s%s' % (self.api_uri, req_data['url'])

        ## play with parameters
        params = req_data.get('params', None)
        if not req_data.get('params_all', False) and params is not None:
            for k, v in req_data['params'].items():
                if not v:
                    del req_data['params'][k]

        ## sign request, if we have oauth data
        if self._oauth_token and self._oauth_consumer:
            oauth_request = oauth.OAuthRequest.from_consumer_and_token(
                self._oauth_consumer,
                token=self._oauth_token,
                http_method=req_data['method'].upper(),
                http_url=url,
                parameters=params,
            )
            oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
                                       self._oauth_consumer,
                                       token=self._oauth_token)
            oauth_headers = oauth_request.to_header()
            headers.update(oauth_headers)

        ## add query string
        if params is not None:
            url += '?' + arr2qstr(params, True)

        ## go!
        try:
            shaperd = self._shaperd()
            if not shaperd:
                raise BlipApiError('Too many requests')

            self._ch.request(req_data['method'].upper(),
                             url,
                             body=req_body,
                             headers=headers)
        except socket.error, (errno, error):
            self._ch = None
            raise BlipApiError('Connection error: [%d] %s' % (errno, error))
Exemplo n.º 28
0
 def __init__(self, consumer, token, user_name):
     self.consumer = consumer
     self.token = token
     self.user_name = user_name
     self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
Exemplo n.º 29
0
def run_example():
    print '** OAuth Python Library Example **'
    client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL,
                               ACCESS_TOKEN_URL, AUTHORIZATION_URL)
    consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
    signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
    pause()

    # get request token
    print '* Obtain a request token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer,
        callback=CALLBACK_URL,
        http_url=client.request_token_url,
        http_method='POST')
    oauth_request.sign_request(signature_method_hmac_sha1, consumer, None)
    print 'REQUEST (via headers)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    token = client.fetch_request_token(oauth_request)
    print 'GOT'
    print 'key: %s' % str(token.key)
    print 'secret: %s' % str(token.secret)
    print 'callback confirmed? %s' % str(token.callback_confirmed)
    pause()

    print '* Authorize the request token ...'
    pause()
    print 'Please login at %s?oauth_token=%s' % (client.authorization_url,
                                                 token.key)
    callback_url = raw_input(
        "Please copy paste the complete callback url here: ")
    #oauth_request = oauth.OAuthRequest.from_token_and_callback(token=token, http_url=client.authorization_url)
    #print 'REQUEST (via url query string)'
    #print 'parameters: %s' % str(oauth_request.parameters)
    #pause()
    # this will actually occur only on some callback
    #response = client.authorize_token(oauth_request)
    #print 'GOT'
    #print response
    # sad way to get the verifier
    import urlparse, cgi
    query = urlparse.urlparse(callback_url)[4]
    params = cgi.parse_qs(query, keep_blank_values=False)
    verifier = params['oauth_verifier'][0]
    print 'verifier: %s' % verifier
    pause()

    # get access token
    print '* Obtain an access token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer,
        token=token,
        verifier=verifier,
        http_url=client.access_token_url)
    oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
    print 'REQUEST (via headers)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    token = client.fetch_access_token(oauth_request)
    print 'GOT'
    print 'key: %s' % str(token.key)
    print 'secret: %s' % str(token.secret)
    pause()

    # access some protected resources
    print '* Access protected resources ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer, token=token, http_method='GET', http_url=RESOURCE_URL)
    oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
    print 'REQUEST (via headers)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    params = client.access_resource(oauth_request)
    print 'GOT'
    print 'non-oauth parameters: %s' % params
    pause()
Exemplo n.º 30
0
def run_example():

    # setup
    print '** OAuth Python Library Example **'
    client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL,
                               ACCESS_TOKEN_URL, AUTHORIZATION_URL)
    consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
    signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
    pause()

    # get request token
    print '* Obtain a request token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer,
        http_url=client.request_token_url,
        parameters={'scope': 'http://www.google.com/calendar/feeds'})
    oauth_request.sign_request(signature_method_hmac_sha1, consumer, None)
    print 'REQUEST (via headers)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    token = client.fetch_request_token(oauth_request)
    print 'GOT'
    print 'key: %s' % str(token.key)
    print 'secret: %s' % str(token.secret)
    pause()

    print '* Authorize the request token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_token_and_callback(
        token=token, callback=CALLBACK_URL, http_url=client.authorization_url)
    print 'REQUEST (via url query string)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    # this will actually occur only on some callback
    url = client.authorize_token(oauth_request, get_url_only=True)
    print 'GOT'
    print url
    pause()

    # get access token
    print '* Obtain an access token ...'
    pause()
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer, token=token, http_url=client.access_token_url)
    oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
    print 'REQUEST (via headers)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    token = client.fetch_access_token(oauth_request)
    print 'GOT'
    print 'key: %s' % str(token.key)
    print 'secret: %s' % str(token.secret)
    pause()

    # access some protected resources
    print '* Access protected resources ...'
    pause()
    parameters = {
        'file': 'vacation.jpg',
        'size': 'original',
        'oauth_callback': CALLBACK_URL
    }  # resource specific params
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer,
        token=token,
        http_method='POST',
        http_url=RESOURCE_URL,
        parameters=parameters)
    oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
    print 'REQUEST (via post body)'
    print 'parameters: %s' % str(oauth_request.parameters)
    pause()
    params = client.access_resource(oauth_request)
    print 'GOT'
    print 'non-oauth parameters: %s' % params
    pause()