def get(self): if not (request_token and request_token_secret): raise HTTPError(log_message='OAuth callback, no request token') verifier = self.get_query_argument('oauth_verifier') access_token_response = zotero_oauth_service().get_raw_access_token( request_token, request_token_secret, data={'oauth_verifier': verifier} ) access_token_response.raise_for_status() access_info = parse_utf8_qsl(access_token_response.content) if 'oauth_token' not in access_info: raise HTTPError(log_message="Missing oauth_token. Response content: %r" % access_token_response.content) # We have successfully authenticated. cm = ConfigManager() cm.update('cite2c', {'zotero': { 'user_id': access_info['userID'], 'username': access_info['username'], 'access_token': access_info['oauth_token'], }}) self.log.info("OAuth completed for Zotero user %s", access_info['userID']) with open(oauth_success) as f: self.finish(f.read())
def twt_auth(user, org): # raise error when configurations are not provided. if not settings.TWT_ENABLED: raise AuthError( 'You must provide a "twitter_api_key" and "twitter_api_secret" in ' 'your NewsLynx configuration to enable Twitter integration. ' 'See http://dev.twitter.com for details on how to create ' 'an application on Twitter.') # get callback url oauth_callback = url_for('auth_twitter.twt_callback', _external=True) params = {'oauth_callback': oauth_callback} # make initial authentication request r = twt_oauth.get_raw_request_token(params=params) # parse out request tokens into the session data = parse_utf8_qsl(r.content) session['twitter_oauth'] = ( data['oauth_token'], data['oauth_token_secret']) session['org_id'] = org.id session['redirect_uri'] = request.args.get('redirect_uri') # redirect the user to the auth url. auth_url = twt_oauth.get_authorize_url(data['oauth_token'], **params) return redirect(auth_url)
def connect(self, access_code): self.access_token_time = time.time() verification_code = access_code print verification_code raw_access = self.oauth.get_raw_access_token( self.request_token, self.request_token_secret, params={"oauth_verifier": verification_code}) print "raw_access" print raw_access.content parsed_access_token = parse_utf8_qsl(raw_access.content) self.saved_token = {} self.saved_token["access_token"] = parsed_access_token["oauth_token"] self.saved_token["access_token_secret"] = \ parsed_access_token["oauth_token_secret"] self.saved_token["session_handle"] = \ parsed_access_token["oauth_session_handle"] if tokenfile is not None: try: f = open(tokenfile, "w") pickle.dump(self.saved_token, f) f.close() except IOError: pass self.session = self.oauth.get_session( (self.saved_token["access_token"], self.saved_token["access_token_secret"]))
def get_raw_request_token(self, method="GET", oauth_callback="oob", **kwargs): """Gets a response from the request token endpoint. Returns the entire parsed response, without trying to pull out the token and secret. Use this if your endpoint doesn't use the usual names for 'oauth_token' and 'oauth_token_secret'. :param method: A string representation of the HTTP method to be used. :param \*\*kwargs: Optional arguments. Same as Requests. """ # ensure we've set the request_token_url if self.request_token_url is None: raise TypeError("request_token_url must not be None") auth_session = self._construct_session(header_auth=self.header_auth, default_oauth_callback=oauth_callback) response = auth_session.request(method, self.request_token_url, **kwargs) # TODO: use the following instead # if not response.ok: # return response.content response.raise_for_status() return parse_utf8_qsl(response.content)
def get(self): if not (request_token and request_token_secret): raise HTTPError(log_message='OAuth callback, no request token') verifier = self.get_query_argument('oauth_verifier') access_token_response = zotero_oauth_service().get_raw_access_token( request_token, request_token_secret, data={'oauth_verifier': verifier}) access_token_response.raise_for_status() access_info = parse_utf8_qsl(access_token_response.content) if 'oauth_token' not in access_info: raise HTTPError( log_message="Missing oauth_token. Response content: %r" % access_token_response.content) # We have successfully authenticated. cm = ConfigManager() cm.update( 'cite2c', { 'zotero': { 'user_id': access_info['userID'], 'username': access_info['username'], 'access_token': access_info['oauth_token'], } }) self.log.info("OAuth completed for Zotero user %s", access_info['userID']) with open(oauth_success) as f: self.finish(f.read())
def twt_auth(user, org): # raise error when configurations are not provided. if not settings.TWT_ENABLED: raise AuthError( 'You must provide a "twitter_api_key" and "twitter_api_secret" in ' 'your NewsLynx configuration to enable Twitter integration. ' 'See http://dev.twitter.com for details on how to create ' 'an application on Twitter.') # get callback url oauth_callback = url_for('auth_twitter.twt_callback', _external=True) params = {'oauth_callback': oauth_callback} # make initial authentication request r = twt_oauth.get_raw_request_token(params=params) # parse out request tokens into the session data = parse_utf8_qsl(r.content) session['twitter_oauth'] = (data['oauth_token'], data['oauth_token_secret']) session['org_id'] = org.id session['redirect_uri'] = request.args.get('redirect_uri') # redirect the user to the auth url. auth_url = twt_oauth.get_authorize_url(data['oauth_token'], **params) return redirect(auth_url)
def __init__(self, consumer_key, consumer_secret, access_token=None, access_token_secret=None, session_handle=None): self.saved_token = None if all(x is not None for x in (access_token, access_token_secret, session_handle)): self.saved_token = { "access_token": access_token, "access_token_secret": access_token_secret, "session_handle": session_handle } self.oauth = rauth.OAuth1Service( consumer_key=consumer_key, consumer_secret=consumer_secret, name="yahoo", request_token_url="https://api.login.yahoo.com/oauth/v2/get_request_token", access_token_url="https://api.login.yahoo.com/oauth/v2/get_token", authorize_url="https://api.login.yahoo.com/oauth/v2/request_auth", base_url="http://fantasysports.yahooapis.com/") self.last_request = time.time() if (self.saved_token is not None and self.saved_token["access_token"] and self.saved_token["access_token_secret"] and self.saved_token["session_handle"]): # refresh access token, it may not have expired yet but refresh anyway self.refresh_access_token() else: request_token, request_token_secret = \ self.oauth.get_request_token(params={"oauth_callback": "oob"}) authorize_url = self.oauth.get_authorize_url(request_token) print("Sign in here: " + str(authorize_url)) verification_code = input("Enter code: ") self.access_token_time = time.time() raw_access = self.oauth.get_raw_access_token( request_token, request_token_secret, params={"oauth_verifier": verification_code}) parsed_access_token = parse_utf8_qsl(raw_access.content) self.saved_token = { "access_token": parsed_access_token["oauth_token"], "access_token_secret": parsed_access_token["oauth_token_secret"], "session_handle": parsed_access_token["oauth_session_handle"] } print(self.saved_token) self.session = self.oauth.get_session( (self.saved_token["access_token"], self.saved_token["access_token_secret"]) )
def __init__(self, consumer_key, consumer_secret, access_token=None, access_token_secret=None, session_handle=None): self.saved_token = None if all(x is not None for x in (access_token, access_token_secret, session_handle)): self.saved_token = { "access_token": access_token, "access_token_secret": access_token_secret, "session_handle": session_handle } self.oauth = rauth.OAuth1Service( consumer_key=consumer_key, consumer_secret=consumer_secret, name="yahoo", request_token_url="https://api.login.yahoo.com/oauth/v2/get_request_token", access_token_url="https://api.login.yahoo.com/oauth/v2/get_token", authorize_url="https://api.login.yahoo.com/oauth/v2/request_auth", base_url="http://fantasysports.yahooapis.com/") self.last_request = time.time() if (self.saved_token is not None and self.saved_token["access_token"] and self.saved_token["access_token_secret"] and self.saved_token["session_handle"]): # refresh access token, it may not have expired yet but refresh anyway self.refresh_access_token() else: request_token, request_token_secret = \ self.oauth.get_request_token(params={"oauth_callback": "oob"}) authorize_url = self.oauth.get_authorize_url(request_token) print "Sign in here: " + str(authorize_url) verification_code = raw_input("Enter code: ") self.access_token_time = time.time() raw_access = self.oauth.get_raw_access_token( request_token, request_token_secret, params={"oauth_verifier": verification_code}) parsed_access_token = parse_utf8_qsl(raw_access.content) self.saved_token = { "access_token": parsed_access_token["oauth_token"], "access_token_secret": parsed_access_token["oauth_token_secret"], "session_handle": parsed_access_token["oauth_session_handle"] } print self.saved_token self.session = self.oauth.get_session( (self.saved_token["access_token"], self.saved_token["access_token_secret"]) )
def __init__(self, credentials_file): """ Authenticate with the Yahoo Fantasy Sports API. Parameters: credentials_file: path to a json file """ # load credentials self.credentials_file = open(credentials_file) self.credentials = json.load(self.credentials_file) self.credentials_file.close() # create oauth object self.oauth = OAuth1Service( consumer_key=self.credentials['consumer_key'], consumer_secret=self.credentials['consumer_secret'], name="yahoo", request_token_url= "https://api.login.yahoo.com/oauth/v2/get_request_token", access_token_url="https://api.login.yahoo.com/oauth/v2/get_token", authorize_url="https://api.login.yahoo.com/oauth/v2/request_auth", base_url="http://fantasysports.yahooapis.com/") # leg 1 request_token, request_token_secret = self.oauth.get_request_token( params={"oauth_callback": "oob"}) # leg 2 authorize_url = self.oauth.get_authorize_url(request_token) webbrowser.open(authorize_url) verify = input('Enter code: ') # leg 3 raw_access = self.oauth.get_raw_access_token( request_token, request_token_secret, params={"oauth_verifier": verify}) self.parsed_access_token = parse_utf8_qsl(raw_access.content) access_token = (self.parsed_access_token['oauth_token'], self.parsed_access_token['oauth_token_secret']) # log time self.start_time = time.time() self.end_time = self.start_time + 3600 # store tokens self.credentials['access_token'] = self.parsed_access_token[ 'oauth_token'] self.credentials['access_token_secret'] = self.parsed_access_token[ 'oauth_token_secret'] self.tokens = (self.credentials['access_token'], self.credentials['access_token_secret']) # start session self.session = self.oauth.get_session(self.tokens)
def login(): oauth_callback = url_for('authorized', _external=True) params = {'oauth_callback': oauth_callback} r = twitter.get_raw_request_token(params=params) data = parse_utf8_qsl(r.content) session['twitter_oauth'] = (data['oauth_token'], data['oauth_token_secret']) return redirect(twitter.get_authorize_url(data['oauth_token'], **params))
def fb_extend_oauth_token(temp_access_token): url = _graph_url + "oauth/access_token" params = { "grant_type": "fb_exchange_token", "client_id": settings.FACEBOOK_APP_ID, "client_secret": settings.FACEBOOK_APP_SECRET, "fb_exchange_token": temp_access_token, } r = requests.get(url=url, params=params) token = parse_utf8_qsl(r.content) token["expires"] = dates.parse_ts(dates.now(ts=True) + int(token["expires"])).isoformat() return token
def login(): oauth_callback = url_for('authorized', _external=True) params = {'oauth_callback': oauth_callback} r = twitter.get_raw_request_token(params=params) if r.status_code is not 200: flash('There was an issue while trying to connect to Twitter. Ping @rsinha') return redirect(url_for('index')) data = parse_utf8_qsl(r.content) session['twitter_oauth'] = (data['oauth_token'], data['oauth_token_secret']) return redirect(twitter.get_authorize_url(data['oauth_token'], **params))
def fb_extend_oauth_token(temp_access_token): url = _graph_url + "oauth/access_token" params = { 'grant_type': 'fb_exchange_token', 'client_id': settings.FACEBOOK_APP_ID, 'client_secret': settings.FACEBOOK_APP_SECRET, 'fb_exchange_token': temp_access_token } r = requests.get(url=url, params=params) token = parse_utf8_qsl(r.content) token['expires'] = dates.parse_ts( dates.now(ts=True) + int(token['expires'])).isoformat() return token
def content(self): # NOTE: it would be nice to use content-type here however we can't # trust services to be honest with this header so for now the # following is more robust and less prone to fragility when the header # isn't set properly if isinstance(self.response.content, basestring): try: content = json.loads(self.response.content) except ValueError: content = parse_utf8_qsl(self.response.content) else: content = self.response.content return content
def handler(self,): """* get request token if OAuth1 * Get user authorization * Get access token """ if self.oauth_version == 'oauth1': request_token, request_token_secret = self.oauth.get_request_token(params={'oauth_callback': self.callback_uri}) logger.debug("REQUEST_TOKEN = {0}\n REQUEST_TOKEN_SECRET = {1}\n".format(request_token, request_token_secret)) authorize_url = self.oauth.get_authorize_url(request_token) else: authorize_url = self.oauth.get_authorize_url(redirect_uri=self.callback_uri, response_type='code') logger.debug("AUTHORIZATION URL : {0}".format(authorize_url)) if self.browser_callback: # Open authorize_url webbrowser.open(authorize_url) self.verifier = input("Enter verifier : ") else: self.verifier = input("AUTHORIZATION URL : {0}\nEnter verifier : ".format(authorize_url)) self.token_time = time.time() credentials = {'token_time': self.token_time} if self.oauth_version == 'oauth1': raw_access = self.oauth.get_raw_access_token(request_token, request_token_secret, params={"oauth_verifier": self.verifier}) parsed_access = parse_utf8_qsl(raw_access.content) self.access_token = parsed_access['oauth_token'] self.access_token_secret = parsed_access['oauth_token_secret'] self.session_handle = parsed_access['oauth_session_handle'] self.guid = parsed_access.get('xoauth_yahoo_guid', None) # Updating credentials credentials.update({ 'access_token': self.access_token, 'access_token_secret': self.access_token_secret, 'session_handle': self.session_handle, 'guid': self.guid }) else: # Building headers headers = self.generate_oauth2_headers() # Getting access token raw_access = self.oauth.get_raw_access_token(data={"code": self.verifier, 'redirect_uri': self.callback_uri, 'grant_type': 'authorization_code'}, headers=headers) # parsed_access = parse_utf8_qsl(raw_access.content.decode('utf-8')) credentials.update(self.oauth2_access_parser(raw_access)) return credentials
def get_access_token(self): raw_token = self.srvc.get_raw_access_token( self.creds['request_token'], self.creds['request_token_secret'], data={'oauth_verifier': self.creds['verifier']}) token_data = parse_utf8_qsl(raw_token.content) access_token = token_data['oauth_token'] access_token_secret = token_data['oauth_token_secret'] session_handle = token_data['oauth_session_handle'] self.update_credentials(access_token=access_token, access_token_secret=access_token_secret, session_handle=session_handle) session = self.srvc.get_session( (self.creds['access_token'], self.creds['access_token_secret']))
def login(img_id): if img_id not in IMAGES: flash("不正なIDです") return redirect(url_for('index')) session["img_id"] = img_id oauth_callback = url_for('authorized', _external=True) params = {'oauth_callback': oauth_callback} r = twitter.get_raw_request_token(params=params) data = parse_utf8_qsl(r.content) print(data) session['twitter_oauth'] = (data['oauth_token'], data['oauth_token_secret']) return redirect(twitter.get_authorize_url(data['oauth_token'], **params))
def login(): redir = request.args.get('continue', None) urlparams = urllib.urlencode({'continue': redir}) oauth_callback = 'http://twitlink.blackmad.com/twitter/authorized?%s' % urlparams params = {'oauth_callback': oauth_callback} r = twitterAuth.get_raw_request_token(params=params) data = parse_utf8_qsl(r.content) session['twitter_oauth'] = (data['oauth_token'], data['oauth_token_secret']) return redirect(twitterAuth.get_authorize_url(data['oauth_token'], **params))
def store_credentials(email): fieldnames = ['user_email', 'access_token', 'access_token_secret', 'session_handle'] writer = csv.DictWriter(open('data/user_auth_info.csv', 'a'), fieldnames = fieldnames) yahoo = OAuth1Service( consumer_key=OAUTH_CONSUMER_KEY, consumer_secret=OAUTH_SHARED_SECRET, name='yahoo', access_token_url=GET_TOKEN_URL, authorize_url=AUTHORIZATION_URL, request_token_url=REQUEST_TOKEN_URL, base_url= BASE_URL) request_token, request_token_secret = yahoo.get_request_token(data = { 'oauth_callback': CALLBACK_URL }) auth_url = yahoo.get_authorize_url(request_token) print 'Visit this URL in your browser: ' + auth_url pin = raw_input('Enter PIN from browser: ') raw_access = yahoo.get_raw_access_token(request_token, request_token_secret, params={"oauth_verifier": pin}) parsed_access_token = parse_utf8_qsl(raw_access.content) access_token = parsed_access_token["oauth_token"] access_token_secret = parsed_access_token["oauth_token_secret"] session_handle = parsed_access_token["oauth_session_handle"] writer.writerow({'user_email': email, 'access_token':access_token, 'access_token_secret':access_token_secret, 'session_handle':session_handle})
def login(): redir = request.args.get('continue', None) urlparams = urllib.urlencode({'continue': redir}) oauth_callback = 'http://twitlink.blackmad.com/twitter/authorized?%s' % urlparams params = {'oauth_callback': oauth_callback} r = twitterAuth.get_raw_request_token(params=params) data = parse_utf8_qsl(r.content) session['twitter_oauth'] = (data['oauth_token'], data['oauth_token_secret']) return redirect( twitterAuth.get_authorize_url(data['oauth_token'], **params))
def handler(self,): """* get request token if OAuth1 * Get user authorization * Get access token """ if self.oauth_version == 'oauth1': request_token, request_token_secret = self.oauth.get_request_token(params={'oauth_callback': self.callback_uri}) logger.debug("REQUEST_TOKEN = {0}\n REQUEST_TOKEN_SECRET = {1}\n".format(request_token, request_token_secret)) authorize_url = self.oauth.get_authorize_url(request_token) else: authorize_url = self.oauth.get_authorize_url(client_secret=self.consumer_secret, redirect_uri=self.callback_uri, response_type='code') logger.debug("AUTHORISATION URL : {0}".format(authorize_url)) # Open authorize_url webbrowser.open(authorize_url) self.verifier = input("Enter verifier : ") self.token_time = time.time() credentials = {'token_time': self.token_time} if self.oauth_version == 'oauth1': raw_access = self.oauth.get_raw_access_token(request_token, request_token_secret, params={"oauth_verifier": self.verifier}) parsed_access = parse_utf8_qsl(raw_access.content) self.access_token = parsed_access['oauth_token'] self.access_token_secret = parsed_access['oauth_token_secret'] self.session_handle = parsed_access['oauth_session_handle'] self.guid = parsed_access['xoauth_yahoo_guid'] # Updating credentials credentials.update({ 'access_token': self.access_token, 'access_token_secret': self.access_token_secret, 'session_handle': self.session_handle, 'guid': self.guid }) else: # Building headers headers = self.generate_oauth2_headers() # Getting access token raw_access = self.oauth.get_raw_access_token(data={"code": self.verifier, 'redirect_uri': self.callback_uri,'grant_type':'authorization_code'}, headers=headers) #parsed_access = parse_utf8_qsl(raw_access.content.decode('utf-8')) credentials.update(self.oauth2_access_parser(raw_access)) return credentials
def get(self): twitter_auth_loader = OAuth1Service( name='twitter', consumer_key=current_app.config['CONSUMER_KEY'], consumer_secret=current_app.config['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/' ) oauth_callback = url_for('twittercallback', _external=True) params = {'oauth_callback': oauth_callback} auth_url = twitter_auth_loader.get_raw_request_token(params=params) data = parse_utf8_qsl(auth_url.content) session['twitter_oauth'] = (data['oauth_token'], data['oauth_token_secret']) return redirect(twitter_auth_loader.get_authorize_url(data['oauth_token'], **params))
def get_access_token(self): raw_token = self.srvc.get_raw_access_token( self.creds['request_token'], self.creds['request_token_secret'], data={'oauth_verifier': self.creds['verifier']} ) token_data = parse_utf8_qsl(raw_token.content) access_token = token_data['oauth_token'] access_token_secret = token_data['oauth_token_secret'] session_handle = token_data['oauth_session_handle'] self.update_credentials( access_token=access_token, access_token_secret=access_token_secret, session_handle=session_handle ) session = self.srvc.get_session( (self.creds['access_token'],self.creds['access_token_secret']) )
def auth_cb(): if not current_user.is_authenticated: flash('Alert: Cannot complete authentication. User is not logged in.') else: verifier = request.args.get('oauth_verifier') text = 'Call back comes here, verifier is {}'.format(verifier) access_token_response = zoteroAuth.get_raw_access_token( session['request_token'], session['request_token_secret'], data={'oauth_verifier': verifier}) access_info = parse_utf8_qsl(access_token_response.content) current_user.zotero_userid = access_info['userID'] current_user.zotero_username = access_info['username'] current_user.zoter_api = access_info['oauth_token_secret'] db.session.commit() flash( 'Success! We successfullly received API key from Zoter user {}'.format( current_user.zotero_username)) return redirect(url_for('bookshelf'))
def login(): flask.session.pop('group_id', None) flask.session.pop('inv_id', None) if not 'grp_id' in request.args: oauth_callback = url_for('twits.authorized', _external=True) if 'grp_id' in request.args: grp_id = request.args.get('grp_id') inv_id = request.args.get('inv_id') e = Invitations.query.filter(Invitations.id == inv_id).first() usr = user_datastore.get_user(e.email) # invited user who is already registered.so he has already a group.so he will be added to the invited group if usr and e.accepted == False: g = Group.query.filter(Group.id == grp_id).first() g.users.append(usr) e.accepted = True db.session.commit() # person who has invited also will join to the group of the person who got invitation g_who_got_invitation=Group.query.filter(Group.owner_id == usr.id).first() # user instance who has invited usr_who_has_invited = User.query.filter(User.id == g.owner_id).first() g_who_got_invitation.users.append(usr_who_has_invited) db.session.commit() flask.ext.security.utils.login_user(usr) flash('you are already registerd in this program','info') flash('you are added to the group' +grp_id,'info') flash('Logged in as ' + e.email,'info') return redirect(url_for('frontend.index')) else: oauth_callback = 'http://staging.ivivelabs.com:3104/twits/authorized?grp_id={0}&inv_id={1}'.format(grp_id,inv_id) params = {'oauth_callback': oauth_callback, 'scope':'user:email'} r = twitter.get_raw_request_token(params=params) data = parse_utf8_qsl(r.content) session['twitter_oauth'] = (data['oauth_token'], data['oauth_token_secret']) return redirect(twitter.get_authorize_url(data['oauth_token'], **params))
def do_POST(self): global service global request_token global request_token_secret if self.path == "/submit": length = int(self.headers['Content-Length']) post_data = urlparse.parse_qs(self.rfile.read(length).decode('utf-8')) if "key" not in post_data or "secret" not in post_data: self.send_response(301) self.send_header("Location", "/error") self.end_headers() return service = OAuth1Service( name="Twitter", consumer_key=post_data["key"][0], consumer_secret=post_data["secret"][0], 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/' ) params = { "oauth_callback" : "http://%s:%i/token" % (HOSTNAME, LISTEN_PORT) } token_response = service.get_raw_request_token(params=params) token_data = utils.parse_utf8_qsl(token_response.content) try: request_token = token_data["oauth_token"] request_token_secret = token_data["oauth_token_secret"] next_url = service.get_authorize_url(request_token) except KeyError: next_url = "/error" self.send_response(301) self.send_header("Location", next_url) self.end_headers()
def __init__(self, keyfile, tokenfile=None): self.saved_token = None # read in consumer key and consumer secret key from file f = open(keyfile, "r") keys = f.read().split() f.close() if len(keys) != 2: raise RuntimeError('Incorrect number of keys found in ' + keyfile) consumer_key, consumer_secret = keys self.oauth = OAuth1Service( consumer_key = consumer_key, consumer_secret = consumer_secret, name = "yahoo", request_token_url = "https://api.login.yahoo.com/oauth/v2/get_request_token", access_token_url = "https://api.login.yahoo.com/oauth/v2/get_token", authorize_url = "https://api.login.yahoo.com/oauth/v2/request_auth", base_url = "http://fantasysports.yahooapis.com/fantasy/v2/") self.last_request = time.time() if tokenfile is not None: try: f = open(tokenfile, "r") self.saved_token = pickle.load(f) f.close() except IOError: self.saved_token = None if (self.saved_token is not None and self.saved_token["access_token"] and self.saved_token["access_token_secret"] and self.saved_token["session_handle"]): # refresh access token, it may not have expired yet but refresh # anyway self.refresh_access_token() else: request_token, request_token_secret = \ self.oauth.get_request_token(params={"oauth_callback": "oob"}) authorize_url = self.oauth.get_authorize_url(request_token) print "Sign in here: " + str(authorize_url) verification_code = raw_input("Enter code: ") self.access_token_time = time.time() raw_access = self.oauth.get_raw_access_token( request_token, request_token_secret, params={"oauth_verifier": verification_code}) parsed_access_token = parse_utf8_qsl(raw_access.content) self.saved_token = {} self.saved_token["access_token"] = parsed_access_token["oauth_token"] self.saved_token["access_token_secret"] = \ parsed_access_token["oauth_token_secret"] self.saved_token["session_handle"] = \ parsed_access_token["oauth_session_handle"] if tokenfile is not None: try: f = open(tokenfile, "w") pickle.dump(self.saved_token, f) f.close() except IOError: pass self.session = self.oauth.get_session( (self.saved_token["access_token"], self.saved_token["access_token_secret"]))
#authorize_url = oauth.get_authorize_url(request_token) #webbrowser.open(authorize_url) #verify = input('Enter code: ') #Enter code: k2pm8y # Leg 3 # Obtain access tokens. Tokens expire after 3600 seconds (60 minutes) # so we'd like to save the time these tokens were generated. This time can be # used later to check against and refresh the tokens if necessary. # Next, we'll also save the tokens in our credentials dictionary and create a tuple that is used in the creation of a session raw_access = oauth.get_raw_access_token(request_token, request_token_secret, params={"oauth_verifier": verify}) parsed_access_token = parse_utf8_qsl(raw_access.content) access_token = (parsed_access_token['oauth_token'], parsed_access_token['oauth_token_secret']) start_time = time.time() end_time = start_time + 3600 credentials['access_token'] = parsed_access_token['oauth_token'] credentials['access_token_secret'] = parsed_access_token['oauth_token_secret'] tokens = (credentials['access_token'], credentials['access_token_secret']) #Start a session s = oauth.get_session(tokens) #Send a query
def client_oauth_twitter(request): if authenticated_userid(request): return HTTPSeeOther(location=request.route_url('access.cl.home')) cfg = request.registry.settings loc = get_localizer(request) req_session = request.session min_pwd_len = int(cfg.get('netprofile.client.registration.min_password_length', 8)) auth_provider = 'twitter' email = request.matchdict['email'] redirect_uri = request.route_url('access.cl.oauthtwitter', email=email) reg_params = { 'email':email, 'username':None, 'password':None, 'givenname':None, 'familyname':None, } TWITTER_APP_ID = cfg.get('netprofile.client.TWITTER_APP_ID', False) TWITTER_APP_SECRET = cfg.get('netprofile.client.TWITTER_APP_SECRET', False) twitter = OAuth1Service( consumer_key=TWITTER_APP_ID, consumer_secret=TWITTER_APP_SECRET, name='twitter', authorize_url='https://api.twitter.com/oauth/authorize', access_token_url='https://api.twitter.com/oauth/access_token', request_token_url='https://api.twitter.com/oauth/request_token', base_url='https://api.twitter.com/1.1/') if TWITTER_APP_ID and TWITTER_APP_SECRET: auth_token = request.GET.get('oauth_token', False) auth_verifier = request.GET.get('oauth_verifier', False) if not auth_token and not auth_verifier: params = { 'oauth_callback': redirect_uri, } authorize_url = twitter.get_raw_request_token(params=params) data = parse_utf8_qsl(authorize_url.content) # should pass callback_url # and get something like http://netprofile.ru/?oauth_token=1jMq4YD5cKEgRrOjoRae3xdfHJaoQRPf&oauth_verifier=bpOPZ1CYVUGtNs8nTFihwBv6KWhJzV1C # http://stackoverflow.com/questions/17512572/rauth-flask-how-to-login-via-twitter #it works req_session['twitter_oauth'] = (data['oauth_token'], data['oauth_token_secret']) return HTTPSeeOther(twitter.get_authorize_url(data['oauth_token'], **params)) else: request_token, request_token_secret = req_session.pop('twitter_oauth') creds = { 'request_token': request_token, 'request_token_secret': request_token_secret } params = {'oauth_verifier': auth_verifier} sess = twitter.get_auth_session(params=params, **creds) res_json = sess.get('account/verify_credentials.json', params={'format':'json'}).json() print(res_json) #twitter does not provide email with rest api, we hawe to ask the user explicitly reg_params['username'] = res_json['screen_name'].replace(' ','').lower() reg_params['givenname'] = res_json['name'].split()[0] reg_params['familyname'] = res_json['name'].split()[-1] passwordhash = hashlib.sha224((auth_provider + reg_params['email'] + reg_params['username'] + str(res_json['id'])).encode('utf8')).hexdigest() reg_params['password'] = passwordhash[::3][:8] headers = client_oauth_register(request, reg_params) if headers: return HTTPSeeOther(location=request.route_url('access.cl.home'), headers=headers) return HTTPSeeOther(location=request.route_url('access.cl.login'))
def client_oauth_twitter(request): if authenticated_userid(request): return HTTPSeeOther(location=request.route_url('main')) cfg = request.registry.settings loc = get_localizer(request) req_session = request.session min_pwd_len = 8 auth_provider = 'twitter' email = request.matchdict['email'] redirect_uri = request.route_url('oauthtwitter', email=email) reg_params = { 'email':email, 'username':None, 'password':None, 'givenname':None, 'familyname':None, } TWITTER_APP_ID = cfg.get('TWITTER_APP_ID', False) TWITTER_APP_SECRET = cfg.get('TWITTER_APP_SECRET', False) twitter = OAuth1Service( consumer_key=TWITTER_APP_ID, consumer_secret=TWITTER_APP_SECRET, name='twitter', authorize_url='https://api.twitter.com/oauth/authorize', access_token_url='https://api.twitter.com/oauth/access_token', request_token_url='https://api.twitter.com/oauth/request_token', base_url='https://api.twitter.com/1.1/') if TWITTER_APP_ID and TWITTER_APP_SECRET: auth_token = request.GET.get('oauth_token', False) auth_verifier = request.GET.get('oauth_verifier', False) if not auth_token and not auth_verifier: params = { 'oauth_callback': redirect_uri, } authorize_url = twitter.get_raw_request_token(params=params) data = parse_utf8_qsl(authorize_url.content) req_session['twitter_oauth'] = (data['oauth_token'], data['oauth_token_secret']) return HTTPSeeOther(twitter.get_authorize_url(data['oauth_token'], **params)) else: request_token, request_token_secret = req_session.pop('twitter_oauth') creds = { 'request_token': request_token, 'request_token_secret': request_token_secret } params = {'oauth_verifier': auth_verifier} sess = twitter.get_auth_session(params=params, **creds) res_json = sess.get('account/verify_credentials.json', params={'format':'json'}).json() reg_params['username'] = res_json['screen_name'].replace(' ','').lower() reg_params['givenname'] = res_json['name'].split()[0] reg_params['familyname'] = res_json['name'].split()[-1] passwordhash = hashlib.sha224((auth_provider + reg_params['email'] + reg_params['username'] + str(res_json['id'])).encode('utf8')).hexdigest() reg_params['password'] = passwordhash[::3][:8] headers = client_oauth_register(request, reg_params) if headers: return HTTPSeeOther(location=request.route_url('main'), headers=headers) return HTTPSeeOther(location=request.route_url('login'))
def test_parse_utf8_qsl(self): d = parse_utf8_qsl('fü=bar&rauth=über') self.assertEqual(d, {u'rauth': u'\xfcber', u'f\xfc': u'bar'})
def test_both_kv_unicode(self): d = parse_utf8_qsl(u'fü=bar&rauth=über') self.assertEqual(d, {u'rauth': u'\xfcber', u'f\xfc': u'bar'})
def __init__(self, consumer_key, consumer_secret, **kwargs): """ consumer_key : client key consumer_secret : client secret access_token : access token access_token_secret : access token secret from_file : file containing the credentials """ if kwargs.get('from_file'): self.from_file = kwargs.get('from_file') json_data = self.json_get_data(self.from_file) vars(self).update(json_data) else: self.consumer_key = consumer_key self.consumer_secret = consumer_secret vars(self).update(kwargs) # Init OAuth self.oauth = OAuth1Service( consumer_key = self.consumer_key, consumer_secret = self.consumer_secret, name = "yahoo", request_token_url = REQUEST_TOKEN_URL, access_token_url = ACCESS_TOKEN_URL, authorize_url = AUTHORIZE_TOKEN_URL, base_url = BASE_URL ) if vars(self).get('access_token') and vars(self).get('access_token_secret') and vars(self).get('session_handle'): if not self.token_is_valid(): self.session = self.refresh_token() else: self.session = self.oauth.get_session((self.access_token, self.access_token_secret)) else: # Fetching request token/token_secret request_token, request_token_secret = self.oauth.get_request_token(params={'oauth_callback': CALLBACK_URI}) logging.debug("REQUEST_TOKEN = {0}\n REQUEST_TOKEN_SECRET = {1}\n".format(request_token, request_token_secret)) #authorize_url = self.oauth.get_authorize_url(request_token) authorize_url = AUTHORIZE_TOKEN_URL+request_token logging.debug(authorize_url) webbrowser.open(authorize_url) verifier = raw_input("Enter verifier : ") logging.debug("VERIFIER = {0}".format(verifier)) self.token_time = time.time() raw_acess = self.oauth.get_raw_access_token(request_token, request_token_secret, params={"oauth_verifier": verifier}) parsed_acess = parse_utf8_qsl(raw_acess.content) self.access_token = parsed_acess['oauth_token'] self.access_token_secret = parsed_acess['oauth_token_secret'] self.session_handle = parsed_acess['oauth_session_handle'] self.session = self.oauth.get_session((self.access_token, self.access_token_secret)) json_data.update({ 'access_token' : self.access_token, 'access_token_secret' : self.access_token_secret, 'session_handle' : self.session_handle, 'token_time' : self.token_time }) self.json_wirte_data(json_data, self.from_file)
def __init__(self, keyfile, tokenfile=None): self.saved_token = None # read in consumer key and consumer secret key from file f = open(keyfile, "r") keys = f.read().split() f.close() if len(keys) != 2: raise RuntimeError('Incorrect number of keys found in ' + keyfile) consumer_key, consumer_secret = keys self.oauth = OAuth1Service( consumer_key = consumer_key, consumer_secret = consumer_secret, name = "yahoo", request_token_url = "https://api.login.yahoo.com/oauth/v2/get_request_token", access_token_url = "https://api.login.yahoo.com/oauth/v2/get_token", authorize_url = "https://api.login.yahoo.com/oauth/v2/request_auth", base_url = "http://fantasysports.yahooapis.com/") self.last_request = time.time() if tokenfile is not None: try: f = open(tokenfile, "r") self.saved_token = pickle.load(f) f.close() except IOError: self.saved_token = None if (self.saved_token is not None and self.saved_token["access_token"] and self.saved_token["access_token_secret"] and self.saved_token["session_handle"]): # refresh access token, it may not have expired yet but refresh # anyway self.refresh_access_token() else: request_token, request_token_secret = \ self.oauth.get_request_token(params={"oauth_callback": "oob"}) authorize_url = self.oauth.get_authorize_url(request_token) print "Sign in here: " + str(authorize_url) webbrowser.open(str(authorize_url)) verification_code = raw_input("Enter code: ") self.access_token_time = time.time() raw_access = self.oauth.get_raw_access_token( request_token, request_token_secret, params={"oauth_verifier": verification_code}) parsed_access_token = parse_utf8_qsl(raw_access.content) self.saved_token = {} self.saved_token["access_token"] = parsed_access_token["oauth_token"] self.saved_token["access_token_secret"] = \ parsed_access_token["oauth_token_secret"] self.saved_token["session_handle"] = \ parsed_access_token["oauth_session_handle"] if tokenfile is not None: try: f = open(tokenfile, "w") pickle.dump(self.saved_token, f) f.close() except IOError: pass self.session = self.oauth.get_session( (self.saved_token["access_token"], self.saved_token["access_token_secret"]))