Esempio n. 1
0
 def __init__(self, customer_key, customer_secret):
     OAuth1Service.__init__(self, consumer_key=customer_key,
         consumer_secret=customer_secret,
         request_token_url='https://chpp.hattrick.org/oauth/request_token.ashx',
         access_token_url='https://chpp.hattrick.org/oauth/access_token.ashx',
         authorize_url='https://chpp.hattrick.org/oauth/authorize.aspx',
         base_url='http://chpp.hattrick.org/chppxml.ashx',
         signature_obj=HmacSha1Signature)
Esempio n. 2
0
    def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret):
        self.service = OAuth1Service(name='bricklink',
                                     consumer_key=consumer_key,
                                     consumer_secret=consumer_secret,
                                     base_url='https://api.bricklink.com/api/store/v1/')

        self.session = self.service.get_session((access_token, access_token_secret))

        self.orders = Orders(self)
        self.inventory = Inventory(self)
        self.catalog = Catalog(self)
        self.feedback = Feedback(self)
        self.color = Color(self)
        self.category = Category(self)
        self.pushnotification = PushNotification(self)
        self.member = Member(self)
Esempio n. 3
0
def oath():
    zaimService = OAuth1Service(
        consumer_key=consumerKey,
        consumer_secret=consumerSecret,
        request_token_url='https://api.zaim.net/v2/auth/request',
        access_token_url='https://api.zaim.net/v2/auth/access',
        authorize_url='https://auth.zaim.net/users/auth',
        base_url='https://api.zaim.net/v2/home/')

    zaimSession = OAuth1Session(consumer_key=consumerKey,
                                consumer_secret=consumerSecret,
                                access_token=accessToken,
                                access_token_secret=accessTokenSecret,
                                service=zaimService)

    return zaimSession
Esempio n. 4
0
def getSession() :
    # Create rauth service
    twitter = OAuth1Service(
        consumer_key=secrets['consumer_key'],
        consumer_secret=secrets['consumer_secret'],
        name='twitter',
        access_token_url='https://api.twitter.com/oauth/access_token',
        authorize_url='https://api.twitter.com/oauth/authorize',
        request_token_url='https://api.twitter.com/oauth/request_token',
        base_url='https://api.twitter.com/1.1/')
    
    # Get a session
    session = twitter.get_session(
        (secrets['token_key'], secrets['token_secret']))
    
    return session
Esempio n. 5
0
def oauth():
    """Allows user authorization for the sample application with OAuth 1"""
    etrade = OAuth1Service(
        name="etrade",
        consumer_key=config["DEFAULT"]["CONSUMER_KEY"],
        consumer_secret=config["DEFAULT"]["CONSUMER_SECRET"],
        request_token_url="https://api.etrade.com/oauth/request_token",
        access_token_url="https://api.etrade.com/oauth/access_token",
        authorize_url="https://us.etrade.com/e/t/etws/authorize?key={}&token={}",
        base_url="https://api.etrade.com")
    
    base_url = config["DEFAULT"]["PROD_BASE_URL"]
    
     # Step 1: Get OAuth 1 request token and secret
    request_token, request_token_secret = etrade.get_request_token(
        params={"oauth_callback": "oob", "format": "json"})

    # Step 2: Go through the authentication flow. Login to E*TRADE.
    # After you login, the page will provide a text code to enter.
    authorize_url = etrade.authorize_url.format(etrade.consumer_key, request_token)
    
    #############################################
    # Automate the login process
    driver = webdriver.Edge(executable_path='')
    driver.get(authorize_url)
    
    logon = driver.find_element_by_id("logon_button")
    logon.click()
    
    driver.implicitly_wait(5)
     
    accept = driver.find_element_by_xpath("//form[@name='CustInfo']/input[3]")
    accept.click()
    
    code = driver.find_element_by_xpath("//div[@style='text-align:center']/input[1]")
    code = code.get_attribute('value')
    
    driver.close()
        
    text_code = code

    # Step 3: Exchange the authorized request token for an authenticated OAuth 1 session
    session = etrade.get_auth_session(request_token,
                                  request_token_secret,
                                  params={"oauth_verifier": text_code})
    
    automateTrades(session, base_url)
Esempio n. 6
0
 def __init__(self, access_token, access_token_secret, data_url):
     self.authorized = False
     self.data_uri = data_url
     if access_token and access_token_secret:
         self.service = OAuth1Service(
             name="khan_oauth",
             consumer_key=CONSUMER_KEY,
             consumer_secret=CONSUMER_SECRET,
             request_token_url=REQUEST_TOKEN_URL,
             access_token_url=ACCESS_TOKEN_URL,
             authorize_url=AUTHORIZE_URL,
             base_url=BASE_URL,
         )
         self.session = self.service.get_session(
             (access_token, access_token_secret))
         self.authorized = True
     self.get_resource = self.get
Esempio n. 7
0
 def __init__(self, access_token=None, access_token_secret=None):
     self.authorized = False
     # We need an access token and secret to make authorized calls
     # Otherwise we can only access open endpoints
     if access_token and access_token_secret:
         self.service = OAuth1Service(
             name="khan_oauth",
             consumer_key=CONSUMER_KEY,
             consumer_secret=CONSUMER_SECRET,
             request_token_url=REQUEST_TOKEN_URL,
             access_token_url=ACCESS_TOKEN_URL,
             authorize_url=AUTHORIZE_URL,
             base_url=BASE_URL,
         )
         self.session = self.service.get_session(
             (access_token, access_token_secret))
         self.authorized = True
     self.get_resource = self.get
Esempio n. 8
0
    def __init__(self,
                 consumer_key,
                 consumer_secret,
                 access_token_key='',
                 access_token_secret=''):
        """
        Initialization of a CHPP instance

        It needs at least consumer_key and consumer_secret parameters.

        If access_token_key and access_token_secret parameters are not defined,
        the instanciated object can be used to obtain them from Hattrick.

        :param consumer_key: Consumer Key of the application
        :param consumer_secret: Consumer Secret of the application
        :param access_token_key: Access Token Key for the current user
        :param access_token_secret: Access Token Secret for the current user
        :type consumer_key: str
        :type consumer_secret: str
        :type access_token_key: str
        :type access_token_secret: str
        :return: None
        """
        self.consumer_key = consumer_key
        self.consumer_secret = consumer_secret
        self.access_token_key = access_token_key
        self.access_token_secret = access_token_secret

        self.request_token_url = (
            "https://chpp.hattrick.org/oauth/request_token.ashx")
        self.access_token_url = (
            "https://chpp.hattrick.org/oauth/access_token.ashx")
        self.authorize_url = ("https://chpp.hattrick.org/oauth/authorize.aspx")
        self.base_url = ("https://chpp.hattrick.org/chppxml.ashx")

        self.service = OAuth1Service(
            consumer_key=self.consumer_key,
            consumer_secret=self.consumer_secret,
            request_token_url=self.request_token_url,
            access_token_url=self.access_token_url,
            authorize_url=self.authorize_url,
            base_url=self.base_url,
            signature_obj=HmacSha1Signature,
        )
Esempio n. 9
0
class Twitter():
    """Provides the glue between a common social media API and the Twitter API"""

    # statics:
    _twitter_api = OAuth1Service(
        name="twitter",
        consumer_key="VgdIuvcYYe26gYaYigQLbYsAP",
        consumer_secret="IoQoiUumSjBBF1dc708YGCxZ4ZqptCGQS1MNES45cgiXdO97TH",
        request_token_url="https://twitter.com/oauth/request_token",
        access_token_url="https://api.twitter.com/oauth/access_token",
        authorize_url="https://api.twitter.com/oauth/authenticate",
        base_url="https://api.twitter.com/1.1/")

    # instance vars:
    request_token = None
    request_token_secret = None
    authorized_verifier = None
    authorized_session = None

    def authorize(self, callback_url):
        """callback_url should forward the request to authorize_receive()"""
        """Returns a URL to redirect to"""
        self.request_token, self.request_token_secret = self._twitter_api.get_request_token(
            params={'oauth_callback': callback_url})
        return "https://api.twitter.com/oauth/authenticate?oauth_token=%s" % self.request_token

    def authorize_receive(self, oauth_token, oauth_verifier):
        if oauth_token != self.request_token:
            raise EnvironmentError(
                "Response from twitter does not match token sent")
        self.authorized_verifier = oauth_verifier
        self.authorized_session = self._twitter_api.get_auth_session(
            self.request_token,
            self.request_token_secret,
            params={'oauth_verifier': self.authorized_verifier})
        return True

    def tweet(self, message):
        response = self.authorized_session.post("statuses/update.json",
                                                data={'status': message})
        if response.status_code == 200:
            return True
        else:
            raise EnvironmentError("Failed to send tweet")
Esempio n. 10
0
    def __init__(self,
                 pathToConfigFile=None,
                 consumer_key=None,
                 consumer_secret=None,
                 silent=False):

        if pathToConfigFile is None and consumer_key is None:
            raise Exception("Need a config file and/or consumer_key")

        if consumer_key is not None:
            print 'got key from constructor'
            self.consumer_key = consumer_key
        if consumer_secret is not None:
            print 'got secret from constructor'
            self.consumer_secret = consumer_secret

        self.knownUserDict = {}
        if pathToConfigFile is not None:
            self.configFileName = pathToConfigFile
        else:
            self.configFileName = str(consumer_key) + ".txt"
        if not os.path.exists(self.configFileName):
            outfile = codecs.open(self.configFileName, 'w', 'utf8')
            outfile.write(','.join([self.consumer_key, self.consumer_secret]) +
                          '\n')
            outfile.close()

        self.load_known_users(silent)

        self.twitter = OAuth1Service(
            name='twitter',
            consumer_key=self.consumer_key,
            consumer_secret=self.consumer_secret,
            request_token_url='https://api.twitter.com/oauth/request_token',
            access_token_url='https://api.twitter.com/oauth/access_token',
            authorize_url='https://api.twitter.com/oauth/authorize',
            base_url='https://api.twitter.com/1.1/')

        self.api_hooks = []
        for name in self.knownUserDict.keys():
            self.api_hooks.append(
                TwitterAPIHook(self.consumer_key, self.consumer_secret,
                               self.init_session(name)))
Esempio n. 11
0
    def __Oauth(self, redirect_url):
        """
        use Oauth
        """
        if self.session:
            return self.session

        access_token_pickle = 'access_token.pickle'
        try:
            with open(access_token_pickle, 'rb') as f:
                access_token, access_token_secret = pickle.load(f)
                self.session = OAuth1Session(self.app_key, self.app_secret,
                                             access_token, access_token_secret)
                return self.session
        except:
            pass

        tudou = OAuth1Service(
            name='tudou',
            consumer_key=self.app_key,
            consumer_secret=self.app_secret,
            request_token_url='http://api.tudou.com/auth/request_token.oauth',
            access_token_url='http://api.tudou.com/auth/access_token.oauth',
            authorize_url='http://api.tudou.com/auth/authorize.oauth',
            base_url='http://api.tudou.com/')
        request_token, request_token_secret = tudou.get_request_token()
        print 'request_token %s' % request_token
        params = {'oauth_callback': redirect_url}
        authorize_url = tudou.get_authorize_url(request_token, **params)

        webbrowser.open(authorize_url)
        a = raw_input('press Enter to continue: ')
        access_token, access_token_secret = tudou.get_access_token(
            request_token, request_token_secret)
        # self.session = tudou.get_auth_session(request_token, request_token_secret)
        self.session = OAuth1Session(self.app_key, self.app_secret,
                                     access_token, access_token_secret)
        try:
            with open(access_token_pickle, 'wb') as f:
                pickle.dump((access_token, access_token_secret), f)
        except:
            print 'can not open %s to store the access token' % access_token_pickle
        return self.session
Esempio n. 12
0
 def _get_service(self):
     try:
         return self.service
     except AttributeError:
         with open(self.config_file, 'r') as fh:
             config = json.load(fh)
         if type(config) is not dict \
                 or 'key' not in config \
                 or 'secret' not in config:
             raise TypeError('Invalid Config file: {0}'.format(config_file))
         service = OAuth1Service(name='smugliam',
                                 consumer_key=config['key'],
                                 consumer_secret=config['secret'],
                                 request_token_url=self.REQUEST_TOKEN_URL,
                                 access_token_url=self.ACCESS_TOKEN_URL,
                                 authorize_url=self.AUTHORIZE_URL,
                                 base_url=self.API_ORIGIN + '/api/v2')
         self.service = service
         return self.service
    def get_authorize_url(self):
        """Returns the Authorize URL as returned by QB, 
        and specified by OAuth 1.0a.
        :return URI:
        """
        self.qbService = OAuth1Service(
                name = None,
                consumer_key = self.consumer_key,
                consumer_secret = self.consumer_secret,
                request_token_url = self.request_token_url,
                access_token_url = self.access_token_url,
                authorize_url = self.authorize_url,
                base_url = None
            )
        self.request_token, self.request_token_secret = self.qbService.get_request_token(
                params={'oauth_callback':self.callback_url}
            )

        return self.qbService.get_authorize_url(self.request_token)
Esempio n. 14
0
def get_sessions():
    rdio = OAuth1Service(
        name='rdio',
        consumer_key=rdio_consumer_key,
        consumer_secret=rdio_consumer_secret,
        request_token_url='http://api.rdio.com/oauth/request_token',
        access_token_url='http://api.rdio.com/oauth/access_token',
        authorize_url='https://www.rdio.com/oauth/authorize',
        base_url='http://api.rdio.com/1/')

    rdio_request_token, rdio_request_token_secret = rdio.get_request_token(params={'oauth_callback': 'oob'})
    rdio_authorize_url = rdio.get_authorize_url(rdio_request_token)

    print 'Visit this URL in your browser: ' + rdio_authorize_url
    rdio_pin = raw_input('Enter PIN from browser: ')

    rdio_session = rdio.get_auth_session(rdio_request_token,
                                       rdio_request_token_secret,
                                       method='POST',
                                       data={'oauth_verifier': rdio_pin})    

    spotify = OAuth2Service(
          name='spotify',
          client_id=spotify_client_id,
          client_secret=spotify_client_secret,
          authorize_url='https://accounts.spotify.com/authorize/',
          access_token_url='https://accounts.spotify.com/api/token',
          base_url='https://api.spotify.com',)

    params={'scope':'user-library-modify user-library-read playlist-read-private playlist-modify-public', 'response_type': 'code', 'redirect_uri': 'http://localhost'}
    spotify_authorize_url = spotify.get_authorize_url(**params)

    print 'Visit this URL in your browser: ' + spotify_authorize_url
    spotify_pin = raw_input('Enter code from URL: ')

    spotify_session = spotify.get_auth_session(method='POST',
                                               data={'code': spotify_pin, 
                                                     'grant_type': 'authorization_code',
                                                     'redirect_uri': 'http://localhost',},
                                               headers={'Authorization': 'Basic ' + base64.b64encode(spotify_client_id + ":" + spotify_client_secret)},
                                               decoder=json.loads)
                                                 
    return rdio_session, spotify_session
Esempio n. 15
0
    def __init__(self, clientKey, clientSecret, username, password):
        """Class Constructor assigns class variables and attempts authentication

        :param clientKey: Oauth1 client key
        :type clientKey: string
        :param clientSecret: Oauth1 client secret
        :type clientSecret: string
        :param username: FellowshipOne username
        :type username: string
        :param password: FellowshipOne password :type password: string"""

        # CT fellowshipone base URL
        self.baseUrl = "https://christny.fellowshiponeapi.com"

        # Hash credentials
        credential_string = "{} {}".format(username, password)
        credentials = b64encode(bytes(credential_string, "utf-8"))
        credentials = urllib.parse.quote_plus(credentials)

        # Setup OAuth1 Service to retrive Request Tokens
        service = OAuth1Service(
           consumer_key=clientKey,
           consumer_secret=clientSecret,
           request_token_url="%s/v1/PortalUser/AccessToken" % self.baseUrl
        )

        # Fetch tokens from fellowship one
        tokens = service.get_raw_request_token(data=credentials)
        tokens_content = urllib.parse.parse_qs(tokens.content)

        # Parse Ouath Request token and Secret
        oauth_token = tokens_content[b'oauth_token'][0].decode()
        oauth_tokensecret = tokens_content[b'oauth_token_secret'][0].decode()

        # Create a session that will be used for every following request
        session = OAuth1Session(
                clientKey,
                clientSecret,
                oauth_token,
                oauth_tokensecret
        )
        self.session = session
Esempio n. 16
0
 def set_up_service(self):
     if self.oauth2:
         self.qbService = OAuth2Service(
             client_id=self.client_id,
             client_secret=self.client_secret,
             name='noblebankint',
             authorize_url=self.authorization_endpoint,
             access_token_url=self.token_endpoint,
             base_url=None
         )
     else:
         self.qbService = OAuth1Service(
             name=None,
             consumer_key=self.consumer_key,
             consumer_secret=self.consumer_secret,
             request_token_url=self.request_token_url,
             access_token_url=self.access_token_url,
             authorize_url=self.authorize_url,
             base_url=None
         )
Esempio n. 17
0
    def authorize(self):

        # Get a real consumer key & secret from https://dev.twitter.com/apps/new
        self.srvc = OAuth1Service(
            name='yahoo',
            consumer_key=self.creds['consumer_key'],
            consumer_secret=self.creds['consumer_secret'],
            request_token_url=REQUEST_TOKEN_URL,
            access_token_url=GET_TOKEN_URL,
            authorize_url=AUTHORIZATION_URL,
            base_url=BASE_URL,
            signature_obj=HmacSha1Signature)

        if 'session_handle' not in self.creds:
            request_token, request_token_secret = \
             self.srvc.get_request_token(params={'oauth_callback': CALLBACK_URL,})
            authorize_url = self.srvc.get_authorize_url(request_token)
            webbrowser.open(authorize_url)
            verifier = raw_input("Input code given: ")
            try:
                session = self.get_access_token()
            except KeyError as e:
                if 'oauth_verifier_invalid' in e.message:
                    print "Verifier invalid."
                elif "oauth_problem=token_rejected" in e.message:
                    print "Token rejected."
                elif "oauth_problem=token_expired" in e.message:
                    print "Token expired."
                sys.exit(-1)
        else:
            try:
                session = self.renew_access_token()
            except KeyError as e:
                if 'oauth_verifier_invalid' in e.message:
                    print "Verifier invalid."
                elif "oauth_problem=token_rejected" in e.message:
                    print "Token rejected."
                elif "oauth_problem=token_expired" in e.message:
                    print "Token expired."
                sys.exit(-1)
        return session
Esempio n. 18
0
class QBAuth(object):
	qbo=OAuth1Service(
		name="qbo",
		consumer_key=settings.consumer_key,
		consumer_secret=settings.consumer_sec,
		request_token_url=settings.request_token_url,
		access_token_url=settings.access_token_url,
		authorize_url=settings.authorize_url,
		base_url=settings.base_url)

	def getRequestTokens(self):
		request_token, request_token_secret = self.qbo.get_request_token(params={'oauth_callback': "http://localhost:8000/oauth/authHandler"})
		self.request_token = request_token
		self.request_token_secret = request_token_secret
		print(request_token)
		authorize_url = self.qbo.get_authorize_url(request_token)
		return authorize_url
		
	def getAccessTokens(self, oauth_verifier):
		session_obj = self.qbo.get_auth_session(self.request_token, self.request_token_secret, data={'oauth_verifier': oauth_verifier})
		return session_obj
def get_access_tokens(test_config):
    connection = OAuth1Service(
        consumer_key=test_config['DEFAULT']['CONSUMER_KEY'],
        consumer_secret=test_config['DEFAULT']['CONSUMER_SECRET'],
        name='Hattrick',
        request_token_url=test_config['DEFAULT']['REQUEST_TOKEN_PATH'],
        access_token_url=test_config['DEFAULT']['ACCESS_TOKEN_PATH'],
        authorize_url=test_config['DEFAULT']['AUTHORIZE_PATH'],
        base_url=test_config['DEFAULT']['PROTECTED_RESOURCE_PATH'],
        signature_obj=HmacSha1Signature)
    request_token, request_token_secret = connection.get_request_token(
        params={'oauth_callback': test_config['DEFAULT']['CALLBACK_URL']})
    webbrowser.open(connection.get_authorize_url(request_token), new=2)
    if dw.show_string_input_window_in_thread(
            title='PIN Required',
            message='Please insert the PIN specified by Hattrick') is None:
        return False
    else:
        return True if add_access_tokens_to_config_file(
            test_config, connection, request_token, request_token_secret,
            code) else False
Esempio n. 20
0
    def __init__(self,
                 config: ServiceProvider,
                 stored_session: ProviderSession = None):
        self.name = f'etrade.{config.name.lower()}'
        self.log_prefix = f'[{self.name}]'
        self.config = config
        self.stored_session = stored_session
        self.service = OAuth1Service(
            name=config.name,
            consumer_key=config.consumer_key,
            consumer_secret=config.consumer_secret,
            request_token_url=config.request_token_url,
            access_token_url=config.access_token_url,
            authorize_url=config.authorize_url,
            base_url=config.base_url)

        self.session = None
        if stored_session and stored_session.access_token and stored_session.access_token_secret:
            self.session = self.service.get_session(
                token=(stored_session.access_token,
                       stored_session.access_token_secret))
Esempio n. 21
0
    def __oAuth(self):
        """ 
        Gets the authorization from the ETrade website to access the API endpoints. 
        Returns a authenticated session and base url to make requests to the API endpoints
        as a tuple.

        Based on the source code given on the eTrade documentation website that can be found at:
        https://developer.etrade.com/home 
        """
        etrade = OAuth1Service(
            name="etrade",
            consumer_key=self.__consumer_key,
            consumer_secret=self.__consumer_secret,
            request_token_url="https://api.etrade.com/oauth/request_token",
            access_token_url="https://api.etrade.com/oauth/access_token",
            authorize_url=
            "https://us.etrade.com/e/t/etws/authorize?key={}&token={}",
            base_url="https://api.etrade.com")

        # Step 1: Get OAuth 1 request token and secret
        request_token, request_token_secret = etrade.get_request_token(
            params={
                "oauth_callback": "oob",
                "format": "json"
            })

        # Step 2: Go through the authentication flow. Login to E*TRADE.
        # After you login, the page will provide a text code to enter.
        authorize_url = etrade.authorize_url.format(etrade.consumer_key,
                                                    request_token)
        webbrowser.open(authorize_url)
        text_code = input(
            "Please accept agreement and enter text code from browser: ")

        # Step 3: Exchange the authorized request token for an authenticated OAuth 1 session
        session = etrade.get_auth_session(request_token,
                                          request_token_secret,
                                          params={"oauth_verifier": text_code})

        return session
Esempio n. 22
0
def oauth():
    """Allows user authorization for the sample application with OAuth 1"""
    etrade = OAuth1Service(
        name="etrade",
        consumer_key=config["DEFAULT"]["CONSUMER_KEY"],
        consumer_secret=config["DEFAULT"]["CONSUMER_SECRET"],
        request_token_url="https://api.etrade.com/oauth/request_token",
        access_token_url="https://api.etrade.com/oauth/access_token",
        authorize_url="https://us.etrade.com/e/t/etws/authorize?key={}&token={}",
        base_url="https://api.etrade.com")

    base_url = config["DEFAULT"]["PROD_BASE_URL"]
    # Step 1: Get OAuth 1 request token and secret
    request_token, request_token_secret = etrade.get_request_token(
        params={"oauth_callback": "oob", "format": "json"})

    # Step 2: Go through the authentication flow. Login to E*TRADE.
    # After you login, the page will provide a text code to enter.
    authorize_url = etrade.authorize_url.format(etrade.consumer_key, request_token)
    webbrowser.open(authorize_url)
    text_code = input("Please accept agreement and enter text code from browser: ")

    # Step 3: Exchange the authorized request token for an authenticated OAuth 1 session
    session = etrade.get_auth_session(request_token,
                                  request_token_secret,
                                  params={"oauth_verifier": text_code})

    main_menu(session, base_url)

    def writeCSV(self, list):
        with open('port.csv', 'w', newline='') as csvfile:
            fieldnames = ['action', 'type', 'price', 'accountIdKey', 'symbolDescription', 'quantity', 'lastTrade', 'pricePaid', 'totalGain', 'marketValue',  'totalGainPct', 'daysGainPct', 'daysGain']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames, extrasaction='ignore')
            writer.writeheader()
            for port in list:
                port['action'] = "None"
                port['type'] = "STOP"
                port['lastTrade']=port['Quick']['lastTrade']
                port['price'] = int(port['Quick']['lastTrade'] * PERCENT)/100
                writer.writerow(port)
Esempio n. 23
0
    def get_access_tokens(self, oauth_verifier):
        """
        Wrapper around get_auth_session, returns session, and sets access_token and
        access_token_secret on the QB Object.
        :param oauth_verifier: the oauth_verifier as specified by OAuth 1.0a
        """
        qb_service = OAuth1Service(
            consumer_key=self.consumer_key,
            consumer_secret=self.consumer_secret,
            request_token_url=self.request_token_url,
            access_token_url=self.access_token_url,
            authorize_url=self.authorize_url,
        )

        session = qb_service.get_auth_session(
            self.request_token,
            self.request_token_secret,
            data={'oauth_verifier': oauth_verifier})

        self.access_token = session.access_token
        self.access_token_secret = session.access_token_secret
        return session
Esempio n. 24
0
    def __init__(self, app_key, app_secret, user_social_auth):
        """Constructor for YahooOAuthClient

        `app_key` - Yahoo App Key
        `app_secret` - Yahoo App Secret
        `user_social_auth` - UserSocialAuth model to store refreshed token
        """
        # UserSocialAuth needed to access the access token
        self.last_error = None
        self.user_social_auth = user_social_auth
        self.access_token = user_social_auth.extra_data.get('access_token')
        self.oauth = OAuth1Service(
            name='Yahoo',
            consumer_key=app_key,
            consumer_secret=app_secret,
            request_token_url=YAHOO_OAUTH_REQUEST_TOKEN_URL,
            access_token_url=YAHOO_OAUTH_ACCESS_TOKEN_URL,
            authorize_url=YAHOO_OAUTH_AUTHORIZE_URL,
        )
        self.session = self.oauth.get_session(
            (self.access_token['oauth_token'],
             self.access_token['oauth_token_secret']))
Esempio n. 25
0
    def EstablishOAuth(self):
        allyBank = OAuth1Service(
            name='Invest Magic',
            consumer_key='aN91TS2OaHIzoD1ejh6FwVtwjL4gGFs5e08edlumcsg7',
            consumer_secret='l6cT12lm2pcWabi5sRCg2LOXcxDR3T3CYisEVN4lPno6',
            request_token_url=
            'https://developers.tradeking.com/oauth/request_token',
            access_token_url=
            'https://developers.tradeking.com/oauth/access_token',
            authorize_url='https://developers.tradeking.com/oauth/authorize',
            base_url='https://api.tradeking.com/v1/')

        request_token, request_token_secret = allyBank.get_request_token()
        authorize_url = allyBank.get_authorize_url(request_token)

        print('Visit this URL in your browser: ' + authorize_url)
        pin = input('Enter PIN from browser: ')  # `input` if using Python 3!
        session = allyBank.get_auth_session(request_token,
                                            request_token_secret,
                                            method='POST',
                                            data={'oauth_verifier': pin})
        return session
Esempio n. 26
0
def yahoo_oauth():

    # We define a bunch of starter variables for rauth.
    ACCESS_TOKEN_URL = 'https://api.login.yahoo.com/oauth/v2/get_token'
    AUTHORIZE_URL = 'https://api.login.yahoo.com/oauth/v2/request_auth'
    REQUEST_TOKEN = 'https://api.login.yahoo.com/oauth/v2/get_request_token'

    if OAUTH_CONSUMER_KEY and OAUTH_SHARED_SECRET:
        # We use the rauth library to set up an Oauth session
        yahoo = OAuth1Service(name='yahoo',
                              consumer_key=OAUTH_CONSUMER_KEY,
                              consumer_secret=OAUTH_SHARED_SECRET,
                              request_token_url=REQUEST_TOKEN,
                              access_token_url=ACCESS_TOKEN_URL,
                              authorize_url=AUTHORIZE_URL,
                              base_url='https://api.login.yahoo.com/oauth/v2/')
        return yahoo

    else:
        print " Yahoo API login failed. You need to enter your api keys into the script."
        print " Get your keys here: http://developer.yahoo.com/fantasysports/"
        exit(1)
Esempio n. 27
0
    def __init__(self, host, key, secret, *args, **kwargs):
        """
        Initialize the MauticApi
        Inputs:
         host = with the host name without the last '/' e.g. 'https://www.mauticinstance.com'
         key = Mautic public key
         secret = Mautic secret key

        Optional Inputs in kwargs:
         access_token = Your access token from Mautic
         access_token_secret = Your access token secret from Mautic

        If you don't yet have your access token and access token secret, from the python shell:
         1) Initialize MauticApi (m = MauticApi(host, key, secret))
         2) Call request_and_authorize, and go to the returned URL in your browser (m.request_and_authorize())
         3) Approve the application
         4) Call get_access_token passing the oauth_verifier parameter (m.get_access_token(verifier))
         5) Get the access token from access_token (m.access_token)
         6) Get the access token secret from access_token_secret (m.access_token_secret)
        """
        self.host = host
        self.base_url = self.host + "/api/"
        self.mautic = OAuth1Service(
            name='mautic',
            consumer_key=key,
            consumer_secret=secret,
            request_token_url=self.host + "/oauth/v1/request_token",
            access_token_url=self.host + "/oauth/v1/access_token",
            authorize_url=self.host + "/oauth/v1/authorize",
            base_url=self.base_url)

        if "access_token" in kwargs:
            self.access_token = kwargs.pop("access_token")
            if "access_token_secret" in kwargs:
                self.access_token_secret = kwargs.pop("access_token_secret")
            else:
                raise InvalidToken("Token Secret is missing.")
            self.get_session()
Esempio n. 28
0
def start_service():
    host = 'http://restapi.surveygizmo.com/head'
    key = "put your oauth service key here"
    secret = "your client secret"
    #//This is the URL that we use to request a new access token
    request_token_url = host + '/oauth/request_token'
    #//After getting an access token we'll want to have the user authenicate 
    authorize_url = host + '/oauth/authenticate'
    # //this final call fetches an access token.
    access_token_url = host + '/oauth/access_token'
    import requests
    from rauth import OAuth1Service # requires requests
    # 1. create a rauth service object.
    service = OAuth1Service(
        name='surveygizmo',
        consumer_key= key, 
        consumer_secret= secret, 
        request_token_url= request_token_url, 
        access_token_url= access_token_url, 
        authorize_url= authorize_url, 
        base_url= host
        )
    return service
Esempio n. 29
0
def get_oauth_tokens(API_KEY, API_KEY_SECRET):
    """
    :param API_KEY: Smugmug API key
    :param API_KEY_SECRET: Smugmug Secret key
    :return: (access_token, secret_token)
    :rtype: tuple
    """

    SERVICE = OAuth1Service(name='smugmug-oauth',
                            consumer_key=API_KEY,
                            consumer_secret=API_KEY_SECRET,
                            request_token_url=settings.REQUEST_TOKEN_URL,
                            access_token_url=settings.ACCESS_TOKEN_URL,
                            authorize_url=settings.AUTHORIZE_URL,
                            base_url=settings.BASE_URL)

    rt, rts = SERVICE.get_request_token(params={'oauth_callback': 'oob'})
    auth_url = SERVICE.get_authorize_url(rt)
    print('Go to %s in a web browser.' % auth_url)
    sys.stdout.write('Enter the six-digit code: ')
    sys.stdout.flush()
    verifier = sys.stdin.readline().strip()
    at, ats = SERVICE.get_access_token(rt,
                                       rts,
                                       params={'oauth_verifier': verifier})
    print("NEW ACCESS_TOKEN:", at)
    print("NEW ACCESS_TOKEN_SECRET:", ats)
    session = OAuth1Session(API_KEY,
                            API_KEY_SECRET,
                            access_token=at,
                            access_token_secret=ats)
    print(
        session.get(settings.API_ORIGIN + '/api/v2!authuser',
                    headers={
                        'Accept': 'application/json'
                    }).json())
    return at, ats
Esempio n. 30
0
    def create_api_key():
        """ Interactively create a new API key via Zotero's OAuth API.

        Requires the user to enter a verification key displayed in the browser.

        :returns:   API key and the user's library ID
        """
        auth = OAuth1Service(name='zotero',
                             consumer_key=CLIENT_KEY,
                             consumer_secret=CLIENT_SECRET,
                             request_token_url=REQUEST_TOKEN_URL,
                             access_token_url=ACCESS_TOKEN_URL,
                             authorize_url=AUTH_URL,
                             base_url=BASE_URL)
        token, secret = auth.get_request_token(
            params={'oauth_callback': 'oob'})
        auth_url = auth.get_authorize_url(token)
        auth_url += '&' + urlencode({
            'name': 'zotero-cli',
            'library_access': 1,
            'notes_access': 1,
            'write_access': 1,
            'all_groups': 'read'
        })
        click.echo("Opening {} in browser, please confirm.".format(auth_url))
        click.launch(auth_url)
        verification = click.prompt("Enter verification code")
        token_resp = auth.get_raw_access_token(
            token,
            secret,
            method='POST',
            data={'oauth_verifier': verification})
        if not token_resp:
            logging.debug(token_resp.content)
            click.fail("Error during API key generation.")
        access = urlparse.parse_qs(token_resp.text)
        return access['oauth_token'][0], access['userID'][0]
Esempio n. 31
0
    def __init__(self,
                 consumer_key,
                 consumer_secret,
                 callback_url,
                 request_token=None,
                 request_token_secret=None):
        """

        :param consumer_key: Client consumer key, required for signing.
        :type consumer_key: str
        :param consumer_secret: Client consumer secret, required for signing.
        :type consumer_secret: str
        :param callback_url: Redirect url where quickbook must redirect after
            authentication
        :type callback_url: str
        :param request_token: Request Token as returned by
            :class:`get_request_token_pair`.
        :type request_token: str
        :param request_token_secret: Request Token Secret as returned by
            :class:`get_request_token_pair`.
        :type request_token_secret: str

        """

        self.qbservice = OAuth1Service(
            name=None,
            consumer_key=consumer_key,
            consumer_secret=consumer_secret,
            request_token_url=self.request_token_url,
            access_token_url=self.access_token_url,
            authorize_url=self.authorize_url,
            base_url=None)

        self.callback_url = callback_url
        self.request_token = request_token
        self.request_token_secret = request_token_secret
Esempio n. 32
0
 def __init__(self, app=None, base_url=None, consumer_key=None, consumer_secret=None, **kwargs):
     OAuth1Service.__init__(self, consumer_key=consumer_key, consumer_secret=consumer_secret, **kwargs)