예제 #1
0
    def lookup_consumer(self, key):
        memkey = 'OAuthConsumerKey-' + key
        secret = memcache.get(memkey)
        if secret is not None:
            return oauth.OAuthConsumer(key, secret)

        que = db.Query(OAuthConsumerKey).filter('consumer =', key)
        results = que.fetch(limit=1)
        if len(results) > 0:
            secret = results[0].secret
            memcache.set(memkey, secret, 7200)
            return oauth.OAuthConsumer(key, secret)

        # Demo hard coded hacks if there are no keys
        que = db.Query(OAuthConsumerKey)
        results = que.fetch(limit=1)
        if len(results) < 1:
            if key == "lmsng.school.edu":
                memcache.set(memkey, 'secret', 7200)
                return oauth.OAuthConsumer(key, "secret")
            if key == "12345":
                memcache.set(memkey, 'secret', 7200)
                return oauth.OAuthConsumer(key, "secret")

        logging.info("Did not find consumer " + key)
        return None
예제 #2
0
 def __init__(self,
              consumer_key,
              consumer_secret,
              oauth_token=None,
              oauth_token_secret=None):
     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
예제 #3
0
    def __init__(self, name, key, secret, extra_key=None, extra_secret=None):
        self.name = name
        self.normalized_name = self.normalize_name(name)
        self.consumer = oauth.OAuthConsumer(key, secret)

        self.consumers = dict()
        self.consumers[key] = self.consumer

        if extra_key and extra_secret:
            self.consumers[extra_key] = oauth.OAuthConsumer(
                extra_key, extra_secret)
예제 #4
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
예제 #5
0
def augment(url, parameters):
    secrets = hidden.oauth()
    consumer = oauth.OAuthConsumer(secrets['consumer_key'],
                                   secrets['consumer_secret'])
    token = oauth.OAuthConsumer(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()
예제 #6
0
def augment(url, parameters, credentials, http_method='GET'):
    """
    Create a URL for HTTP request with authentication 
    information. These are added as extra parameters.
    """

    # Create an object with the api key and secret key as attributes `key` and `secret`:
    consumer = oauth.OAuthConsumer(credentials['api_key'],
                                   credentials['api_secret_key'])
    # Create an object with the token and token secret as attributes; this object has to/from string methods:
    token = oauth.OAuthToken(credentials['access_token'],
                             credentials['access_token_secret'])

    # Create an object with all the provided information plus OAuth version, timestamp and random number:
    oauth_request = oauth.OAuthRequest.from_consumer_and_token(
        consumer,
        token=token,
        http_method=http_method,
        http_url=url,
        parameters=parameters)
    # Create the attribute 'oauth_signature' in the object; this attribute is a authentication signature built from my secret key and the full message to be sent:
    oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
                               consumer, token)

    return oauth_request.to_url()
예제 #7
0
 def bind(self, verifier):
   s = Session.get_by_key_name(self._jid)
   if s:
     token = oauth.OAuthToken.from_string(s.data)
     consumer = oauth.OAuthConsumer(config.OAUTH_CONSUMER_KEY, config.OAUTH_CONSUMER_SECRET)
     oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=token, verifier=verifier,
                                                                http_url=config.ACCESS_TOKEN_URL)
     signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
     oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
     try:
       result = urlfetch.fetch(oauth_request.to_url(), method=oauth_request.http_method)
     except urlfetch.Error:
       return 'Network Error!'
     try:
       token = oauth.OAuthToken.from_string(result.content)
     except BaseException:
       return 'Wrong verifier!'
     u = User.get_by_key_name(self._jid)
     if u:
       u.access_key = token.key
       u.access_secret = token.secret
       u.put()
     else:
       User(key_name=self._jid, access_key=token.key, access_secret=token.secret).put()
     s.data = None
     s.put()
     return 'Successfully bind your account.'
예제 #8
0
 def oauth(self, mobile=None):
   consumer = oauth.OAuthConsumer(config.OAUTH_CONSUMER_KEY, config.OAUTH_CONSUMER_SECRET)
   params = {'xoauth_displayname': 'Gmail2GTalk', 'scope': config.RESOURCE_URL}
   oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, callback='oob', parameters=params,
                                                              http_url=config.REQUEST_TOKEN_URL)
   signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
   oauth_request.sign_request(signature_method_hmac_sha1, consumer, None)
   try:
     result = urlfetch.fetch(oauth_request.to_url(), method=oauth_request.http_method)
   except urlfetch.Error:
     return 'Network Error!'
   token = oauth.OAuthToken.from_string(result.content)
   s = Session.get_by_key_name(self._jid)
   if not s:
     Session(key_name=self._jid, data=result.content).put()
   else:
     s.data = result.content
     s.put()
   if mobile == 'mobile':
     params = {'btmpl': 'mobile'}
   else:
     params = None
   oauth_request = oauth.OAuthRequest.from_token_and_callback(token, http_url=config.AUTHORIZATION_URL,
                                                              parameters=params)
   url = oauth_request.to_url()
   return 'Please visit following url to authorize:\n%s' % url
예제 #9
0
def createOauthRequest(http_url, params, default_params):

    validateOptions(params, default_params)

    default_params.update(params)
    params = default_params

    http_method = 'GET'
    token = params.pop('token', None)

    base_url = 'https://www.pesapal.com/api/'
    if testing:
        base_url = 'https://demo.pesapal.com/api/'

    url = base_url + http_url

    if not consumer_key:
        raise MissingKeyError('provide consumer key')
    if not consumer_secret:
        raise MissingKeyError('provide consumer consumer_secret')
    oauth_consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)

    request = OAuthRequest.from_consumer_and_token(oauth_consumer,
                                                   http_url=url,
                                                   http_method=http_method,
                                                   parameters=params)
    request.sign_request(SIGNATURE_METHOD, oauth_consumer, token)
    return request.to_url()
예제 #10
0
 def __init__(self, consumer_key, consumer_secret):
     self.consumer_key = consumer_key
     self.consumer_secret = consumer_secret
     self.consumer = oauth.OAuthConsumer(self.consumer_key,
                                         self.consumer_secret)
     self.sig_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
     self.connection = httplib.HTTPSConnection("twitter.com")
예제 #11
0
파일: tdtool.py 프로젝트: xmayeur/rPIserver
def doRequest(method, params):
    global config

    consumer = oauth.OAuthConsumer(PUBLIC_KEY, PRIVATE_KEY)

    token = oauth.OAuthToken(config['telldus']['token'],
                             config['telldus']['tokenSecret'])

    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)
예제 #12
0
파일: auth.py 프로젝트: raully7/pyqqweibo
 def __init__(self, consumer_key, consumer_secret, 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 or 'null'  # fixed
     self.username = None
예제 #13
0
    def __init__(self, twitter_config, urlToken=None):
        """
        Initialise an instance of the TwitterAuth class that will enable us to create an oauth access
        token with twitter
        """

        # initialise the configuration
        self.config = twitter_config
        self.requestToken = urlToken
        self.accessToken = None

        # create the consumer
        self.consumer = oauth.OAuthConsumer(self.config.consumerKey,
                                            self.config.consumerSecret)

        # if the oauth token is not set, then prepare the request token and authorization steps
        if self.requestToken is None:
            # create the request token
            self.requestToken = self._initRequestToken(URL_REQUEST_TOKEN)

            # authorize the request token
            self._authorizeToken()
        # otherwise, create an oauth token from the string passed to the function
        else:
            # look for the twitter user from the database
            requestKey = OAuthAccessKey.findByRequestKey(self.requestToken)

            # if we found the user
            if requestKey is not None:
                self.accessToken = oauth.OAuthToken.from_string(
                    requestKey.requestKeyEncoded)
예제 #14
0
 def __init__(self, token=None):
     self.consumer = oauth.OAuthConsumer(settings.TWITTERAUTH_KEY,
                                         settings.TWITTERAUTH_SECRET)
     self.conn = None
     self.conn1 = None
     self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
     self.token = token
예제 #15
0
  def __init__(self, use_sandbox=False, server_rpc_base=None,
               consumer_key='anonymous', consumer_secret='anonymous',
               http_post=None):
    """Initializes a service that can perform the various OAuth steps.

    Args:
      use_sandbox: A boolean indicating whether to use Wave Sandbox URLs
      server_rpc_base: optional explicit url to use for rpc,
          overriding use_sandbox.
      consumer_key: A string for the consumer key, defaults to 'anonymous'
      consumer_secret: A string for the consumer secret, defaults to 'anonymous'
      http_post: handler to call to execute a http post.
    """
    self._consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
    logging.info('server_rpc_base: %s', server_rpc_base)
    if server_rpc_base:
      self._server_rpc_base = server_rpc_base
    elif use_sandbox:
      self._server_rpc_base = WaveService.SANDBOX_RPC_URL
    else:
      self._server_rpc_base = WaveService.RPC_URL
    logging.info('server:' + self._server_rpc_base)

    self._http_post = self.http_post
    self._connection = httplib.HTTPSConnection('www.google.com')
    self._access_token = None
예제 #16
0
def _generate_unittest_settings():
    '''Generate a cascade_unittest_settings.py module in the current
       directory.'''

    print '>>> generating cascade_unittest_settings.py'

    sys.stdout.write('consumer key: ')
    consumerKey = sys.stdin.readline().strip()

    sys.stdout.write('consumer secret: ')
    consumerSecret = sys.stdin.readline().strip()

    sys.stdout.write('consumer callback URL: ')
    consumerCbUrl = sys.stdin.readline().strip()

    oaConsumer = oauth.OAuthConsumer(consumerKey, consumerSecret)

    reqTok, url = oauth_get_request_token(oaConsumer, consumerCbUrl)

    print '''>>> navigate to the following URL in your browser, then paste
in token callback URL that results'''
    print url

    sys.stdout.write('token callback URL: ')
    tokenCbUrl = sys.stdin.readline().strip()

    tokenCbUrlQp = urlparse.urlsplit(tokenCbUrl).query
    tokenCbUrlDict = cgi.parse_qs(tokenCbUrlQp)

    assert(tokenCbUrlDict['oauth_token'][0] == reqTok.key)
    reqTok.set_verifier(tokenCbUrlDict['oauth_verifier'][0])

    accTok = oauth_get_access_token(oaConsumer, reqTok)

    _write_unittest_settings(consumerKey, consumerSecret, accTok)
예제 #17
0
    def setUp(self):
        # XXX: This is funky. Because we're doing an import from within the
        #      confines of this class method, unless we're careful, the import
        #      of this module will get bound to a local variable. Instead, we
        #      make sure that it gets bound to a global.
        global cascade_unittest_settings

        # Load up unittest settings, creating them if non-existant. These
        # are stashed in cascade_unittest_settings.py and are loaded using
        # the standard module path.
        try:
            import cascade_unittest_settings
        except ImportError:
            _generate_unittest_settings()

            try:
                import cascade_unittest_settings
            except ImportError:
                print sys.stderr, '>>> unable to configure settings; exiting'
                sys.exit(1)

        # Create OAuth objects (a consumer, a request token, and access
        # token if requested) from unittest settings.
        self._oaConsumer = oauth.OAuthConsumer(
            cascade_unittest_settings.OAUTH_CONSUMER_KEY,
            cascade_unittest_settings.OAUTH_CONSUMER_SECRET
        )

        self._oaAccessToken = oauth_token_from_query_string(cascade_unittest_settings.OAUTH_ACCESS_TOKEN)
예제 #18
0
 def __init__(self, consumer_key, consumer_secret, account_id, username):
     self.consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
     self.signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1(
     )
     self.oauth_token = None
     self.account_id = account_id
     self.username = username
예제 #19
0
    def get(self):
        # setup/initial
        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()

        # get request token
        # print '* Obtain a request token ...'
        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)
        cid = str(int(random.uniform(0, sys.maxint)))
        token = client.fetch_request_token(oauth_request)
        memcache.set("PK_" + cid, token.to_string())
        PHASETWO_CALLBACK_URL = 'http://' + os.environ[
            'HTTP_HOST'] + '/oauth_authorized?id=' + cid

        #print '* Authorize the request token ...'
        oauth_request = oauth.OAuthRequest.from_token_and_callback(
            token=token,
            callback=PHASETWO_CALLBACK_URL,
            http_url=client.authorization_url)
        #??? response = client.authorize_token(oauth_request)
        #??? self.redirect(response)
        # OR USING BELOW LINES instead ?
        oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
        self.redirect(oauth_request.to_url())
예제 #20
0
파일: tdtool.py 프로젝트: xmayeur/rPIserver
def getAccessToken():
    global config
    consumer = oauth.OAuthConsumer(PUBLIC_KEY, PRIVATE_KEY)
    token = oauth.OAuthToken(config['telldus']['requestToken'],
                             config['telldus']['requestTokenSecret'])
    request = oauth.OAuthRequest.from_consumer_and_token(
        consumer,
        token=token,
        http_method='GET',
        http_url='http://api.telldus.com/oauth/accessToken')
    request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer,
                         token)
    conn = httplib.HTTPConnection('api.telldus.com:80')
    conn.request(request.http_method,
                 request.to_url(),
                 headers=request.to_header())

    resp = conn.getresponse()
    if resp.status != 200:
        print('Error retrieving access token, the server replied:\n%s' %
              resp.read())
        return
    token = oauth.OAuthToken.from_string(resp.read())
    config['telldus']['requestToken'] = None
    config['telldus']['requestTokenSecret'] = None
    config['telldus']['token'] = str(token.key)
    config['telldus']['tokenSecret'] = str(token.secret)
    print('Authentication successful, you can now use tdtool')
    saveConfig()
예제 #21
0
    def __init__(self, consumer_key, consumer_secret, testing=True):

        self.oauth_consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)

        self.base_url = 'https://www.pesapal.com/api/'
        if testing:
            self.base_url = 'http://demo2.pesapal.com/api/'
예제 #22
0
 def __init__(self, consumer_key, consumer_secret):
     self.consumer_key = consumer_key
     self.consumer_secret = consumer_secret
     self.oauth_consumer = oauth.OAuthConsumer(consumer_key,
                                               consumer_secret)
     self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
     self.access_token = None
예제 #23
0
파일: session.py 프로젝트: vrudikov/youtify
    def __init__(self,
                 consumer_key,
                 consumer_secret,
                 access_type,
                 locale=None):
        """Initialize a DropboxSession object.

        Your consumer key and secret are available
        at https://www.dropbox.com/developers/apps

        Args:
            access_type: Either 'dropbox' or 'app_folder'. All path-based operations
                will occur relative to either the user's Dropbox root directory
                or your application's app folder.
            locale: A locale string ('en', 'pt_PT', etc.) [optional]
                The locale setting will be used to translate any user-facing error
                messages that the server generates. At this time Dropbox supports
                'en', 'es', 'fr', 'de', and 'ja', though we will be supporting more
                languages in the future. If you send a language the server doesn't
                support, messages will remain in English. Look for these translated
                messages in rest.ErrorResponse exceptions as e.user_error_msg.
        """
        assert access_type in [
            'dropbox', 'app_folder'
        ], "expected access_type of 'dropbox' or 'app_folder'"
        self.consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
        self.token = None
        self.request_token = None
        self.signature_method = oauth.OAuthSignatureMethod_PLAINTEXT()
        self.root = 'sandbox' if access_type == 'app_folder' else 'dropbox'
        self.locale = locale
예제 #24
0
def return_(request):
	"/return/"
	CONSUMER = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
	CONNECTION = httplib.HTTPSConnection(SERVER)		
	unauthed_token = user = getCurrentUser(request)["unauthed_token"]
	if not unauthed_token:
		return HttpResponse("No un-authed token cookie")
	token = oauth.OAuthToken.from_string(unauthed_token)
	if token.key != request.GET.get("oauth_token", "no-token"):
		return HttpResponse("Something went wrong! Tokens do not match")
	access_token = exchange_request_token_for_access_token(CONSUMER, CONNECTION, token)	
	clog(str(access_token))
	exis_user = getCollUsers().find_one({"access_token":str(access_token)})
	response = HttpResponseRedirect("/")
	user = getCurrentUser(request);
	if exis_user and user["_id"]!=exis_user["_id"]:
		users = getCollUsers()
		clog("delete temp user")
		users.remove({"_id":user["_id"]}, safe=True)
		setCookie(response, "newsrivr_userid_md5", str(exis_user["newsrivr_userid_md5"]))
		checkDoubleUsernames(exis_user["screen_name"])
	else:
		user["access_token"] = access_token.to_string()
		user["newuser"] = True
		users = getCollUsers()	
		users.save(user, safe=True)

	return response
예제 #25
0
 def get_access_token(self,token=None,verifier=None):
     if verifier:
         r = self.oauth_request(self.access_token_url(), args={'oauth_verifier': verifier})
     else:
         r = self.oauth_request(self.access_token_url())
     token = self.oauth_parse_response(r)
     self.token = oauth.OAuthConsumer(token['oauth_token'],token['oauth_token_secret'])
     return token
예제 #26
0
 def get_request_token(self):
     response = self.oauth_request(self.request_token_url())
     token = self.oauth_parse_response(response)
     try:
         self.token = oauth.OAuthConsumer(token['oauth_token'],token['oauth_token_secret'])
         return token
     except:
         raise oauth.OAuthError('Invalid oauth_token')
예제 #27
0
 def __init__(self, consumer_key, consumer_secret, access_token=None):
     if access_token:
         Api.__init__(self, access_token.key, 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
예제 #28
0
 def __init__(self, ):
     self.client = TOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL,
                                ACCESS_TOKEN_URL, AUTHORIZATION_URL)
     self.consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
     self.signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT(
     )
     self.signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1(
     )
예제 #29
0
def _get_signed_oauth_request(key, secret, parameters, url):
    consumer = oauth.OAuthConsumer(key, secret)
    request = oauth.OAuthRequest.from_consumer_and_token(consumer,
                                                         http_method=_POST,
                                                         http_url=url,
                                                         parameters=parameters)
    request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer,
                         None)
    return request
예제 #30
0
 def __init__(self, uid, key=None, secret=None):
     self.uid = uid
     self.key = key
     self.secret = secret
     self.consumer = oauth.OAuthConsumer(API_KEY, API_SECRET)
     if key and secret:
         self.token = oauth.OAuthToken(key, secret)
     else:
         self.token = None