def handle_google_login(self, data): c = Client(token_endpoint='https://accounts.google.com/o/oauth2/token', resource_endpoint='https://www.googleapis.com/oauth2/v1', client_id=config['google.client_id'], client_secret=config['google.client_secret'], token_transport=transport_headers) c.request_token(code=data['code'], redirect_uri='http://localhost/login/google') self.dump_client(c) data = c.request('/userinfo') self.dump_response(data) if hasattr(c, 'refresh_token'): rc = Client(token_endpoint=c.token_endpoint, client_id=c.client_id, client_secret=c.client_secret, resource_endpoint=c.resource_endpoint, token_transport='headers') rc.request_token(grant_type='refresh_token', refresh_token=c.refresh_token) self.wfile.write( '<p>post refresh token:</p>'.encode(ENCODING_UTF8)) self.dump_client(rc)
def handle_facebook_login(self, data): c = Client( token_endpoint='https://graph.facebook.com/oauth/access_token', resource_endpoint='https://graph.facebook.com', client_id=config['facebook.client_id'], client_secret=config['facebook.client_secret']) c.request_token(code=data['code'], redirect_uri='http://localhost/login/facebook') self.dump_client(c) d = c.request('/me') self.dump_response(d) try: d = c.request('/me/feed', data=bytes( urlencode( {'message': 'test post from py-sanction'}), 'ascii')) self.wfile.write( 'I posted a message to your wall (in sandbox mode, nobody ' 'else will see it)'.encode(ENCODING_UTF8)) except: self.wfile.write(b'Unable to post to your wall')
def handle_foursquare_login(self, data): def token_transport(url, access_token, data=None, method=None): parts = urlsplit(url) query = dict(parse_qsl(parts.query)) query.update({'oauth_token': access_token}) url = urlunsplit((parts.scheme, parts.netloc, parts.path, urlencode(query), parts.fragment)) try: req = Request(url, data=data, method=method) except TypeError: req = Request(url, data=data) req.get_method = lambda: method return req c = Client(token_endpoint='https://foursquare.com/oauth2/access_token', resource_endpoint='https://api.foursquare.com/v2', client_id=config['foursquare.client_id'], client_secret=config['foursquare.client_secret'], token_transport=token_transport) c.request_token(code=data['code'], redirect_uri='http://localhost/login/foursquare') self.dump_client(c) d = c.request('/users/24700343') self.dump_response(d)
def get_token(grant_type): client = Client(token_endpoint=get_config()["42.token_url"], resource_endpoint=get_config()["42.endpoint"], client_id=get_config()["42.client_id"], client_secret=get_config()["42.client_secret"]) client.request_token(grant_type=grant_type) return client
def __init__(self, credentials, target_user): """ Open an API handle for the explorer. :param credentials: Credentials to use in this session. :param target_user: str for user to explore in this session. """ if not type(credentials) is Credentials: raise DAExplorerException( "Argument 'credentials' must be type Credentials.") if not type(target_user) is str: raise DAExplorerException( "Argument 'target_user' must be type str.") # Define all class members self.oauth = None self.user = target_user # @todo move away from sanction oauth2 library, make this (and callers) async self.oauth = Client( auth_endpoint="https://www.deviantart.com/oauth2/authorize", token_endpoint="https://www.deviantart.com/oauth2/token", resource_endpoint="https://www.deviantart.com/api/v1/oauth2", client_id=credentials.client_id, client_secret=credentials.client_secret) try: self.oauth.request_token(grant_type="client_credentials") except HTTPError as e: if e.code == 401: raise DAExplorerException("Unauthorized. Check credentials. " + str(e)) else: raise DAExplorerException("Error authorizing: " + str(e)) self._check_creds() self._check_user()
def get_token(grant_type): client = Client(token_endpoint="https://api.intra.42.fr/oauth/token", resource_endpoint="https://api.intra.42.fr", client_id=os.environ["INTRA_CLIENT_ID"], client_secret=os.environ["INTRA_SECRET"]) client.request_token(grant_type=grant_type) return client
def handle_stackexchange(self, data): self.send_response(302) c = Client(auth_endpoint='https://stackexchange.com/oauth', client_id=config['stackexchange.client_id']) self.send_header( 'Location', c.auth_uri(redirect_uri='http://localhost/login/stackexchange')) self.end_headers()
def handle_instagram(self, data): self.send_response(302) c = Client(auth_endpoint='https://api.instagram.com/oauth/authorize/', client_id=config['instagram.client_id']) self.send_header( 'Location', c.auth_uri(redirect_uri='http://localhost/login/instagram')) self.end_headers()
def handle_github(self, data): self.send_response(302) c = Client(auth_endpoint='https://github.com/login/oauth/authorize', client_id=config['github.client_id']) self.send_header( 'Location', c.auth_uri(redirect_uri='http://localhost/login/github')) self.end_headers()
def handle_foursquare(self, data): self.send_response(302) c = Client(auth_endpoint='https://foursquare.com/oauth2/authenticate', client_id=config['foursquare.client_id']) self.send_header( 'Location', c.auth_uri(redirect_uri='http://localhost/login/foursquare')) self.end_headers()
def make_refresh_post(refresh_token): client = Client( token_endpoint='https://accounts.google.com/o/oauth2/token', resource_endpoint='https://www.googleapis.com/oauth2/v1', client_id=CLIENT_ID, client_secret=CLIENT_SECRET) params = {"grant_type": "refresh_token"} client.request_token(refresh_token=refresh_token, **params) return client.access_token, client.expires_in
def _make_code_post(code, redirect_uri): client = Client( token_endpoint='https://accounts.google.com/o/oauth2/token', resource_endpoint='https://www.googleapis.com/oauth2/v1', client_id=CLIENT_ID, client_secret=CLIENT_SECRET) params = {"redirect_uri": redirect_uri} client.request_token(code=code, **params) return client.access_token, client.refresh_token, client.expires_in
def handle_deviantart(self, data): self.send_response(302) c = Client( auth_endpoint='https://www.deviantart.com/oauth2/draft15/authorize', client_id=config['deviantart.client_id']) self.send_header( 'Location', c.auth_uri(redirect_uri=config['deviantart.redirect_uri'])) self.end_headers()
def handle_facebook(self, data): self.send_response(302) c = Client(auth_endpoint='https://www.facebook.com/dialog/oauth', client_id=config['facebook.client_id']) self.send_header( 'Location', c.auth_uri(scope=config['facebook.scope'], redirect_uri='http://localhost/login/facebook')) self.end_headers()
def handle_google(self, data): self.send_response(302) c = Client(auth_endpoint='https://accounts.google.com/o/oauth2/auth', client_id=config['google.client_id']) self.send_header( 'Location', c.auth_uri(scope=config['google.scope'], access_type='offline', redirect_uri='http://localhost/login/google')) self.end_headers()
def handle_jawbone(self, data): self.send_response(302) c = Client(auth_endpoint='https://jawbone.com/auth/oauth2/auth', client_id='nEXyCKO3F3s') self.send_header( 'Location', c.auth_uri( scope= 'basic_read extended_read location_read friends_read mood_read mood_write move_read sleep_read sleep_write generic_event_read generic_event_write', redirect_uri='http://localhost/login/jawbone')) self.end_headers()
def handle_instagram_login(self, data): c = Client( token_endpoint='https://api.instagram.com/oauth/access_token', resource_endpoint='https://api.instagram.com/v1', client_id=config['instagram.client_id'], client_secret=config['instagram.client_secret']) c.request_token(code=data['code'], redirect_uri='http://localhost/login/instagram') self.dump_client(c) data = c.request('/users/self')['data'] self.dump_response(data)
def handle_github_login(self, data): c = Client( token_endpoint='https://github.com/login/oauth/access_token', resource_endpoint='https://api.github.com', client_id=config['github.client_id'], client_secret=config['github.client_secret']) c.request_token(code=data['code'], redirect_uri='http://localhost/login/github') self.dump_client(c) data = c.request('/user') self.dump_response(data)
def handle_deviantart_login(self, data): c = Client( token_endpoint='https://www.deviantart.com/oauth2/draft15/token', resource_endpoint='https://www.deviantart.com/api/draft15', client_id=config['deviantart.client_id'], client_secret=config['deviantart.client_secret']) c.request_token(code=data['code'], redirect_uri=config['deviantart.redirect_uri']) self.dump_client(c) data = c.request('/user/whoami') self.dump_response(data)
def handle_jawbone_login(self, data): c = Client(token_endpoint='https://jawbone.com/auth/oauth2/token', client_id='nEXyCKO3F3s', client_secret='c9a66fc619ccb0e7c2c4e90e59200dfba8aea5de', token_transport=transport_headers) c.request_token(grant_type='authorization_code', code=data['code']) #createInfo(c.access_token,c.token_expires) createDb = sqlite3.connect('key.db') updateInfo(c.access_token, c.token_expires) createDb.commit() #queryCurs.execute('UPDATE * FROM userinfo') self.dump_client(c) return
def handle_jawbone_login(self, data): c = Client(token_endpoint='https://jawbone.com/auth/oauth2/token', client_id='nEXyCKO3F3s', client_secret='c9a66fc619ccb0e7c2c4e90e59200dfba8aea5de', token_transport=transport_headers) c.request_token(grant_type='authorization_code', code=data['code']) #createInfo(c.access_token,c.token_expires) query = DatabaseManager('key.db') #maybe check if table doesn't exist and create it in DBMR__init__) query.updateInfo("UPDATE userinfo SET key = ?, expires = ?", c.access_token, c.token_expires) del query self.dump_client(c) return
def handle_stackexchange_login(self, data): c = Client( token_endpoint='https://stackexchange.com/oauth/access_token', resource_endpoint='https://api.stackexchange.com/2.0', client_id=config['stackexchange.client_id'], client_secret=config['stackexchange.client_secret']) c.request_token(code=data['code'], parser=lambda data: dict(parse_qsl(data)), redirect_uri='http://localhost/login/stackexchange') self.dump_client(c) data = c.request('/me?{}'.format( urlencode({ 'site': 'stackoverflow.com', 'key': config['stackexchange.key'] })), parser=lambda c: loads( self._gunzip(c).decode('utf-8')))['items'][0] self.dump_response(data)
# However, if there is a .config file, use this instead of os.environ if os.path.exists('.config'): config = toml.load(".config") client_id = config['TDA']['client_id'] client_secret = config['TDA']['refresh_token'] redirect_uri = config['TDA']['redirect_uri'] token_url = 'https://api.tdameritrade.com/v1/oauth2/token' # token url - issues access tokens base_url = 'https://api.tdameritrade.com/v1/marketdata' # Instantiate a client to request an access token # this requires a previously issued refresh token # stored as an environment variable, e.g. client_secret = os.environ.get('autoTraderToken') c = Client(token_endpoint=token_url, resource_endpoint=base_url, client_id=client_id, \ client_secret=client_secret) # Request an access token # Requests are throttled to 120 requests / minute or 1 request every 0.5 sec # Excessive token requests will be discouraged by TD Ameritrade - i.e. rate limiting by IP address, etc. c.request_token(grant_type='refresh_token', refresh_token=client_secret, redirect_uri=redirect_uri) # Price History API Request # ref for stocks: https://www.barchart.com/stocks/most-active/price-volume-leaders symbol = args.symbol #data1 = api_pricehistory(symbol) today = dt.now() marketStart = dt.combine(date.today(), datetime.time(0, 2)) marketEnd = dt.combine(date.today(), datetime.time(0, 3)) if today > marketStart and today < marketEnd:
def __init__(self, client_id, client_secret): self.client = Client( token_endpoint="https://api.yelp.com/oauth2/token", resource_endpoint="https://api.yelp.com/v3", client_id=client_id, client_secret=client_secret)
from sanction import Client # The URL for access token requests token_request_url = "https://oauth.brightcove.com/v3/access_token" # Client ID and secret # Your Client ID from your client credential client_id = "762df048-1d42-468c-9d18-f023d524f94f" # Your Client Secret from your client credential client_secret = "s728iZUVU3YbBSJC4to_9UhYgVrxIVvIQL3OkypMSOudWg02lZk3tNDbPESUAiup0uJV_rBinbyQ70Vh7FSWLA" # The base URL of the resource server # The URL below is for the example resource server resource_base = "https://data.brightcove.com/" # Create the OAuth2 client object client = Client(token_endpoint=token_request_url, resource_endpoint=resource_base, client_id=client_id, client_secret=client_secret) # Request the access token into the client object client.request_token(grant_type='client_credentials') # Now make the resource request # The path below is for the example resource server print client.request( '/analytics-api/videocloud/account/12345/report?dimensions=video,player')
from sanction import Client # instantiating a client to process OAuth2 response client = Client(token_endpoint="http://karl.novareto.de:8085/token", resource_endpoint="http://karl.novareto.de:8085/resource", client_id="novareto", client_secret="test") client.request_token(grant_type='client_credentials') data = client.request('/') print data
def setUp(self): self.client = Client(auth_endpoint=AUTH_ENDPOINT, token_endpoint=TOKEN_ENDPOINT, resource_endpoint=RESOURCE_ENDPOINT, client_id=CLIENT_ID)
def authenticate(force=False): """ Returns an oauth token that can be passed to the server for identification. """ if not force: try: cur_time = int(time.time()) access_token, expires_at, refresh_token = get_storage() if cur_time < expires_at - 10: return access_token access_token, expires_in = make_refresh_post(refresh_token) if not access_token and expires_in: raise AuthenticationException( "Authentication failed and returned an empty token.") update_storage(access_token, expires_in, refresh_token) return access_token except IOError as _: print('Performing authentication') except AuthenticationException as e: raise e # Let the main script handle this error except Exception as _: print('Performing authentication') check_ssl() print("Please enter your bCourses email.") email = input("bCourses email: ") host_name = REDIRECT_HOST try: port_number = pick_free_port(port=REDIRECT_PORT) except AuthenticationException as e: # Could not bind to REDIRECT_HOST:0, try localhost instead host_name = 'localhost' port_number = pick_free_port(host_name, 0) redirect_uri = "http://{0}:{1}/".format(host_name, port_number) log.info("Authentication server running on {}".format(redirect_uri)) c = Client(auth_endpoint='https://accounts.google.com/o/oauth2/auth', client_id=CLIENT_ID) url = c.auth_uri(scope="profile email", access_type='offline', name='ok-server', redirect_uri=redirect_uri, login_hint=email) webbrowser.open_new(url) done = False access_token = None refresh_token = None expires_in = None auth_error = None class CodeHandler(http.server.BaseHTTPRequestHandler): def send_failure(self, message): self.send_response(400) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(bytes(failure_page(message), "utf-8")) def do_GET(self): """Respond to the GET request made by the OAuth""" nonlocal access_token, refresh_token, expires_in, auth_error, done path = urlparse(self.path) qs = parse_qs(path.query) try: code = qs['code'][0] code_response = _make_code_post(code, redirect_uri) access_token, refresh_token, expires_in = code_response except KeyError: message = qs.get('error', 'Unknown') log.warning("No auth code provided {}".format(message)) auth_error = message done = True self.send_failure(message) return except Exception as e: # TODO : Catch just SSL errors log.warning("Could not obtain token", exc_info=True) auth_error = e.message done = True self.send_failure(e.message) return done = True self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() actual_email = email try: email_resp = get_student_email(access_token) if email_resp: actual_email = email_resp except Exception as e: # TODO : Catch just SSL errors log.warning("Could not get email from token", exc_info=True) reponse = success_page(SERVER, actual_email, access_token) self.wfile.write(bytes(reponse, "utf-8")) def log_message(self, format, *args): return server_address = (host_name, port_number) try: httpd = http.server.HTTPServer(server_address, CodeHandler) httpd.handle_request() except OSError as e: log.warning("HTTP Server Err {}".format(server_address), exc_info=True) raise if not auth_error: update_storage(access_token, expires_in, refresh_token) return access_token else: print("Authentication error: {}".format(auth_error)) return None
# get a Client ID and Secret from # https://login.rally1.rallydev.com/accounts/index.html#/clients CLIENT_ID = os.environ.get('CLIENT_ID', '') CLIENT_SECRET = os.environ.get('CLIENT_SECRET', '') # Server URL must match the one specified when creating the client SERVER_URL = os.environ.get('SERVER_URL', '') + "/oauth-redirect" # We will use these to make WSAPI calls RALLY_WSAPI_URL = "https://rally1.rallydev.com" RALLY_USER_URL = RALLY_WSAPI_URL + "/slm/webservice/v2.x/user" RALLY_STORIES_URL = RALLY_WSAPI_URL + "/slm/webservice/v2.x/hierarchicalrequirement" try: c = Client(auth_endpoint = "https://rally1.rallydev.com/login/oauth2/auth", token_endpoint = "https://rally1.rallydev.com/login/oauth2/token", client_id = CLIENT_ID, client_secret = CLIENT_SECRET) except Exception, e: print "Failed to init the OAuth2 Client " + str(e) exit(0) urls = ( '/', 'display_stories', '/login', 'login', '/logout', 'logout', '/oauth-redirect', 'redirect' ) app = web.application(urls, globals())
from sanction import Client # import urllib.parse with open('genius_credentials.yml', 'r') as stream: try: config = yaml.load(stream) except yaml.YAMLError as exc: print(exc) query = 'Rick Ross' querystring = requests.utils.requote_uri('http://api.genius.com/search/' + query) c = Client( token_endpoint="https://api.genius.com/oauth/authorize", resource_endpoint=querystring, # redirect_uri="https://anthonywbaker.com", client_id=config['client_id'], client_secret=config['client_secret']) scope = 'me' c.auth_uri(scope) # querystring='https://api.genius.com/songs/378195' r = requests.get(querystring, params={'access_token': config['client_access_token']}, headers={ 'user-agent': '', 'Authorization': 'Bearer ' + config['client_access_token'] })