def set_twitter(): if 'username' not in session: return redirect(url_for('show_login')) context = {} REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' consumer_key = "HhJrg0xTo3o0CYmZH0472kVJf" consumer_secret = "gNcybIYQvVCs7USfLyqYMATdG0oLapJHtxX28reJ0neFktObYM" signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) oauth_client = oauth.Client(oauth_consumer) resp, content = oauth_client.request(REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': print('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) print(request_token) request_token = { str(key, 'utf-8'): str(value, 'utf-8') for key, value in request_token.items() } print(request_token) print('') print( 'Please visit this Twitter page and retrieve the pincode to be used' ) print('in the next step to obtaining an Authentication Token:') print('') print( str(AUTHORIZATION_URL) + '?oauth_token=' + request_token['oauth_token']) print('') context["twitterAuth"] = str( AUTHORIZATION_URL) + '?oauth_token=' + request_token['oauth_token'] context["tokenSecret"] = request_token['oauth_token_secret'] context["OauthToken"] = request_token['oauth_token'] if request.method == 'POST': if 'username' not in session: return redirect(url_for('show_login')) #get file and text pincode = str(request.form.get("pincode")) s1 = str(request.form.get("OauthToken")) s2 = str(request.form.get("tokenSecret")) token = oauth.Token(s1, s2) token.set_verifier(pincode) oauth_client = oauth.Client(oauth_consumer, token) resp, content = oauth_client.request( ACCESS_TOKEN_URL, method='POST', body='oauth_callback=oob&oauth_verifier=' + pincode) access_token = dict(parse_qsl(content)) access_token = { str(key, 'utf-8'): str(value, 'utf-8') for key, value in access_token.items() } if resp['status'] != '200': print('The request for a Token did not succeed: ' + resp['status']) print(access_token) else: oauth_token = access_token['oauth_token'] oauth_token_secret = access_token['oauth_token_secret'] data = onepost.model.get_db() cur = data.execute('SELECT * \ FROM twitter WHERE username =\'' + session['username'] + '\'').fetchone() if cur: data.execute('UPDATE twitter \ SET accessToken = \'' + oauth_token + '\',accessTokenSecret = \'' + oauth_token_secret + '\' WHERE username =\'' + session['username'] + '\'') else: data.execute( 'INSERT INTO twitter \ VALUES(?, ?, ?) ', [session['username'], oauth_token, oauth_token_secret]) data.commit() return redirect(url_for('show_index')) return flask.render_template("twittersetting.html", **context)
def login_with_token(self, oauth_token, oauth_token_secret): """ When you want to access a user's data using their existing token """ self.token = oauth.Token(oauth_token, oauth_token_secret) self.http = oauth.Client(self.consumer, self.token)
def reader_callback(request): access_token_url = 'https://www.google.com/accounts/OAuthGetAccessToken' consumer = oauth.Consumer(settings.OAUTH_KEY, settings.OAUTH_SECRET) user_token = None if request.user.is_authenticated(): user_token = OAuthToken.objects.filter( user=request.user).order_by('-created_date') if not user_token: user_uuid = request.COOKIES.get('newsblur_reader_uuid') if user_uuid: user_token = OAuthToken.objects.filter( uuid=user_uuid).order_by('-created_date') if not user_token: session = request.session if session.session_key: user_token = OAuthToken.objects.filter( session_id=request.session.session_key).order_by( '-created_date') if not user_token: user_token = OAuthToken.objects.filter( remote_ip=request.META['REMOTE_ADDR']).order_by('-created_date') # logging.info("Found ip user_tokens: %s" % user_tokens) if user_token: user_token = user_token[0] user_token.session_id = request.session.session_key user_token.save() if user_token and request.GET.get('oauth_verifier'): # logging.info("Google Reader request.GET: %s" % request.GET) # Authenticated in Google, so verify and fetch access tokens token = oauth.Token(user_token.request_token, user_token.request_token_secret) token.set_verifier(request.GET['oauth_verifier']) client = oauth.Client(consumer, token) resp, content = client.request(access_token_url, "POST") access_token = dict(urlparse.parse_qsl(content)) user_token.access_token = access_token.get('oauth_token') user_token.access_token_secret = access_token.get('oauth_token_secret') try: user_token.save() except IntegrityError: logging.info( " ***> [%s] Bad token from Google Reader. Re-authenticating." % (request.user, )) return HttpResponseRedirect(reverse('google-reader-authorize')) # Fetch imported feeds on next page load request.session['import_from_google_reader'] = True logging.user( request, "~BB~FW~SBFinishing Google Reader import - %s" % (request.META['REMOTE_ADDR'], )) if request.user.is_authenticated(): return HttpResponseRedirect(reverse('index')) else: logging.info( " ***> [%s] Bad token from Google Reader. Re-authenticating." % (request.user, )) return HttpResponseRedirect(reverse('google-reader-authorize')) return HttpResponseRedirect(reverse('import-signup'))
def twitter_authenticated(request): print request.session['request_token_oauth_token'] # Step 1. Use the request token in the session to build a new client. token = oauth.Token(request.session['request_token_oauth_token'], request.session['request_token_oauth_token_secret']) token.set_verifier(request.GET['oauth_verifier']) client = oauth.Client(consumer, token) # Step 2. Request the authorized access token from Twitter. resp, content = client.request(access_token_url, "GET") if resp['status'] != '200': print content raise Exception("Invalid response from Twitter.") """ This is what you'll get back from Twitter. Note that it includes the user's user_id and screen_name. { 'oauth_token_secret': 'IcJXPiJh8be3BjDWW50uCY31chyhsMHEhqJVsphC3M', 'user_id': '120889797', 'oauth_token': '120889797-H5zNnM3qE0iFoTTpNEHIz3noL9FKzXiOxwtnyVOD', 'screen_name': 'heyismysiteup' } """ access_token = dict(cgi.parse_qsl(content)) us = access_token['screen_name'] # Step 3. Lookup the user or create them if they don't exist. try: user = User.objects.get(username=access_token['screen_name']) except User.DoesNotExist: # When creating the user I just use their [email protected] # for their email and the oauth_token_secret for their password. # These two things will likely never be used. Alternatively, you # can prompt them for their email here. Either way, the password # should never be used. user = User.objects.create_user( access_token['screen_name'], '*****@*****.**' % access_token['screen_name'], access_token['oauth_token_secret']) # Save our permanent token and secret for later. ''' profile = Profile() profile.user = user profile.oauth_token = access_token['oauth_token'] profile.oauth_secret = access_token['oauth_token_secret'] profile.save() ''' # Authenticate the user and log them in using Django's pre-built # functions for these things. user = authenticate(username=access_token['screen_name'], password=access_token['oauth_token_secret']) print '' #print user['statuses.count'] print '' #login(request, user) #home_timeline = oauth_req('https://api.twitter.com/1.1/statuses/home_timeline.json', settings.TWITTER_TOKEN, settings.TWITTER_SECRET) user = oauth_req( 'https://api.twitter.com/1.1/users/show.json?screen_name=' + us, settings.TWITTER_TOKEN, settings.TWITTER_SECRET) #tweets = oauth_req('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name='+us, settings.TWITTER_TOKEN,settings.TWITTER_SECRET) print '' print user print '' obj = json.loads(user) #u=ast.literal_eval(user) #get_all_tweets(obj["id"]) if obj["statuses_count"] < 100: return render( request, 'userRatings/user/illegable.html', { 'msg': 'Thank you for your interest ' + obj["screen_name"] + ', unfortunately, in order to participate in this questionnaire you need to have an active Twitter account with at least 100 tweets. You only have ' + str(obj["statuses_count"]) + ' tweets!' }) elif obj["protected"]: return render( request, 'userRatings/user/illegable.html', { 'msg': 'Thank you for your interest ' + obj["screen_name"] + ', unfortunately, in order to participate in this questionnaire you should have Twitter account set so that your tweets are unprotected and public.' }) elif checkifRatingsExist(obj["id_str"]): return render( request, 'userRatings/user/illegable.html', { 'msg': 'Thank you for your interest ' + obj["screen_name"] + ', you have already submitted your questionnaire, no need to resubmit.' }) else: request.session['usr'] = user # save user if checkifUserExist(obj["id_str"]) == False: insert_user(obj) redirect_url = 'display_petitions' return redirect(redirect_url)
def __init__(self, oauth_key, oauth_secret): self.consumer = oauth.Consumer(oauth_key, oauth_secret) self.oauth_client = oauth.Client(self.consumer) self.token = None
def __init__(self, consumer_key, consumer_secret): super(KuaipanOAuth, self).__init__() self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.consumer = oauth.Consumer(consumer_key, consumer_secret) self.client = oauth.Client(self.consumer)
if len(elems) > 0: book_description = elems[0].text.strip().replace('\n', '') book_description = book_description.replace('\t', '') return book_description if __name__ == "__main__": path = 'YOUR_PATH' key = "YOUR_KEY" secret = "YOUR_SECRET" base_url = 'http://www.goodreads.com' access_token = "YOUR_ACCESS_TOKEN" access_token_secret = "YOUR_ACCESS_TOCKEN_SECRET" consumer = oauth.Consumer(key=key, secret=secret) token = oauth.Token(access_token, access_token_secret) client = oauth.Client(consumer, token) book_features_file = 'books_features.txt' links = [] link_file = 'books_links.txt' with open(path + link_file, 'r') as f_in: next(f_in) for line in f_in: tabs = line.strip().split('\t') link = tabs[0] links.append(link) infos = [] try: counter = 0 for link in links: book_info = book_page_scrape(client, link) time.sleep(1)
def regTwitter(self, token_key=None, token_secret=None, token_pin=None): import oauth2 import autosub.notify.twitter as notifytwitter try: from urlparse import parse_qsl except: from cgi import parse_qsl if not token_key and not token_secret: consumer = oauth2.Consumer(key=notifytwitter.CONSUMER_KEY, secret=notifytwitter.CONSUMER_SECRET) oauth_client = oauth2.Client(consumer) response, content = oauth2.request(notifytwitter.REQUEST_TOKEN_URL, 'GET') if response['status'] != '200': message = "Something went wrong when trying to register Twitter" tmpl = PageTemplate( file="interface/templates/config-settings.tmpl") tmpl.message = message tmpl.displaymessage = "Yes" tmpl.modalheader = "Error" return str(tmpl) else: request_token = dict(parse_qsl(content)) tmpl = PageTemplate( file="interface/templates/config-twitter.tmpl") tmpl.url = notifytwitter.AUTHORIZATION_URL + "?oauth_token=" + request_token[ 'oauth_token'] token_key = request_token['oauth_token'] token_secret = request_token['oauth_token_secret'] tmpl.token_key = token_key tmpl.token_secret = token_secret return str(tmpl) if token_key and token_secret and token_pin: token = oauth2.Token(token_key, token_secret) token.set_verifier(token_pin) consumer = oauth2.Consumer(key=notifytwitter.CONSUMER_KEY, secret=notifytwitter.CONSUMER_SECRET) oauth_client2 = oauth2.Client(consumer, token) response, content = oauth_client2.request( notifytwitter.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % token_pin) access_token = dict(parse_qsl(content)) if response['status'] != '200': message = "Something went wrong when trying to register Twitter" tmpl = PageTemplate( file="interface/templates/config-settings.tmpl") tmpl.message = message tmpl.displaymessage = "Yes" tmpl.modalheader = "Error" return str(tmpl) else: autosub.TWITTERKEY = access_token['oauth_token'] autosub.TWITTERSECRET = access_token['oauth_token_secret'] message = "Twitter registration complete.<br> Remember to save your configuration and test Twitter!" tmpl = PageTemplate( file="interface/templates/config-settings.tmpl") tmpl.message = message tmpl.displaymessage = "Yes" tmpl.modalheader = "Information" return str(tmpl)
if consumer_key is None or consumer_secret is None: print 'You need to edit this script and provide values for the' print 'consumer_key and also consumer_secret.' print '' print 'The values you need come from Twitter - you need to register' print 'as a developer your "application". This is needed only until' print 'Twitter finishes the idea they have of a way to allow open-source' print 'based libraries to have a token that can be used to generate a' print 'one-time use key that will allow the library to make the request' print 'on your behalf.' print '' sys.exit(1) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) oauth_client = oauth.Client(oauth_consumer) print 'Requesting temp token from Twitter' resp, content = oauth_client.request(REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': print 'Invalid respond from Twitter requesting temp token: %s' % resp[ 'status'] else: request_token = dict(parse_qsl(content)) print '' print 'Please visit this Twitter page and retrieve the pincode to be used' print 'in the next step to obtaining an Authentication Token:' print ''
import pprint import urllib.parse #crie uma conta no twitter developers #crie um app para acessar o twitter #crie um arquivo twitter-auth.py com as variaveis contendo seu próprio token #da seguinte forma: (insira suas chaves dentro das aspas) # consumer_key = '' # secret_key = '' # # token_key = '' # token_secret = '' exec(open('twitter-auth.py').read()) consumer = oauth2.Consumer(consumer_key, secret_key) token = oauth2.Token(token_key, token_secret) cliente = oauth2.Client(consumer, token) query = input("Novo tweet: ") #codificar para usar o # como caracter normal query_codificada = urllib.parse.quote(query, safe='') requisicao = cliente.request( 'https://api.twitter.com/1.1/statuses/update.json?status=' + query_codificada, method='POST') #objeto veio em bytes, decodificar decodificar = requisicao[1].decode() #transformar em dicionario objeto = json.loads(decodificar) #imprimir estruturado pprint
def __init__(self, consumer_key, consumer_secret, token_key, token_secret): consumer = oauth2.Consumer(consumer_key, consumer_secret) token = oauth2.Token(token_key, token_secret) self.cliente = oauth2.Client(consumer, token)
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)
def runauth(self, API_KEY, API_SECRET, CONSUMER_KEY, CONSUMER_SECRET): consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET) access_token = oauth.Token(key=API_KEY, secret=API_SECRET) client = oauth.Client(consumer, access_token) return (client)
def set_tumblr(): if 'username' not in session: return redirect(url_for('show_login')) context = {} consumer_key = 'ijkbgt66qLbYkc1DLYUVDf9bEPrsRLPSO0Bbt5VFpjEtIvrT5i' consumer_secret = 'ZbRVAW6PEBKfNWkVTtCE63OO6IDgYxuYHLYTfKtvnyqlLHYddF' request_token_url = 'https://www.tumblr.com/oauth/request_token' access_token_url = 'https://www.tumblr.com/oauth/access_token' authorize_url = 'https://www.tumblr.com/oauth/authorize' consumer = oauth.Consumer(consumer_key, consumer_secret) client = oauth.Client(consumer) #Get request token resp, content = client.request(request_token_url, "POST") if resp['status'] != '200': raise Exception("Invalid response ." + resp['status']) request_token = dict(parse_qsl(content)) request_token = { str(key, 'utf-8'): str(value, 'utf-8') for key, value in request_token.items() } context["TumblrAuth"] = authorize_url + "?oauth_token=" + request_token[ 'oauth_token'] context["OauthToken"] = request_token['oauth_token'] context["tokenSecret"] = request_token['oauth_token_secret'] if request.method == 'POST': #get file and text oauth_verifier = str(request.form.get("verifier")) s1 = str(request.form.get("OauthToken")) s2 = str(request.form.get("tokenSecret")) token = oauth.Token(s1, s2) token.set_verifier(oauth_verifier) client = oauth.Client(consumer, token) resp, content = client.request(access_token_url, "POST") access_token = dict(parse_qsl(content)) access_token = { str(key, 'utf-8'): str(value, 'utf-8') for key, value in access_token.items() } if resp['status'] != '200': print('The request for a Token did not succeed: ' + resp['status']) print(access_token) else: oauth_token = access_token['oauth_token'] oauth_token_secret = access_token['oauth_token_secret'] data = onepost.model.get_db() cur = data.execute('SELECT * \ FROM tumblr WHERE username =\'' + session['username'] + '\'').fetchone() if cur: data.execute('UPDATE tumblr \ SET accessToken = \'' + oauth_token + '\',accessTokenSecret = \'' + oauth_token_secret + '\' WHERE username =\'' + session['username'] + '\'') else: data.execute( 'INSERT INTO tumblr \ VALUES(?, ?, ?) ', [session['username'], oauth_token, oauth_token_secret]) data.commit() return redirect(url_for('show_index')) return flask.render_template("tumblrsetting.html", **context)
def test_access_token_get(self): """Test getting an access token via GET.""" client = oauth.Client(self.consumer, None) resp, content = client.request(self._uri('request_token'), "GET") self.assertEquals(int(resp['status']), 200)
def __init__(self, api_key=None, api_secret=None, oauth_token=None, oauth_token_secret=None, headers=None, client_args=None, callback_url=None, permissions=None): self.api_key = api_key self.api_secret = api_secret self.oauth_token = oauth_token self.oauth_secret = oauth_token_secret self.callback_url = callback_url self.permissions = permissions # Authentication URLs self.request_token_url = 'https://api.linkedin.com/uas/oauth/requestToken' self.access_token_url = 'https://api.linkedin.com/uas/oauth/accessToken' # Authentication page in http://developer.linkedin.com/documents/authentication states that # endpoint is the following not the previous url used. self.authorize_url = 'https://api.linkedin.com/uas/oauth/authenticate' if self.callback_url: self.request_token_url = '%s?oauth_callback=%s' % ( self.request_token_url, self.callback_url) if self.permissions: delimiter = "&" if self.callback_url else "?" if type(self.permissions) is list: permissions = "+".join(self.permissions) else: permissions = self.permissions self.request_token_url = '%s%sscope=%s' % (self.request_token_url, delimiter, permissions) self.api_base = 'http://api.linkedin.com' self.api_version = 'v1' self.api_url = '%s/%s/' % (self.api_base, self.api_version) # If there's headers, set them. If not, lets self.headers = headers if self.headers is None: self.headers = {'User-agent': 'Linkedin %s' % __version__} # ALL requests will be json. Enforcing it here... self.headers.update({ 'x-li-format': 'json', 'Content-Type': 'application/json' }) self.consumer = None self.token = None client_args = client_args or {} # See if they're authenticating for the first or if they already have some tokens. # http://michaelhelmick.com/tokens.jpg if self.api_key is not None and self.api_secret is not None: self.consumer = oauth.Consumer(key=self.api_key, secret=self.api_secret) if self.oauth_token is not None and self.oauth_secret is not None: self.token = oauth.Token(key=oauth_token, secret=oauth_token_secret) if self.consumer is not None and self.token is not None: # Authenticated self.client = oauth.Client(self.consumer, self.token, **client_args) elif self.consumer is not None: # Authenticating self.client = oauth.Client(self.consumer, **client_args) else: # Unauthenticated requests (for LinkedIn calls available to public) self.client = httplib2.Http(**client_args)
def _two_legged(self, method): client = oauth.Client(self.consumer, None) return client.request(self._uri('two_legged'), method, body=urllib.urlencode(self.body))
class TwitterConnector(IConnector): data = None client = None try: root = Util.get_credentials_folder(__file__) json_file = str(root) + "/credentials/twitter.json" data = Util.get_json_file_from_file_path(json_file) except Exception as ex: print('TwitterConnector: File not found %s' % ex) if data is not None: try: consumer_key = data['consumer_key'] consumer_secret = data['consumer_secret'] access_key = data['access_key'] access_secret = data['access_secret'] timeline_endpoint = data['timeline_endpoint'] consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) access_token = oauth.Token(key=access_key, secret=access_secret) client = oauth.Client(consumer, access_token) print('TwitterConnector is ready') except Exception as ex: print('TwitterConnector is no ready %s' % ex) client = None twitterDateFormat = "%a %b %d %H:%M:%S +%f %Y" def fetch_posts(self) -> List[SocialPost]: social_posts = [] # type: List[SocialPost] if self.client is None: return social_posts response, data = self.client.request(self.timeline_endpoint) twitter_posts = json.loads(data) for twitter_post in twitter_posts: if twitter_post == "errors": print(twitter_post) continue social_post = SocialPost() social_post.text = twitter_post["full_text"] social_post.externalId = twitter_post["id"] entities = twitter_post["entities"] if "media" in entities: media = entities["media"] media_urls = [] if media is not None: for medium in media: media_urls.append(medium["media_url_https"]) social_post.mediaURLs = media_urls created_date = datetime.strptime(twitter_post["created_at"], self.twitterDateFormat) social_post.created = Util.convert_date_to_UTC_time_stamp( created_date) social_post.validTo = Util.convert_date_to_UTC_time_stamp( created_date + timedelta(weeks=3)) social_post.validFrom = Util.convert_date_to_UTC_time_stamp( created_date) social_post.source = "twitter" social_posts.append(social_post) return social_posts
def conexao(self, consumer_key, consumer_secret, token_key, token_secret): # Atributos do objeto self.consumer = oauth2.Consumer(consumer_key, consumer_secret) self.token = oauth2.Token(token_key, token_secret) self.cliente = oauth2.Client(self.consumer, self.token)
def handleLoginRequest(cls, request): assert oauth is not None redirect_uri = get_redirect_uri(request) response_type = "code" social = request.GET['social'] state = social + "," + request.REQUEST.get('next', '/') if social == 'google': consumer_key = liboauth.conf.CONSUMER_KEY_GOOGLE.get() token_request_uri = liboauth.conf.REQUEST_TOKEN_URL_GOOGLE.get() scope = "https://www.googleapis.com/auth/userinfo.email" access_type = "offline" approval_prompt = "force" url = "{token_request_uri}?response_type={response_type}&client_id={client_id}&redirect_uri={redirect_uri}&scope={scope}&state={state}&access_type={access_type}&approval_prompt={approval_prompt}".format( token_request_uri=token_request_uri, response_type=response_type, client_id=consumer_key, redirect_uri=redirect_uri, scope=scope, state=state, access_type=access_type, approval_prompt=approval_prompt) #facebook elif social == 'facebook': consumer_key = liboauth.conf.CONSUMER_KEY_FACEBOOK.get() token_request_uri = liboauth.conf.REQUEST_TOKEN_URL_FACEBOOK.get() scope = "email" grant_type = "client_credentials" url = "{token_request_uri}?client_id={client_id}&redirect_uri={redirect_uri}&grant_type={grant_type}&scope={scope}&state={state}".format( token_request_uri=token_request_uri, client_id=consumer_key, redirect_uri=redirect_uri, grant_type=grant_type, scope=scope, state=state) #linkedin elif social == 'linkedin': consumer_key = liboauth.conf.CONSUMER_KEY_LINKEDIN.get() token_request_uri = liboauth.conf.REQUEST_TOKEN_URL_LINKEDIN.get() scope = "r_emailaddress" url = "{token_request_uri}?response_type={response_type}&client_id={client_id}&scope={scope}&state={state}&redirect_uri={redirect_uri}".format( token_request_uri=token_request_uri, response_type=response_type, client_id=consumer_key, scope=scope, state=state, redirect_uri=redirect_uri) #twitter else: consumer_key = liboauth.conf.CONSUMER_KEY_TWITTER.get() consumer_secret = liboauth.conf.CONSUMER_SECRET_TWITTER.get() token_request_uri = liboauth.conf.REQUEST_TOKEN_URL_TWITTER.get() token_authentication_uri = liboauth.conf.AUTHORIZE_URL_TWITTER.get( ) consumer = oauth.Consumer(consumer_key, consumer_secret) client = oauth.Client(consumer) resp, content = client.request( token_request_uri, "POST", body=urllib.urlencode({'oauth_callback': redirect_uri})) if resp['status'] != '200': raise Exception( _("Invalid response from OAuth provider: %s") % resp) request.session['request_token'] = dict(cgi.parse_qsl(content)) url = "{token_authentication_uri}?oauth_token={oauth_token}".format( token_authentication_uri=token_authentication_uri, oauth_token=request.session['request_token']['oauth_token']) return url
#from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer #from socket import * #import SimpleHTTPServer #import SocketServer import json #import datetime from time import gmtime, strftime host = '127.0.0.1' dbFile = "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/UserRatings/db.sqlite3" twitter_handle = 'change' # It's probably a good idea to put your consumer's OAuth token and # OAuth secret into your project's settings. consumer = oauth.Consumer(settings.CONSUMER_KEY, settings.CONSUMER_SECRET) client = oauth.Client(consumer) auth = tweepy.OAuthHandler(settings.CONSUMER_KEY, settings.CONSUMER_SECRET) auth.set_access_token(settings.TWITTER_TOKEN, settings.TWITTER_SECRET) api = tweepy.API(auth, retry_count=3, retry_delay=60, retry_errors=set([401, 404, 500, 503]), wait_on_rate_limit=True, wait_on_rate_limit_notify=True) request_token_url = 'https://api.twitter.com/oauth/request_token' access_token_url = 'https://api.twitter.com/oauth/access_token' # This is the slightly different URL used to authenticate/authorize. authenticate_url = 'https://api.twitter.com/oauth/authenticate'
def handleAuthenticationRequest(cls, request): assert oauth is not None if 'oauth_verifier' in request.GET: social = 'twitter' consumer_key = liboauth.conf.CONSUMER_KEY_TWITTER.get() consumer_secret = liboauth.conf.CONSUMER_SECRET_TWITTER.get() access_token_uri = liboauth.conf.ACCESS_TOKEN_URL_TWITTER.get() consumer = oauth.Consumer(consumer_key, consumer_secret) token = oauth.Token( request.session['request_token']['oauth_token'], request.session['request_token']['oauth_token_secret']) client = oauth.Client(consumer, token) oauth_verifier = request.GET['oauth_verifier'] resp, content = client.request(access_token_uri + oauth_verifier, "GET") if resp['status'] != '200': raise Exception( _("Invalid response from OAuth provider: %s") % resp) access_token = dict(cgi.parse_qsl(content)) access_token['screen_name'] = ''.join( [x for x in access_token['screen_name'] if x.isalnum()]) else: parser = httplib2.Http() login_failed_url = '/' if 'error' in request.GET or 'code' not in request.GET: return "" redirect_uri = get_redirect_uri(request) code = request.GET['code'] grant_type = 'authorization_code' state_split = request.GET['state'].split(',') nexturl = state_split[1] if len(state_split) > 1 else '/' social = state_split[0] if social == 'google': consumer_key = liboauth.conf.CONSUMER_KEY_GOOGLE.get() consumer_secret = liboauth.conf.CONSUMER_SECRET_GOOGLE.get() access_token_uri = liboauth.conf.ACCESS_TOKEN_URL_GOOGLE.get() authentication_token_uri = liboauth.conf.AUTHORIZE_URL_GOOGLE.get( ) elif social == 'facebook': consumer_key = liboauth.conf.CONSUMER_KEY_FACEBOOK.get() consumer_secret = liboauth.conf.CONSUMER_SECRET_FACEBOOK.get() access_token_uri = liboauth.conf.ACCESS_TOKEN_URL_FACEBOOK.get( ) authentication_token_uri = liboauth.conf.AUTHORIZE_URL_FACEBOOK.get( ) elif social == 'linkedin': consumer_key = liboauth.conf.CONSUMER_KEY_LINKEDIN.get() consumer_secret = liboauth.conf.CONSUMER_SECRET_LINKEDIN.get() access_token_uri = liboauth.conf.ACCESS_TOKEN_URL_LINKEDIN.get( ) authentication_token_uri = liboauth.conf.AUTHORIZE_URL_LINKEDIN.get( ) params = urllib.urlencode({ 'code': code, 'redirect_uri': redirect_uri, 'client_id': consumer_key, 'client_secret': consumer_secret, 'grant_type': grant_type }) headers = {'content-type': 'application/x-www-form-urlencoded'} resp, cont = parser.request(access_token_uri, method='POST', body=params, headers=headers) if resp['status'] != '200': raise Exception( _("Invalid response from OAuth provider: %s") % resp) #google if social == 'google': access_tok = (json.loads(cont))['access_token'] auth_token_uri = authentication_token_uri + access_tok resp, content = parser.request(auth_token_uri, "GET") if resp['status'] != '200': raise Exception( _("Invalid response from OAuth provider: %s") % resp) username = (json.loads(content))["email"] access_token = dict(screen_name=map_username(username), oauth_token_secret=access_tok) whitelisted_domains = liboauth.conf.WHITELISTED_DOMAINS_GOOGLE.get( ) if whitelisted_domains: if username.split('@')[1] not in whitelisted_domains: access_token = "" #facebook elif social == 'facebook': access_tok = (dict(cgi.parse_qsl(cont)))['access_token'] auth_token_uri = authentication_token_uri + access_tok resp, content = parser.request(auth_token_uri, "GET") if resp['status'] != '200': raise Exception( _("Invalid response from OAuth provider: %s") % resp) username = (json.loads(content))["email"] access_token = dict(screen_name=map_username(username), oauth_token_secret=access_tok) #linkedin elif social == 'linkedin': access_tok = (json.loads(cont))['access_token'] auth_token_uri = authentication_token_uri + access_tok resp, content = parser.request(auth_token_uri, "GET") if resp['status'] != '200': raise Exception( _("Invalid response from OAuth provider: %s") % resp) username = (json.loads(content))['emailAddress'] access_token = dict(screen_name=map_username(username), oauth_token_secret=access_tok) return access_token, nexturl
def requestToken(self): client = oauth.Client(self.consumer) resp, content = client.request(BASE_URL + "/oauth/request_token", "GET", headers={"oauth_callback": "oob"}) return self.__splitToken(content)
def authenticate_to_twitter(): client = oauth.Client(consumer, access_token)
def __init__(self, oauthkey, oauthsec): self.consumer = oauth.Consumer(oauthkey, oauthsec) self.client = oauth.Client(self.consumer) self.token = None self.http = None
def authTwitter(): global client consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET) access_token = oauth.Token(key=ACCESS_KEY, secret=ACCESS_SECRET) client = oauth.Client(consumer, access_token)
def api_client(consumer_key, consumer_secret, access_token, access_token_secret): consumer = oauth2.Consumer(key=consumer_key, secret=consumer_secret) token = oauth2.Token(key=access_token, secret=access_token_secret) client = oauth2.Client(consumer, token) return client
def make_client(self, token=None): """Creates a new `oauth2` Client object with the token attached. Usually you don't have to do that but use the :meth:`request` method instead. """ return oauth2.Client(self._consumer, self.get_request_token(token))
""" import json import oauth2 # Application Settings consumer_key = "rNP6vrSOh2DEvEgzKkfYNLehZ" consumer_secret = "13CjYe8t2elQaGvZaWjtzsKBCo9Ui4J3Xwjp7owOLvcJkW3Dgw" # Access Tokens access_token = "965961232262971392-ciDm7oTBbilKMsNqL9ZL79fPtJyHVeW" access_token_secret = "rZp96hJafF08Mbr0283oWdBRBp2hfsL9lAvCZNzMwCl8W" consumer = oauth2.Consumer(key=consumer_key, secret=consumer_secret) access_token = oauth2.Token(key=access_token, secret=access_token_secret) client = oauth2.Client(consumer, access_token) show_status_format = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=botmark36&count=" def view_tweets(): while True: try: num_tweets = int( input( "How many tweets do you want to view from your profile? ")) except ValueError: print("That was not a valid number. Try again") continue else: break
def get_client(self, oauth_token=None, oauth_verifier=None): token = oauth.Token(oauth_token['oauth_token'], oauth_token['oauth_token_secret']) if oauth_verifier: token.set_verifier(oauth_verifier) return oauth.Client(self.consumer, token=token)