Exemplo n.º 1
0
 def __init__(self, consumer_key, consumer_secret, access_token=None):
     if access_token:
         Api.__init__(self,
                      consumer_key=consumer_key,
                      consumer_secret=consumer_secret,
                      access_token_key=access_token.key,
                      access_token_secret=access_token.secret)
     else:
         Api.__init__(self)
     self._Consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
     self._signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
     self._access_token = access_token
Exemplo n.º 2
0
 def __init__(self, accessToken, accessSecret):
     """class init method
     
     Arguments:
     - `accessToken`:
     - `accessSecret`:
     """
     self._accessToken = oauth.OAuthToken(accessToken, accessSecret)
     self._connection = httplib.HTTPConnection("%s:%d" % (SERVER, PORT))
     self.signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1(
     )
     self.consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
Exemplo n.º 3
0
def augment(url, parameters):
    secrets = hidden.oauth()
    consumer = oauth.OAuthConsumer(secrets['consumer_key'],
                                   secrets['consumer_secret'])
    token = oauth.OAuthToken(secrets['token_key'], secrets['token_secret'])

    oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
                    token=token, http_method='GET', http_url=url,
                    parameters=parameters)
    oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
                               consumer, token)
    return oauth_request.to_url()
Exemplo n.º 4
0
 def _signRequest(self, req, signature_method=oauth.OAuthSignatureMethod_HMAC_SHA1()):
     '''Sign a request
     
     Reminder: Created this function so incase
     if I need to add anything to request before signing
     
     Args:
       req: The OAuth request created via _makeOAuthRequest
       signate_method:
          The oauth signature method to use
     '''
     req.sign_request(signature_method, self._Consumer, self._access_token)
Exemplo n.º 5
0
 def __init__(self,
              consumer_key,
              consumer_secret,
              callback=None,
              secure=False):
     self._consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
     self._sigmethod = oauth.OAuthSignatureMethod_HMAC_SHA1()
     self.request_token = None
     self.access_token = None
     self.callback = callback
     self.username = None
     self.secure = secure
Exemplo n.º 6
0
def augment(url, parameters):
"""
This function augments the twitter url adding the authontication data necessary for the scrapping.
"""
	secrets = Hidden.oauth()
	consumer = oauth.OAuthConsumer(secrets['consumer_key'], secrets['consumer_secret'])
	token = oauth.OAuthToken(secrets['token_key'], secrets['token_secret'])

	oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=token, http_method='GET', http_url=url, parameters=parameters)
	oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, token)

	return oauth_request.to_url()
    def url_for_request_token(self, callback=None, parameters=None):
        oauth_request = oauth.OAuthRequest.from_consumer_and_token(
            self.consumer,
            http_url=self.request_token_url,
            callback=callback,
            parameters=parameters)

        print oauth_request.to_url()
        oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
                                   self.consumer, None)
        print oauth_request.to_url()

        return oauth_request.to_url()
Exemplo n.º 8
0
    def __init__(self, consumer_key, consumer_secret, server_params, oauth_token=None, oauth_token_secret=None):
        """
        params should be a dictionary including
        root_url, request_token_path, authorize_path, authenticate_path, access_token_path
        """
        self.server_params = server_params

        self.sha1_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
        self.consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
        if ((oauth_token != None) and (oauth_token_secret!=None)):
            self.token = oauth.OAuthConsumer(oauth_token, oauth_token_secret)
        else:
            self.token = None
Exemplo n.º 9
0
 def url(key, secret, email, name, uid, isSecure=False, **additionalFields):
     consumer = oauth.OAuthConsumer(key, secret)
     url = "https://%s/fastpass" % FastPass.domain
     if isSecure:
         url = "https://%s/fastpass" % FastPass.domain
     params = dict(email=email, name=name, uid=uid)
     params.update(additionalFields)
     sigmethod = oauth.OAuthSignatureMethod_HMAC_SHA1()
     request = oauth.OAuthRequest.from_consumer_and_token(consumer,
                                                          http_url=url,
                                                          parameters=params)
     request.sign_request(sigmethod, consumer, None)
     return request.to_url()
Exemplo n.º 10
0
    def get(self):
        def handle_result(rpc):
            try:
                result = rpc.get_result()
            except urlfetch.Error:
                return
            else:
                jid = self.jids[id(rpc)]
                emails_map = parse(result.content)
                emails = list()
                for email in emails_map:
                    if not Mail.get_by_key_name(email['id']):
                        if Mail(key_name=email['id']).put():
                            str = 'From: %(author)s\nTitle: %(title)s\nSummary: %(summary)s\nTime: %(time)s\n%(url)s' % email
                            emails.insert(0, str)
                if emails:
                    while CapabilitySet('xmpp').is_enabled():
                        try:
                            xmpp.send_message(jid, '\n\n'.join(emails))
                        except xmpp.Error:
                            pass
                        else:
                            break

        def create_callback(rpc):
            return lambda: handle_result(rpc)

        if not db.WRITE_CAPABILITY:
            return
        rpcs = []
        self.jids = {}
        for u in Session.all().filter('data =', None):
            jid = u.key().name()
            u = User.get_by_key_name(jid)
            token = oauth.OAuthToken(u.access_key, u.access_secret)
            consumer = oauth.OAuthConsumer(config.OAUTH_CONSUMER_KEY,
                                           config.OAUTH_CONSUMER_SECRET)
            oauth_request = oauth.OAuthRequest.from_consumer_and_token(
                consumer, token=token, http_url=config.RESOURCE_URL)
            signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
            oauth_request.sign_request(signature_method_hmac_sha1, consumer,
                                       token)
            rpc = urlfetch.create_rpc()
            rpc.callback = create_callback(rpc)
            urlfetch.make_fetch_call(rpc,
                                     oauth_request.http_url,
                                     headers=oauth_request.to_header())
            rpcs.append(rpc)
            self.jids[id(rpc)] = jid
        for rpc in rpcs:
            rpc.wait()
Exemplo n.º 11
0
def build_oauth_request(url, key, secret):
    '''
    Returns an oauth signed urllib2.Request object
    '''
    params = parse_qsl(urlparse(url).query)
    consumer = oauth.OAuthConsumer(key=key, secret=secret)
    request = oauth.OAuthRequest.from_consumer_and_token(consumer,
                                                         http_method='GET',
                                                         http_url=url,
                                                         parameters=params)

    request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer,
                         None)

    return urllib2.Request(url, None, request.to_header())
Exemplo n.º 12
0
    def __init__(self, name, key, secret, callback='', verbose=False):
        self.connection = httplib.HTTPConnection("%s:%s" % (HOST, PORT))
        self.server = HOST
        self.verbose = verbose
        self.user = None
        self.catalog = NetflixCatalog(self)

        self.CONSUMER_NAME = name
        self.CONSUMER_KEY = key
        self.CONSUMER_SECRET = secret
        self.CONSUMER_CALLBACK = callback
        self.consumer = oauth.OAuthConsumer(self.CONSUMER_KEY,
                                            self.CONSUMER_SECRET)
        self.signature_method_hmac_sha1 = \
                                    oauth.OAuthSignatureMethod_HMAC_SHA1()
Exemplo n.º 13
0
    def fetch_access_token(self, a_k, a_s, a_v):
        tok = oauth.OAuthToken(a_k, a_s)
        oauth_request = oauth.OAuthRequest.from_consumer_and_token(
            self.oConsumer,
            token=tok,
            verifier=a_v,
            http_url=TWITTER_ACCESS_TOKEN_URL)
        oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
                                   self.oConsumer, None)
        res = self.send_oauth_request(oauth_request)

        if int(res.status_code) < 400:
            return oauth.OAuthToken.from_string(res.content)

        return None
Exemplo n.º 14
0
    def verify(self):
        consumer = oauth.OAuthConsumer(self.consumer_key, self.consumer_secret)
        signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
        oauth_token = oauth.OAuthToken(self.token, self.token_secret)

        oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
                                                                   token=oauth_token,
                                                                   http_method='GET',
                                                                   http_url=self.url)

        oauth_request.sign_request(signature_method_hmac_sha1, consumer, oauth_token)

        headers = oauth_request.to_header()
        self.request = urllib2.Request(self.url, headers=headers)
        return self.execute_request()
Exemplo n.º 15
0
    def __init__(self,
                 key=None,
                 secret=None,
                 callback=None,
                 access_token_key=None,
                 access_token_secret=None,
                 request_token_key=None,
                 request_token_secret=None):

        self.key = key or method_call.API_KEY
        self.secret = secret or method_call.API_SECRET

        if self.key is None or self.secret is None:
            raise ValueError("API keys have not been set.")

        if callback is None:
            callback = "http://api.flickr.com/services/rest/?method=flickr.test.echo&api_key=%s" % self.key

        params = {
            'oauth_timestamp': str(int(time.time())),
            'oauth_signature_method': "HMAC-SHA1",
            'oauth_version': "1.0",
            'oauth_callback': callback,
            'oauth_nonce': oauth.generate_nonce(),
            'oauth_consumer_key': self.key
        }

        self.consumer = oauth.OAuthConsumer(key=self.key, secret=self.secret)
        if (access_token_key is None) and (request_token_key is None):
            req = oauth.OAuthRequest(http_method="GET",
                                     http_url=TOKEN_REQUEST_URL,
                                     parameters=params)
            req.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
                             self.consumer, None)
            resp = urllib2.urlopen(req.to_url())
            request_token = dict(urlparse.parse_qsl(resp.read()))
            self.request_token = oauth.OAuthToken(
                request_token['oauth_token'],
                request_token['oauth_token_secret'])
            self.access_token = None
        elif request_token_key is not None:
            self.access_token = None
            self.request_token = oauth.OAuthToken(request_token_key,
                                                  request_token_secret)
        else:
            self.request_token = None
            self.access_token = oauth.OAuthToken(access_token_key,
                                                 access_token_secret)
Exemplo n.º 16
0
    def __init__(self,
                 consumer_key,
                 consumer_secret,
                 access_token=None,
                 token_secret=None,
                 callback=None):
        self._consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
        self._sigmethod = oauth.OAuthSignatureMethod_HMAC_SHA1()
        self.request_token = None
        self.access_token = None
        self.callback = callback
        if access_token != None and token_secret != None:
            self.access_token = oauth.OAuthToken(access_token, token_secret)
        self.connection = httplib2.Http()

        self.check_authentication()
Exemplo n.º 17
0
def aumentar(url, parametros):
    credenciales = hidden.oauth()
    consumidor = oauth.OAuthConsumer(credenciales['consumer_key'],
                                     credenciales['consumer_secret'])
    token = oauth.OAuthToken(credenciales['token_key'],
                             credenciales['token_secret'])

    oauth_solicitud = oauth.OAuthRequest.from_consumer_and_token(
        consumidor,
        token=token,
        http_method='GET',
        http_url=url,
        parameters=parametros)
    oauth_solicitud.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
                                 consumidor, token)
    return oauth_solicitud.to_url()
Exemplo n.º 18
0
def doRequest(method, params):
    consumer = oauth.OAuthConsumer(PUBLIC_KEY, PRIVATE_KEY)
    
    token = oauth.OAuthToken(TOKEN, TOKEN_SECRET)
    
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=token, http_method='GET',
                                                               http_url="http://api.telldus.com/json/" + method,
                                                               parameters=params)
    oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, token)
    headers = oauth_request.to_header()
    headers['Content-Type'] = 'application/x-www-form-urlencoded'
    
    conn = httplib.HTTPConnection("api.telldus.com:80")
    conn.request('GET', "/json/" + method + "?" + urllib.urlencode(params, True).replace('+', '%20'), headers=headers)
    response = conn.getresponse()
    return json.load(response)
Exemplo n.º 19
0
def augment(url, parameters):
    """ Returns Authenticated url using parameters and authentication tokens with Oauth Library. """
    secrets = hidden.oauth()  # receives authentication tokens as dictionary
    consumer = oauth.OAuthConsumer(secrets['consumer_key'],
                                   secrets['consumer_secret'])
    token = oauth.OAuthToken(secrets['token_key'], secrets['token_secret'])

    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer,
        token=token,
        http_method='GET',
        http_url=url,
        parameters=parameters)
    oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
                               consumer, token)
    return oauth_request.to_url()
Exemplo n.º 20
0
    def buildAccessToken(self, accessTokenUrl):
        """
        This static method is used to contact twitter and build the access token that will permit
        us to access the twitter information stream
        """

        # if the request token has not been set, then don't attempt to get an access token
        if self.requestToken is None:
            logging.warning(
                "Unable to contact twitter, no request token available.")
            return None

        # initialise the oauth request
        logging.debug(
            "Attempting to build access token from request token '%s'",
            self.requestToken)
        oauth_request = oauth.OAuthRequest.from_consumer_and_token(
            self.consumer, token=self.accessToken, http_url=URL_ACCESS_TOKEN)
        oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
                                   self.consumer, self.accessToken)

        # send the request
        request_result = urlfetch.fetch(url=accessTokenUrl,
                                        headers=oauth_request.to_header())

        # if the response was successful, then process the response
        fnresult = None
        if request_result.status_code == 200:
            fnresult = oauth.OAuthToken.from_string(request_result.content)

            # update the user to store the access token
            request = OAuthAccessKey.findOrCreate(self.requestToken,
                                                  partnerId='twitter')

            # update the user accesskey
            request.accessKeyEncoded = fnresult.to_string()
            request.put()
        else:
            logging.warning("Unable to obtain access token: %s",
                            request_result.content)

        logging.debug("received access token: %s", fnresult)

        if fnresult:
            return fnresult.to_string()
Exemplo n.º 21
0
    def fetch_replies(self, count=0):
        prms = None if count <= 20 else {'count': str(count)}
        oauth_request = oauth.OAuthRequest.from_consumer_and_token(
            self.oConsumer,
            token=self.access_token,
            http_url=TWITTER_REPLIES_URL,
            parameters=prms)

        oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
                                   self.oConsumer, self.access_token)

        if prms:
            oauth_request.http_url = "%s?count=%d" % (oauth_request.http_url,
                                                      count)

        res = self.send_oauth_request(oauth_request)

        return res
Exemplo n.º 22
0
def augment(url, parameters):
    secrets = hidden.oauth()
    consumer = oauth.OAuthConsumer(
        secrets['2hC7L4JYWualVt08f55Q0BWV2'],
        secrets['eaIVbAIIZ6KKEXHc8CoKLTm4F1nRMfp2oBdNDOhcc7Ti2bXnFS'])
    token = oauth.OAuthToken(
        secrets['399296260-lVsELF31IPGd1tTcF7nH3J0C2JiLUc20NO8p8Xm0'],
        secrets['iXXSWlpl9LSxARNoxRjPugrrsQ4bh2HUS9HK3tQhnP1CL'])

    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer,
        token=token,
        http_method='GET',
        http_url=url,
        parameters=parameters)
    oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
                               consumer, token)
    return oauth_request.to_url()
Exemplo n.º 23
0
    def __init__(self, oauth_consumer, pesapal_merchant_reference,
                 pesapal_transaction_tracking_id):

        signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
        api_endpoint = 'https://www.pesapal.com/API/QueryPaymentStatus'

        url = oauth.OAuthRequest.from_consumer_and_token(oauth_consumer,
                                                         http_url=api_endpoint,
                                                         http_method='GET')

        url.set_parameter('pesapal_merchant_reference',
                          pesapal_merchant_reference)

        url.set_parameter('pesapal_transaction_tracking_id',
                          pesapal_transaction_tracking_id)

        url.sign_request(signature_method, oauth_consumer, token=None)
        self.url = url.to_url()
Exemplo n.º 24
0
def initialize_server_request(request):
    """
    Shortcut for initialization.
    """
    oauth_datastore = load_data_store()

    oauth_request = oauth.OAuthRequest.from_request(
        request.method, request.build_absolute_uri(), 
        headers=request.META, parameters=dict(request.REQUEST.items()),
        query_string=request.environ.get('QUERY_STRING', ''))
        
    if oauth_request:
        oauth_server = oauth.OAuthServer(oauth_datastore(oauth_request))
        oauth_server.add_signature_method(oauth.OAuthSignatureMethod_PLAINTEXT())
        oauth_server.add_signature_method(oauth.OAuthSignatureMethod_HMAC_SHA1())
    else:
        oauth_server = None
        
    return oauth_server, oauth_request
Exemplo n.º 25
0
    def _fetch_access_token(self):
        """ send request and get access_token """

        params = {}
        params["x_auth_username"] = self.user
        params["x_auth_password"] = self.passwd
        params["x_auth_mode"] = 'client_auth'
        request = oauth.OAuthRequest.from_consumer_and_token(self.consumer,
                                            http_url=self.ACCESS_TOKEN_URL,
                                            parameters=params)
        self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
        request.sign_request(self.signature_method, self.consumer, None)
        headers = request_to_header(request)

        try:
            resp = urlopen(Request(self.ACCESS_TOKEN_URL, headers=headers))
        except urllib2.HTTPError, ex:
            print ex
            raise ex
Exemplo n.º 26
0
    def __makeAuthHeader(self, method, url, parameters={}):
        headers = {}
        if self.token:
            oauth_request = oauth.OAuthRequest.from_consumer_and_token(
                self.consumer,
                token=self.token,
                http_method=method,
                http_url=url,
                parameters=parameters)
            oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
                                       self.consumer, self.token)
            headers = oauth_request.to_header()

        if method in ('POST', 'PUT'):
            headers['Content-Type'] = 'application/atom+xml; charset=utf-8'

        for k, v in headers.iteritems():
            headers[k] = v.encode('utf-8')

        return headers
Exemplo n.º 27
0
    def request(self, **request):
        params = {}
        qs = request.get('QUERY_STRING')
        params.update(dict((k, v[0]) for k, v in cgi.parse_qs(qs).items()))

        url = 'http://api.' + settings.DOMAIN + request.get('PATH_INFO') + (
            '?' + qs if qs else '')
        oauth_request = oauth.OAuthRequest.from_consumer_and_token(
            self.consumer,
            token=self.access_token,
            http_method=request.get('REQUEST_METHOD'),
            http_url=url,
            parameters=params)
        oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
                                   self.consumer,
                                   token=self.access_token)
        oauth_headers = oauth_request.to_header()
        request.update(('HTTP_%s' % key.upper(), value)
                       for (key, value) in oauth_headers.items())
        return super(OAuthClient, self).request(**request)
    def url_for_access_token(self,
                             request_token,
                             callback=None,
                             parameters=None,
                             verifier=None):
        if not verifier and request_token.verifier:
            verifier = request_token.verifier

        oauth_request = oauth.OAuthRequest.from_consumer_and_token(
            self.consumer,
            token=request_token,
            http_url=self.access_token_url,
            callback=callback,
            parameters=parameters,
            verifier=verifier)

        oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
                                   self.consumer, request_token)

        return oauth_request.to_url()
Exemplo n.º 29
0
    def __init__(self, rc_or_consumer_key, consumer_secret=None):
        """
        syntax: FireEagle( os.path.expanduser( "~/.fireeaglerc" ) )
        or FireEagle( CONSUMER_KEY, CONSUMER_SECRET )
        """

        # Prepare object lifetime variables
        self.read_config(rc_or_consumer_key, consumer_secret)
        self.oauth_consumer = oauth.OAuthConsumer(self.consumer_key,
                                                  self.consumer_secret)
        self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
        proto, host, port = re.search(
            r"^(https?)://([a-z\.0-9]+)(?:\:(\d+))?$",
            self.api_server).groups()
        self.http_connection = (proto == 'https' and httplib.HTTPSConnection
                                or httplib.HTTPConnection)(host, port)

        # Prepare the accumulators for each method
        for method, _ in FIREEAGLE_METHODS.items():
            if not hasattr(self, method):
                setattr(self, method, FireEagleAccumulator(self, method))
Exemplo n.º 30
0
    def __init__(self, config):
        """
        Configures the Authenticator with all the required settings in config.
        Typically you'll use Authenticator.load_config() to load these from
        a .ini file and then pass the returned dict to here.
        """
        self.client = SimpleOAuthClient(config['server'], config['port'],
                                        config['request_token_url'],
                                        config['access_token_url'],
                                        config['authorization_url'])

        self.trusted_access_token_url = config.get('trusted_access_token_url',
                                                   None)

        self.consumer = oauth.OAuthConsumer(config['consumer_key'],
                                            config['consumer_secret'])

        self.signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1(
        )

        self.config = config