def stored_oauth(): consumer = oauth.Consumer(jiraappy.CONSUMER_KEY, jiraappy.CONSUMER_SECRET) accessToken = oauth.Token(jiraappy.JIRA_OAUTH_TOKEN, jiraappy.JIRA_OAUTH_SECRET) client = oauth.Client(consumer, accessToken) client.set_signature_method(SignatureMethod_RSA_SHA1()) return consumer, client
def get_credentials(self, key): request_token = dict(oauth_token=sickbeard.TWITTER_USERNAME, oauth_token_secret=sickbeard.TWITTER_PASSWORD, oauth_callback_confirmed='true') token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) self._log_debug('Generating and signing request for an access token using key ' + key) # noinspection PyUnusedLocal signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) self._log_debug('oauth_consumer: ' + str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) self._log_debug('oauth_client: ' + str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) self._log_debug('resp, content: ' + str(resp) + ',' + str(content)) access_token = dict(parse_qsl(content)) self._log_debug('access_token: ' + str(access_token)) self._log_debug('resp[status] = ' + str(resp['status'])) if '200' != resp['status']: self._log_error('The request for a token with did not succeed: ' + str(resp['status'])) result = False else: self._log_debug('Your Twitter Access Token key: %s' % access_token['oauth_token']) self._log_debug('Access Token secret: %s' % access_token['oauth_token_secret']) sickbeard.TWITTER_USERNAME = access_token['oauth_token'] sickbeard.TWITTER_PASSWORD = access_token['oauth_token_secret'] result = True message = ('Key verification successful', 'Unable to verify key')[not result] logger.log(u'%s result: %s' % (self.name, message)) return self._choose(message, result)
def create_shelf(self, shelf='lazylibrarian'): global consumer, client, token, user_id if not lazylibrarian.CONFIG['GR_API'] or not lazylibrarian.CONFIG['GR_SECRET'] or not \ lazylibrarian.CONFIG['GR_OAUTH_TOKEN'] or not lazylibrarian.CONFIG['GR_OAUTH_SECRET']: logger.warn("Goodreads create shelf error: Please authorise first") return False, 'Unauthorised' consumer = oauth.Consumer(key=str(lazylibrarian.CONFIG['GR_API']), secret=str( lazylibrarian.CONFIG['GR_SECRET'])) token = oauth.Token(lazylibrarian.CONFIG['GR_OAUTH_TOKEN'], lazylibrarian.CONFIG['GR_OAUTH_SECRET']) client = oauth.Client(consumer, token) user_id = self.getUserId() # could also pass [featured] [exclusive_flag] [sortable_flag] all default to False body = urlencode({'user_shelf[name]': shelf.lower()}) headers = {'Content-Type': 'application/x-www-form-urlencoded'} time_now = int(time.time()) if time_now <= lazylibrarian.LAST_GOODREADS: time.sleep(1) lazylibrarian.LAST_GOODREADS = time_now try: response, content = client.request( '%s/user_shelves.xml' % 'https://www.goodreads.com', 'POST', body, headers) except Exception as e: return False, "Exception in client.request: %s %s" % ( type(e).__name__, str(e)) if response['status'] != '200' and response['status'] != '201': msg = 'Failure status: %s' % response['status'] return False, msg return True, ''
def _get_linkedin_user_info(self, auth_info, key=None, secret=None): """Returns a dict of currently logging in linkedin user. LinkedIn user profile API endpoint: http://api.linkedin.com/v1/people/~ or http://api.linkedin.com/v1/people/~:<fields> where <fields> is something like (id,first-name,last-name,picture-url,public-profile-url,headline) """ token = oauth1.Token(key=auth_info['oauth_token'], secret=auth_info['oauth_token_secret']) client = self._oauth1_client(token, key, secret) fields = 'id,first-name,last-name,picture-url,public-profile-url,headline' url = 'http://api.linkedin.com/v1/people/~:(%s)' % fields resp, content = client.request(url) # HACKING this out because I don't want lxml -AaronLifshin # person = etree.fromstring(content) uinfo = {} # for e in person: # uinfo.setdefault(e.tag, e.text) uinfo.setdefault('NOT SUPPORTED', 'NOT SUPPORTED') return uinfo
def request_oauth(oauth_token): consumer = oauth.Consumer(jiraappy.CONSUMER_KEY, jiraappy.CONSUMER_SECRET) token = oauth.Token(oauth_token, oauth_token) client = oauth.Client(consumer, token) client.set_signature_method(SignatureMethod_RSA_SHA1()) return consumer, client
def _get_credentials(self, key): request_token = {'oauth_token': lazylibrarian.CONFIG['TWITTER_USERNAME'], 'oauth_token_secret': lazylibrarian.CONFIG['TWITTER_PASSWORD'], 'oauth_callback_confirmed': 'true'} token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key ' + key) _ = oauth.SignatureMethod_HMAC_SHA1() oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: ' + str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: ' + str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: ' + str(resp) + ',' + str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: ' + str(access_token)) logger.info('resp[status] = ' + str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: ' + str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.CONFIG['TWITTER_USERNAME'] = access_token['oauth_token'] lazylibrarian.CONFIG['TWITTER_PASSWORD'] = access_token['oauth_token_secret'] return True
def create_shelf(self, shelf='lazylibrarian'): global consumer, client, token, user_id if not lazylibrarian.CONFIG['GR_API'] or not lazylibrarian.CONFIG['GR_SECRET'] or not \ lazylibrarian.CONFIG['GR_OAUTH_TOKEN'] or not lazylibrarian.CONFIG['GR_OAUTH_SECRET']: logger.warn("Goodreads create shelf error: Please authorise first") return False, 'Unauthorised' consumer = oauth.Consumer(key=str(lazylibrarian.CONFIG['GR_API']), secret=str( lazylibrarian.CONFIG['GR_SECRET'])) token = oauth.Token(lazylibrarian.CONFIG['GR_OAUTH_TOKEN'], lazylibrarian.CONFIG['GR_OAUTH_SECRET']) client = oauth.Client(consumer, token) user_id = self.getUserId() # could also pass [featured] [exclusive_flag] [sortable_flag] all default to False body = urlencode({'user_shelf[name]': shelf.lower()}) headers = {'Content-Type': 'application/x-www-form-urlencoded'} gr_api_sleep() try: response, content = client.request( '%s/user_shelves.xml' % 'https://www.goodreads.com', 'POST', body, headers) except Exception as e: logger.error("Exception in client.request: %s %s" % (type(e).__name__, traceback.format_exc())) return False, "Error in client.request: see error log" if not response['status'].startswith('2'): msg = 'Failure status: %s' % response['status'] return False, msg return True, ''
def verified_oauth(oauth_token, oauth_token_secret): consumer = oauth.Consumer(jiraappy.CONSUMER_KEY, jiraappy.CONSUMER_SECRET) accessToken = oauth.Token(oauth_token, oauth_token_secret) client = oauth.Client(consumer, accessToken) client.set_signature_method(SignatureMethod_RSA_SHA1()) return consumer, client
def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = sickbeard.TWITTER_USERNAME request_token['oauth_token_secret'] = sickbeard.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.log('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.log('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.log('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.log('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.log('access_token: '+str(access_token)) logger.log('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.log('The request for a token with did not succeed: '+str(resp['status']), logger.ERROR) return False else: logger.log('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.log('Access Token secret: %s' % access_token['oauth_token_secret']) sickbeard.TWITTER_USERNAME = access_token['oauth_token'] sickbeard.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True
def __init__(self, consumer_key, consumer_secret, oauth_token, oauth_token_secret): self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.token = oauth2.Token(oauth_token, oauth_token_secret) self.scope = "https://www.google.com/fusiontables/api/query"
def goodreads_oauth2(): global request_token, consumer, token, client try: if request_token and 'oauth_token' in request_token and 'oauth_token_secret' in request_token: token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) else: return "Unable to run oAuth2 - Have you run oAuth1?" except Exception as e: logger.error("Exception in oAuth2: %s %s" % (type(e).__name__, traceback.format_exc())) return "Unable to run oAuth2 - Have you run oAuth1?" access_token_url = '%s/oauth/access_token' % 'https://www.goodreads.com' client = oauth.Client(consumer, token) try: response, content = client.request(access_token_url, 'POST') except Exception as e: logger.error("Exception in oauth2 client.request: %s %s" % (type(e).__name__, traceback.format_exc())) return "Error in oauth2 client request: see error log" if not response['status'].startswith('2'): return 'Invalid response [%s] from %s' % (response['status'], access_token_url) access_token = dict(parse_qsl(content)) if not PY2: access_token = {key.decode("utf-8"): access_token[key].decode("utf-8") for key in access_token} # print access_token lazylibrarian.CONFIG['GR_OAUTH_TOKEN'] = access_token['oauth_token'] lazylibrarian.CONFIG['GR_OAUTH_SECRET'] = access_token['oauth_token_secret'] lazylibrarian.config_write('API') return "Authorisation complete"
def get_shelf_list(self): global consumer, client, token, user_id if not lazylibrarian.CONFIG['GR_API'] or not lazylibrarian.CONFIG['GR_SECRET'] or not \ lazylibrarian.CONFIG['GR_OAUTH_TOKEN'] or not lazylibrarian.CONFIG['GR_OAUTH_SECRET']: logger.warn("Goodreads get shelf error: Please authorise first") return [] else: # # loop over each page of shelves # loop over each shelf # add shelf to list # consumer = oauth.Consumer(key=str(lazylibrarian.CONFIG['GR_API']), secret=str(lazylibrarian.CONFIG['GR_SECRET'])) token = oauth.Token(lazylibrarian.CONFIG['GR_OAUTH_TOKEN'], lazylibrarian.CONFIG['GR_OAUTH_SECRET']) client = oauth.Client(consumer, token) user_id = self.getUserId() current_page = 0 shelves = [] page_shelves = 1 while page_shelves: current_page = current_page + 1 page_shelves = 0 shelf_template = Template('${base}/shelf/list.xml?user_id=${user_id}&key=${key}&page=${page}') body = urlencode({}) headers = {'Content-Type': 'application/x-www-form-urlencoded'} request_url = shelf_template.substitute(base='https://www.goodreads.com', user_id=user_id, page=current_page, key=lazylibrarian.CONFIG['GR_API']) gr_api_sleep() try: response, content = client.request(request_url, 'GET', body, headers) except Exception as e: logger.error("Exception in client.request: %s %s" % (type(e).__name__, traceback.format_exc())) return shelves if not response['status'].startswith('2'): logger.error('Failure status: %s for page %s' % (response['status'], current_page)) if lazylibrarian.LOGLEVEL & lazylibrarian.log_grsync: logger.debug(request_url) else: xmldoc = xml.dom.minidom.parseString(content) shelf_list = xmldoc.getElementsByTagName('shelves')[0] for item in shelf_list.getElementsByTagName('user_shelf'): shelf_name = item.getElementsByTagName('name')[0].firstChild.nodeValue shelf_count = item.getElementsByTagName('book_count')[0].firstChild.nodeValue shelf_exclusive = item.getElementsByTagName('exclusive_flag')[0].firstChild.nodeValue shelves.append({'name': shelf_name, 'books': shelf_count, 'exclusive': shelf_exclusive}) page_shelves += 1 if lazylibrarian.LOGLEVEL & lazylibrarian.log_grsync: logger.debug('Shelf %s : %s: Exclusive %s' % (shelf_name, shelf_count, shelf_exclusive)) if lazylibrarian.LOGLEVEL & lazylibrarian.log_grsync: logger.debug('Found %s shelves on page %s' % (page_shelves, current_page)) logger.debug('Found %s shelves on %s page%s' % (len(shelves), current_page - 1, plural(current_page - 1))) # print shelves return shelves
def goodreads_oauth2(): global request_token, consumer, token, client # noinspection PyBroadException try: token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) except Exception: return "Unable to run oAuth2. Have you run oAuth1?" access_token_url = '%s/oauth/access_token' % 'https://www.goodreads.com' client = oauth.Client(consumer, token) try: response, content = client.request(access_token_url, 'POST') except Exception as e: return "Exception in client.request: %s %s" % (type(e).__name__, str(e)) if response['status'] != '200': return 'Invalid response: %s' % response['status'] access_token = dict(parse_qsl(content)) # print access_token lazylibrarian.CONFIG['GR_OAUTH_TOKEN'] = access_token['oauth_token'] lazylibrarian.CONFIG['GR_OAUTH_SECRET'] = access_token[ 'oauth_token_secret'] lazylibrarian.config_write('API') return {"Authorisation complete"}
def __init__(self, consumer_key, consumer_secret, token_key, token_secret): if not has_oauth: raise ImportError("No module named oauth2") super(OAuth2Method, self).__init__() consumer = oauth.Consumer(consumer_key, consumer_secret) token = oauth.Token(token_key, token_secret) self.authorized_client = oauth.Client(consumer, token)
def get_gr_shelf_contents(self, shelf='to-read'): global consumer, client, token, user_id if not lazylibrarian.CONFIG['GR_API'] or not lazylibrarian.CONFIG['GR_SECRET'] or not \ lazylibrarian.CONFIG['GR_OAUTH_TOKEN'] or not lazylibrarian.CONFIG['GR_OAUTH_SECRET']: logger.warn( "Goodreads shelf contents error: Please authorise first") return [] else: # # loop over each page of owned books # loop over each book # add book to list # consumer = oauth.Consumer(key=str(lazylibrarian.CONFIG['GR_API']), secret=str( lazylibrarian.CONFIG['GR_SECRET'])) token = oauth.Token(lazylibrarian.CONFIG['GR_OAUTH_TOKEN'], lazylibrarian.CONFIG['GR_OAUTH_SECRET']) client = oauth.Client(consumer, token) user_id = self.getUserId() logger.debug('User id is: ' + user_id) current_page = 0 total_books = 0 gr_list = [] while True: current_page = current_page + 1 content = self.getShelfBooks(current_page, shelf) xmldoc = xml.dom.minidom.parseString(content) page_books = 0 for book in xmldoc.getElementsByTagName('book'): book_id, book_title = self.getBookInfo(book) if lazylibrarian.LOGLEVEL > 2: try: logger.debug('Book %10s : %s' % (str(book_id), book_title)) except UnicodeEncodeError: logger.debug('Book %10s : %s' % (str(book_id), 'Title Messed Up By Unicode Error')) gr_list.append(book_id) page_books += 1 total_books += 1 if lazylibrarian.LOGLEVEL > 2: logger.debug('Found %s books on page %s (total = %s)' % (page_books, current_page, total_books)) if page_books == 0: break logger.debug('Found %s' % total_books) return gr_list
def get_gr_shelf(self, shelf='to-read'): if not self.key or not self.secret or not self.oauth_token or not self.oauth_secret: logger.debug("Goodreads sync error: Please authorise first") return [] else: # # loop over each page of owned books # loop over each book # add book to list # if not self.consumer: self.consumer = oauth.Consumer(key=str(self.key), secret=str(self.secret)) if not self.token: self.token = oauth.Token(self.oauth_token, self.oauth_secret) if not self.client: self.client = oauth.Client(self.consumer, self.token) self.user_id = self.getUserId() logger.debug('User id is: ' + self.user_id) current_page = 0 total_books = 0 gr_list = [] while True: current_page = current_page + 1 time_now = int(time.time()) if time_now <= lazylibrarian.LAST_GOODREADS: time.sleep(1) lazylibrarian.LAST_GOODREADS = time_now content = self.getShelfBooks(current_page, shelf) xmldoc = xml.dom.minidom.parseString(content) page_books = 0 for book in xmldoc.getElementsByTagName('book'): book_id , book_title = self.getBookInfo(book) if lazylibrarian.LOGLEVEL > 2: try: logger.debug('Book %10s : %s' % (str(book_id), book_title)) except UnicodeEncodeError: logger.debug('Book %10s : %s' % (str(book_id), 'Title Messed Up By Unicode Error')) gr_list.append(book_id) page_books += 1 total_books += 1 logger.debug('Found %s books on page %s (total = %s)' % (page_books, current_page, total_books)) if page_books == 0: break logger.debug('Found %s' % total_books) return gr_list
def follow_author(self, authorid=None, follow=True): global consumer, client, token, user_id if not lazylibrarian.CONFIG['GR_API'] or not lazylibrarian.CONFIG['GR_SECRET'] or not \ lazylibrarian.CONFIG['GR_OAUTH_TOKEN'] or not lazylibrarian.CONFIG['GR_OAUTH_SECRET']: logger.warn( "Goodreads follow author error: Please authorise first") return False, 'Unauthorised' consumer = oauth.Consumer(key=str(lazylibrarian.CONFIG['GR_API']), secret=str( lazylibrarian.CONFIG['GR_SECRET'])) token = oauth.Token(lazylibrarian.CONFIG['GR_OAUTH_TOKEN'], lazylibrarian.CONFIG['GR_OAUTH_SECRET']) client = oauth.Client(consumer, token) user_id = self.getUserId() # follow https://www.goodreads.com/author_followings?id=AUTHOR_ID&format=xml # unfollow https://www.goodreads.com/author_followings/AUTHOR_FOLLOWING_ID?format=xml time_now = int(time.time()) if time_now <= lazylibrarian.LAST_GOODREADS: time.sleep(1) lazylibrarian.LAST_GOODREADS = time_now if follow: body = urlencode({'id': authorid, 'format': 'xml'}) headers = {'Content-Type': 'application/x-www-form-urlencoded'} try: response, content = client.request( '%s/author_followings' % 'https://www.goodreads.com', 'POST', body, headers) except Exception as e: logger.error("Exception in client.request: %s %s" % (type(e).__name__, traceback.format_exc())) return False, "Error in client.request: see error log" else: body = urlencode({'format': 'xml'}) headers = {'Content-Type': 'application/x-www-form-urlencoded'} try: response, content = client.request( '%s/author_followings/%s' % ('https://www.goodreads.com', authorid), 'DELETE', body, headers) except Exception as e: logger.error("Exception in client.request: %s %s" % (type(e).__name__, traceback.format_exc())) return False, "Error in client.request: see error log" if follow and response['status'] == '422': return True, 'Already following' if response['status'].startswith('2'): if follow: return True, content.split('<id>')[1].split('</id>')[0] return True, '' return False, 'Failure status: %s' % response['status']
def goodreads_oauth2(self): self.token = oauth.Token(self.request_token['oauth_token'], self.request_token['oauth_token_secret']) access_token_url = '%s/oauth/access_token' % self.url client = oauth.Client(self.consumer, self.token) response, content = client.request(access_token_url, 'POST') if response['status'] != '200': raise Exception('Invalid response: %s' % response['status']) access_token = dict(urlparse.parse_qsl(content)) self.oauth_token = access_token['oauth_token'] self.oauth_secret = access_token['oauth_token_secret'] return {'gr_oauth_token': self.oauth_token, 'gr_oauth_secret': self.oauth_secret}
def setAccessTokenFromCallback(self, token_key, token_secret, verifier): token = oauth.Token(token_key, token_secret) #step 2 depends on callback if verifier: token.set_verifier(verifier) client = oauth.Client(self.consumer, token) resp, content = client.request(OAuthMethod.ACCESS_TOKEN_URL, "POST") if int(resp['status']) != 200: raise IOError("Error setting Access Token") access_token = dict(urlparse.parse_qsl(content)) #created Authorized client using access tokens self.authFromAccessToken(access_token['oauth_token'], access_token['oauth_token_secret'])
def _get_twitter_user_info(self, auth_info, key=None, secret=None): """Returns a dict of twitter user using https://api.twitter.com/1.1/account/verify_credentials.json """ token = oauth1.Token(key=auth_info['oauth_token'], secret=auth_info['oauth_token_secret']) client = self._oauth1_client(token, key, secret) resp, content = client.request( 'https://api.twitter.com/1.1/account/verify_credentials.json') # logging.info(resp) uinfo = json.loads(content) uinfo.setdefault('link', 'http://twitter.com/%s' % uinfo['screen_name']) return uinfo
def get_user_id(self): global consumer, client, token, user_id if not lazylibrarian.CONFIG['GR_API'] or not lazylibrarian.CONFIG['GR_SECRET'] or not \ lazylibrarian.CONFIG['GR_OAUTH_TOKEN'] or not lazylibrarian.CONFIG['GR_OAUTH_SECRET']: logger.warn("Goodreads user id error: Please authorise first") return "" else: try: consumer = oauth.Consumer(key=str(lazylibrarian.CONFIG['GR_API']), secret=str(lazylibrarian.CONFIG['GR_SECRET'])) token = oauth.Token(lazylibrarian.CONFIG['GR_OAUTH_TOKEN'], lazylibrarian.CONFIG['GR_OAUTH_SECRET']) client = oauth.Client(consumer, token) user_id = self.getUserId() return user_id except Exception as e: logger.error("Unable to get UserID: %s %s" % (type(e).__name__, str(e))) return ""
def check_oauth(): consumer = oauth.Consumer(jiraappy.CONSUMER_KEY, jiraappy.CONSUMER_SECRET) accessToken = oauth.Token(jiraappy.JIRA_OAUTH_TOKEN, jiraappy.JIRA_OAUTH_SECRET) client = oauth.Client(consumer, accessToken) client.set_signature_method(SignatureMethod_RSA_SHA1()) data_url = os.path.join(jiraappy.JIRA_BASE_URL, 'rest/api/2/myself') resp, content = client.request(data_url, "GET") if resp['status'] != '200': jiraappy.JIRA_LOGIN_STATUS = None jiraappy.JIRA_LOGIN_USER = None logger.warn("OAuth credentials missing or invalid") else: resp_dict = json.loads(content) jiraappy.JIRA_LOGIN_STATUS = True jiraappy.JIRA_LOGIN_USER = resp_dict['name'] logger.info("JIRA user %s verified login" % resp_dict['name'])
def get_user_id(self): if not self.key or not self.secret or not self.oauth_token or not self.oauth_secret: logger.debug("Goodreads sync error: Please authorise first") return "" else: try: if not self.consumer: self.consumer = oauth.Consumer(key=str(self.key), secret=str(self.secret)) if not self.token: self.token = oauth.Token(self.oauth_token, self.oauth_secret) if not self.client: self.client = oauth.Client(self.consumer, self.token) self.user_id = self.getUserId() return self.user_id except Exception as e: logger.debug("Unable to get UserID: %s" % str(e)) return ""
def callback(self): verifier = self.request.get('oauth_verifier') request_token = self.session.pop('req_token', None) token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(verifier) consumer = oauth.Consumer(config.TWITTER_CONSUMER_KEY, config.TWITTER_CONSUMER_SECRET) client = oauth.Client(consumer, token) resp, content = client.request(config.TWITTER_ACCESS_TOKEN_URL, "POST") access_token = dict(urlparse.parse_qsl(content)) user = users.get_current_user() clients = db.GqlQuery("SELECT * FROM Client", email=user.email()) client = clients.get() client.twitter_actoken_key = access_token['oauth_token'] client.twitter_actoken_secret = access_token['oauth_token_secret'] client.put() self.redirect('/')
def authorize(self, consumer_key, consumer_secret, oauth_token, oauth_token_secret): """ Upgrade OAuth to Access Token Returns: the oauth token the token secret """ consumer = oauth2.Consumer(consumer_key, consumer_secret) token = oauth2.Token(oauth_token, oauth_token_secret) client = oauth2.Client(consumer, token) try: resp, content = client.request(OAUTH_SETTINGS['access_token_url'], "POST") urlparts = content.split("&") oauth_token = urllib.unquote_plus(urlparts[0].split("=")[1]) oauth_token_secret = urllib.unquote_plus(urlparts[1].split("=")[1]) return oauth_token, oauth_token_secret except: return 0
def _oauth1_callback(self, provider, access_token_url): """Third step of OAuth 1.0 dance.""" request_token = self.session.pop('req_token', None) if not request_token: raise InvalidOAuthRequestToken("No request token in user session", provider) verifier = self.request.get('oauth_verifier') if not verifier: raise AuthProviderResponseError("No OAuth verifier was provided", provider) consumer_key, consumer_secret = self._get_consumer_info_for(provider) token = oauth1.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(verifier) client = self._oauth1_client(token, consumer_key, consumer_secret) resp, content = client.request(access_token_url, "POST") logging.info('Content ' + str(content)) logging.info('Response ' + str(resp)) if "<error>" in content: raise AuthProviderResponseError( "The authentication provided returned an error response", provider) _parser = getattr(self, self.TOKEN_RESPONSE_PARSERS[provider]) _fetcher = getattr(self, '_get_%s_user_info' % provider) auth_info = _parser(content) logging.info('Token ' + str(auth_info)) user_data = _fetcher(auth_info, key=consumer_key, secret=consumer_secret) return (user_data, auth_info)
request_token = dict(urlparse.parse_qsl(content)) authorize_link = '%s?oauth_token=%s' % (authorize_url, request_token['oauth_token']) if not authorize_link.startswith('http'): print authorize_link else: print "Use a browser to visit this link and accept your application:" print authorize_link accepted = 'n' while accepted.lower() == 'n': # you need to access the authorize_link via a browser, # and proceed to manually authorize the consumer accepted = raw_input('Have you authorized me? (y/n) ') token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) client = oauth.Client(consumer, token) response, content = client.request(access_token_url, 'POST') if response['status'] != '200': raise Exception('Invalid response: %s' % response['status']) access_token = dict(urlparse.parse_qsl(content)) # this is the token you should save for future use print 'Enter these values in LazyLibrarian config...: ' print 'oauth key: ' + access_token['oauth_token'] print 'oauth secret: ' + access_token['oauth_token_secret']
def authFromAccessToken(self, oauth_token, oauth_token_secret): self.token_key = oauth_token self.token_key_secret = oauth_token_secret token = oauth.Token(oauth_token, oauth_token_secret) self.authorized_client = oauth.Client(self.consumer, token)