def finalize_oauth_client(oauth_token, oauth_secret, oauth_verifier, consumer_key, consumer_secret, access_token_url): new_oauth_hook = OAuthHook(oauth_token, oauth_secret, consumer_key, consumer_secret) response = requests.post(access_token_url, {'oauth_verifier': oauth_verifier}, hooks={'pre_request': new_oauth_hook}) response = urlparse.parse_qs(response.content) access_token = response['oauth_token'][0] access_token_secret = response['oauth_token_secret'][0] oauth_hook = OAuthHook(access_token, access_token_secret, consumer_key, consumer_secret, header_auth=True) client = requests.session(hooks={'pre_request': oauth_hook}) client.access_token = access_token return client
def get_redirect_url(self, **kwargs): self.object = self.get_object() try: # get final oauth tokens oauth_hook = OAuthHook(self.request.GET['oauth_token'], self.request.GET['oauth_token_secret'], consumer_key=OAUTH_CONSUMER_KEY, consumer_secret=OAUTH_CONSUMER_SECRET) response = requests.post( 'https://www.khanacademy.org/api/auth/access_token', params={'oauth_verifier': self.request.GET['oauth_verifier']}, headers={'Content-Length': '0'}, hooks={'pre_request': oauth_hook}) response.raise_for_status() # Extract final oauth token qs = parse_qs(response.text) oauth_token = qs['oauth_token'][0] oauth_secret = qs['oauth_token_secret'][0] except (KeyError, RequestException): return reverse('khan_import_auth_problem', kwargs=dict(pk=self.object.pk)) # Build oauth hook for celery task to use final_oauth_hook = OAuthHook(oauth_token, oauth_secret, OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, True) # Start up the update process update_person.delay(final_oauth_hook, self.object) return reverse('started_khan_import', kwargs=dict(pk=self.object.pk))
def get_authorize_url(self): oauth_hook = OAuthHook(consumer_key=self.consumer_key, consumer_secret=self.consumer_secret) response = requests.post('%s/request_token' % self.URL, hooks={'pre_request': oauth_hook}) qs = parse_qs(response.text) self.oauth_token = qs['oauth_token'][0] self.oauth_secret = qs['oauth_token_secret'][0] return "%s/authorize?oauth_token=%s" % (self.URL, self.oauth_token)
def reg_user(self): init_oauth_hook = OAuthHook( consumer_key=self.authd['consumer_key'], consumer_secret=self.authd['consumer_secret']) req = requests.Request('POST', REQUEST_TOKEN_URL, params={'oauth_callback': CALLBACK_URL}) req = init_oauth_hook(req) session = requests.session() response = session.send(req.prepare()) qs = parse_qs(response.text) self.authd['oauth_token'] = (qs['oauth_token'][0]) self.authd['oauth_token_secret'] = (qs['oauth_token_secret'][0]) #now send user to approve app print "You will now be directed to a website for authorization.\n\ Please authorize the app, and then copy and paste the provide PIN below." print "URL: %s?oauth_token=%s" % (AUTHORIZATION_URL, self.authd['oauth_token']) self.authd['oauth_verifier'] = raw_input('Please enter your PIN:') print "OAuth Verifier: %s" % self.authd['oauth_verifier'] #get final auth token self.get_login_token()
def get_credentials(self, oauth_verifier): oauth_hook = OAuthHook(self.oauth_token, self.oauth_secret, self.consumer_key, self.consumer_secret) response = requests.post('%s/access_token' % self.URL, {'oauth_verifier': oauth_verifier}, hooks={'pre_request': oauth_hook}) response = parse_qs(response.content) return WithingsCredentials(response['oauth_token'][0], response['oauth_token_secret'][0], self.consumer_key, self.consumer_secret, response['userid'][0])
def oauth_client(token, secret, consumer_key, consumer_secret, header_auth=True): """An OAuth client that can issue get requests.""" hook = OAuthHook(token, secret, consumer_key, consumer_secret, header_auth) client = requests.session(hooks={'pre_request': hook}) client.get = wrapget(client.get) client.post = wrapget(client.post) return client
def post_to_twitter(url): hook = OAuthHook(settings.ACCESS_TOKEN, settings.ACCESS_TOKEN_SECRET, settings.CONSUMER_KEY, settings.CONSUMER_SECRET) client = requests.session(hooks={'pre_request': hook}) status = 'Pygrunn #5 example: {url}'.format(url=url) response = client.post('http://api.twitter.com/1/statuses/update.json', {'status': status}) return response.content
def auth(): """Return an authorized requests client.""" key = os.getenv('TUMBLR_CONSUMER_KEY') secret = os.getenv('TUMBLR_CONSUMER_SECRET') oauth_token = os.getenv('TUMBLR_OAUTH_KEY') oauth_secret = os.getenv('TUMBLR_OAUTH_SECRET') oauth = OAuthHook(key, secret, oauth_token, oauth_secret, True) return req.session(hooks={'pre_request': oauth})
def setToken(self, token_key, token_secret): self.token_key = token_key self.token_secret = token_secret self.my_oauth_hook = OAuthHook( access_token=token_key, access_token_secret=token_secret, consumer_key=self.config['app']['consumer_key'], consumer_secret=self.config['app']['consumer_secret'])
def request_token(self, url, **kw): """Request an unauthorized token at the request token url. kws passed to requests.get""" hook = OAuthHook(**self.client_params) client = requests.session(hooks={'pre_request': hook}) response = client.get(url, **kw) data = cgi_clean(response.text) return dict(secret=data["oauth_token_secret"], key=data["oauth_token"])
def auth(app_id, app_secret): OAuthHook.consumer_key = app_id OAuthHook.consumer_secret = app_secret oauth_hook = OAuthHook('', '') client = requests.session(hooks={'pre_request': oauth_hook}) request = client.get(AUTH_URL % (app_id, app_secret)) access_token = request.headers['x-access-token'] access_token_expires = request.headers['x-access-token-expires'] return (access_token, access_token_expires)
def call_api(self, url, req_meth='GET', data=None, headers=None): req_oauth_hook = OAuthHook(self.authd['oauth_token'], self.authd['oauth_token_secret'], self.authd['consumer_key'], self.authd['consumer_secret'], header_auth=True) client = requests.session(hooks={'pre_request': req_oauth_hook}) return client.request(method=req_meth, url=url, data=data, headers=headers)
def get_login_token(self): oauth_hook = OAuthHook(self.authd['oauth_token'], self.authd['oauth_token_secret'], self.authd['consumer_key'], self.authd['consumer_secret']) response = requests.post( GET_TOKEN_URL, {'oauth_verifier': self.authd['oauth_verifier']}, hooks={'pre_request': oauth_hook}) qs = parse_qs(response.content) self.authd.update(map(lambda d: (d[0], (d[1][0])), qs.items())) self.write_authvals_csv(self.authd, self.authf) return response
def __init__(self, consumer_key, consumer_secret, oauth_token=None, oauth_token_secret=None, sandbox=False): self.params = {'api_key': consumer_key} self.consumer_key = consumer_key self.consumer_secret = consumer_secret if sandbox: self.url_base = "http://sandbox.openapi.etsy.com/v2" # generic authenticated oauth hook self.simple_oauth = OAuthHook(consumer_key=consumer_key, consumer_secret=consumer_secret) if oauth_token and oauth_token_secret: # full oauth hook for an authenticated user self.full_oauth = OAuthHook(oauth_token, oauth_token_secret, consumer_key, consumer_secret)
def authorize(self): try: # Step 0: Initialize to just our consumer key and secret. self.my_oauth_hook = OAuthHook( consumer_key=self.config['app']['consumer_key'], consumer_secret=self.config['app']['consumer_secret']) # Step 1: Get a request token. This is a temporary token that is used for # having the user authorize an access token and to sign the request to obtain # said access token. self.requestToken() # Step 2: Redirect to the provider. Since this is a CLI script we do not # redirect. In a web application you would redirect the user to the URL # below. print print "Please visit BotQueue.com or simply visit this URL to authenticate Bumblebee: %s" % \ self.getAuthorizeUrl() print # webbrowser.open_new(self.getAuthorizeUrl()) authorized = False while not authorized: try: # After the user has granted access to you, the consumer, the provider will # redirect you to whatever URL you have told them to redirect to. You can # usually define this in the oauth_callback argument as well. # oauth_verifier = raw_input('What is the PIN? ') # Step 3: Once the consumer has redirected the user back to the oauth_callback # URL you can request the access token the user has approved. You use the # request token to sign this request. After this is done you throw away the # request token and use the access token returned. You should store this # access token somewhere safe, like a database, for future use. self.convertToken() authorized = True # we're basically polling the convert function until the user approves it. # throwing the exception is totally normal. except Exception as ex: time.sleep(10) # record the key in our config self.config['app']['token_key'] = self.token_key self.config['app']['token_secret'] = self.token_secret hive.config.save(self.config) except Exception as ex: self.log.exception(ex) print "There was a problem authorizing the app: %s" % (ex) raise RuntimeError("There was a problem authorizing the app: %s" % (ex))
def refresh_token(self): oauth_hook = OAuthHook( access_token=self.authd['oauth_token'], access_token_secret=self.authd['oauth_token_secret'], consumer_key=self.authd['consumer_key'], consumer_secret=self.authd['consumer_secret']) response = requests.post( GET_TOKEN_URL, {'oauth_session_handle': self.authd['oauth_session_handle']}, hooks={'pre_request': oauth_hook}) qs = parse_qs(response.content) self.authd.update(map(lambda d: (d[0], (d[1][0])), qs.items())) self.write_authvals_csv(self.authd, self.authf)
def get_user_info(screen_name): """Given a unicode, return a dict. """ typecheck(screen_name, unicode) rec = gittip.db.fetchone( "SELECT user_info FROM elsewhere " "WHERE platform='twitter' " "AND user_info->'screen_name' = %s", (screen_name, )) if rec is not None: user_info = rec['user_info'] else: oauth = OAuthHook( # we haven't got access to the website obj, # so let's grab the details from the env access_token=environ['TWITTER_ACCESS_TOKEN'], access_token_secret=environ['TWITTER_ACCESS_TOKEN_SECRET'], consumer_key=environ['TWITTER_CONSUMER_KEY'], consumer_secret=environ['TWITTER_CONSUMER_SECRET'], header_auth=True) url = "https://api.twitter.com/1.1/users/show.json?screen_name=%s" user_info = requests.get(url % screen_name, hooks={'pre_request': oauth}) # Keep an eye on our Twitter usage. # ================================= rate_limit = user_info.headers['X-RateLimit-Limit'] rate_limit_remaining = user_info.headers['X-RateLimit-Remaining'] rate_limit_reset = user_info.headers['X-RateLimit-Reset'] try: rate_limit = int(rate_limit) rate_limit_remaining = int(rate_limit_remaining) rate_limit_reset = int(rate_limit_reset) except (TypeError, ValueError): log("Got weird rate headers from Twitter: %s %s %s" % (rate_limit, rate_limit_remaining, rate_limit_reset)) else: reset = datetime.datetime.fromtimestamp(rate_limit_reset, tz=utc) reset = to_age(reset) log("Twitter API calls used: %d / %d. Resets %s." % (rate_limit - rate_limit_remaining, rate_limit, reset)) if user_info.status_code == 200: user_info = json.loads(user_info.text) else: log("Twitter lookup failed with %d." % user_info.status_code) raise Response(404) return user_info
def call_api(self, url, req_meth='GET', data=None, headers=None): req = requests.Request(req_meth, url, data=data, headers=headers) req_oauth_hook = OAuthHook(self.authd['oauth_token'], self.authd['oauth_token_secret'], self.authd['consumer_key'], self.authd['consumer_secret'], header_auth=True) req = req_oauth_hook(req) session = requests.session() # Sleep for 2 seconds to ratelimit API requests. More than this for # too long and you'll be locked out of the API. time.sleep(.5) self.num_api_requests += 1 # Send the request resp = session.send(req.prepare()) return resp
def make_request(user, url): OAuthHook.consumer_key = FRONTEND_KEY OAuthHook.consumer_secret = FRONTEND_SECRET hook = OAuthHook(access_token=user['access_token'], access_token_secret=user['access_token_secret'], header_auth=True) client = requests.session(hooks={'pre_request': hook}) response = client.get(DATA_HOST + url) if response.status_code != 200: return None return json.loads(response.content)
def example(): oauth_hook = OAuthHook(access_token=OAUTH_TOKEN, access_token_secret=OAUTH_SECRET, consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, header_auth=False) client = requests.session(hooks={ 'pre_request': oauth_hook, 'response': throttle_hook }) return client.get( "https://api.twitter.com/1/users/show.json?screen_name=steveWINton")
def get_oauth_client(): """ Create an application at https://dev.twitter.com/apps Copy the credentials here """ consumer_key = "<consumer key>" consumer_secret = "<consumer secret>" access_token = "<access token>" access_token_secret = "<access token secret>" header_auth = True oauth_hook = OAuthHook(access_token, access_token_secret, consumer_key, consumer_secret, header_auth) client = requests.session(hooks={'pre_request': oauth_hook}) return client
def __init__(self,identi_token=None,identi_secret=None,oauth_token=None,oauth_secret=None,callback_url=None,header=None): # Needed for hitting that there API. self.request_token_url = 'https://identi.ca/api/oauth/request_token' self.access_token_url = 'https://identi.ca/api/oauth/access_token' self.authorize_url = 'https://identi.ca/api/oauth/authorize' #This is not used up. self.authenticate_url = 'https://twitter.com/oauth/authenticate' #This is also not used up. self.identi_token = identi_token self.identi_secret = identi_secret self.oauth_token = oauth_token self.oauth_secret = oauth_secret self.callback_url = callback_url if self.identi_token is not None: OAuthHook.consumer_key = self.identi_token OAuthHook.consumer_secret = self.identi_secret oauth_hook = OAuthHook(self.oauth_token,self.oauth_secret) self.headers = header if self.headers is None: self.headers = { 'User-agent': 'Identi.ca Python Library' } self.client = None #See https://github.com/ctoth/requests-oauth-hook if self.identi_token is not None and self.identi_secret is not None: self.client = requests.session(hooks={'pre_request': oauth_hook}) if self.oauth_token is not None and self.oauth_secret is not None: self.oauth_hook = OAuthHook(self.oauth_token, self.oauth_secret) self.client = requests.session(hooks={'pre_request': self.oauth_hook}) if self.client is None: self.client = requests.session() #Register functions. (**kwargs - For unpacking dictionaries) def setFunc(key): return lambda **kwargs: self._constructFunc(key, **kwargs) for key in list(api_table.keys()): self.__dict__[key] = setFunc(key)
def create_card(trello_id): # Get user user = User.query.get((_get_email(request.form['From']), trello_id)) if not user: abort(404) # Get lists subject = request.form['Subject'] trello_lists = json.loads(user.trello_lists) trello_list_ids = [] for list_id, keyword in trello_lists.items(): if keyword in subject: trello_list_ids.append(list_id) if not trello_list_ids: abort(404) # Set trello client oauth_hook = OAuthHook( access_token=user.trello_oauth_token, access_token_secret=user.trello_oauth_token_secret, **consumer) trello_client = requests.session(hooks={'pre_request': oauth_hook}) # Create cards cards = [] for list_id in trello_list_ids: data = { 'name': subject, 'desc': request.form['body-plain'], 'idList': list_id, } card = (trello_client.post(TRELLO_API_ENDPOINT % 'cards', data=data) .json) cards.append(card) # Add members from cc addresses for cc in request.form.get('Cc', '').split(','): email = _get_email(cc) if not email: continue cc_user = User.query.filter_by(email=email).first() if not cc_user: continue data = { 'value': cc_user.trello_id, } trello_client.post( TRELLO_API_ENDPOINT % 'cards/%s/members' % card['id'], data) return jsonify({'cards': cards})
def use_auth_url_fn(request_url, authorize_url, access_token_url, consumer_key, consumer_secret, auth_url_fn): pre_oauth_hook = OAuthHook(consumer_key=consumer_key, consumer_secret=consumer_secret) response = requests.post(request_url, hooks={'pre_request': pre_oauth_hook}) qs = urlparse.parse_qs(response.text) oauth_token = qs['oauth_token'][0] oauth_secret = qs['oauth_token_secret'][0] auth_url = authorize_url + "?oauth_token=" + oauth_token auth_url_fn(auth_url) return oauth_token, oauth_secret
def get_auth_token(self, verifier, oauth_token, oauth_token_secret): """ Step two in the authentication process. oauth_token and oauth_token_secret are the same that came from the get_auth_url function call. Returned is the permanent oauth_token and oauth_token_secret that will be used in every subsiquent api request that requires authentication. """ endpoint = '/oauth/access_token' self.params = {'oauth_verifier': verifier} oauth = OAuthHook(oauth_token, oauth_token_secret, self.consumer_key, self.consumer_secret) response = self.execute(endpoint, method='post', oauth=oauth) parsed = parse_qs(response.text) return { 'oauth_token': parsed['oauth_token'][0], 'oauth_token_secret': parsed['oauth_token_secret'][0] }
def _get_authorized_client(self, linkedin_key, linkedin_secret, oauth_token=None, oauth_token_secret=None): """ get Authorized Oauth Client using requests and an OAuthHook """ OAuthHook.consumer_key = linkedin_key OAuthHook.consumer_secret = linkedin_secret oauth_hook = OAuthHook(access_token=oauth_token, access_token_secret=oauth_token_secret, header_auth=True) client = requests.session(hooks={'pre_request': oauth_hook}) return client
def get_redirect_url(self, **kwargs): self.object = self.get_object() # set up the initial request for a request token oauth_hook = OAuthHook(consumer_key=OAUTH_CONSUMER_KEY, consumer_secret=OAUTH_CONSUMER_SECRET) # generate the callback (return) url oauth_callback = self.request.build_absolute_uri( reverse('start_khan_import', kwargs=dict(pk=self.object.pk))) # make the request response = requests.post( 'https://www.khanacademy.org/api/auth/request_token', params={'oauth_callback': oauth_callback}, headers={'Content-Length': '0'}, hooks={'pre_request': oauth_hook}, allow_redirects=False) return response.headers['location']
def reg_user(self): init_oauth_hook = OAuthHook( consumer_key=self.authd['consumer_key'], consumer_secret=self.authd['consumer_secret']) response = requests.post(REQUEST_TOKEN_URL, params={'oauth_callback': CALLBACK_URL}, hooks={'pre_request': init_oauth_hook}) qs = parse_qs(response.text) self.authd['oauth_token'] = (qs['oauth_token'][0]) self.authd['oauth_token_secret'] = (qs['oauth_token_secret'][0]) #now send user to approve app print "You will now be directed to a website for authorization.\n\ Please authorize the app, and then copy and paste the provide PIN below." webbrowser.open("%s?oauth_token=%s" % (AUTHORIZATION_URL, self.authd['oauth_token'])) self.authd['oauth_verifier'] = raw_input('Please enter your PIN:') #get final auth token self.get_login_token()
def __init__(self, access_token=None, access_token_secret=None, consumer_key=None, consumer_secret=None, header_auth=True, max_retries=5): Greenlet.__init__(self) self.access_token = access_token self.access_token_secret = access_token_secret self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.header_auth = header_auth self.max_retries = max_retries oauth_hook = OAuthHook(access_token=access_token, access_token_secret=access_token_secret, consumer_key=consumer_key, consumer_secret=consumer_secret, header_auth=header_auth) self.hooks = dict(hooks={'pre_request': oauth_hook})
def __init__(self): self.app_id = settings.API['app_id'] self.app_secret = settings.API['app_secret'] self.oauth_redirect_url = settings.API['oauth_redirect_url'] self.app_scope = settings.API['app_scope'] self.base_url = settings.API['base_url'] % ( settings.API['sk_subdomain']) self.sk_user = settings.API['sk_user'] self.sk_pw = settings.API['sk_pw'] # use oauth only if basic auth is not possible self.use_oauth = (self.sk_user is None or self.sk_pw is None) self.access_token_url = u"%s%s" % (self.base_url, settings.ACCESS_TOKEN_URL) self.client = None if self.use_oauth: OAuthHook.consumer_key = consumer_key OAuthHook.consumer_secret = consumer_secret self.oauth_hook = OAuthHook(access_token, access_token_secret, header_auth=True) if self.app_id is None or len(self.app_id) == 0: raise Exception( "please configure your sdk in salesking.conf.local_settings")