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 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_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_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_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_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 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_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 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) update_storage(access_token, expires_in, refresh_token) return access_token except IOError as _: print('Performing authentication') except Exception as _: print('Performing authentication') print("Please enter your CalNet ID.") calnet_id = input("CalNet ID: ") 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='*****@*****.**' % (calnet_id)) webbrowser.open_new(url) host_name = REDIRECT_HOST port_number = REDIRECT_PORT done = False access_token = None refresh_token = None expires_in = None class CodeHandler(http.server.BaseHTTPRequestHandler): def do_GET(self): """Respond to the GET request made by the OAuth""" path = urlparse(self.path) nonlocal access_token, refresh_token, expires_in, done qs = parse_qs(path.query) code = qs['code'][0] access_token, refresh_token, expires_in = _make_code_post(code) done = True self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(bytes(SUCCESS_HTML, "utf-8")) server_address = (host_name, port_number) httpd = http.server.HTTPServer(server_address, CodeHandler) httpd.handle_request() update_storage(access_token, expires_in, refresh_token) return access_token
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_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 openid_authenticate(provider): """return openid authenticate url for client to authenticate :param provider: OAuth2 provider. """ oauth_kwargs = current_app.config.get(str.format('OAUTH_{0}', provider.upper())) if oauth_kwargs is None: abort(404); c = Client(**oauth_kwargs) next_url = get_url(request.args.get('next')) or get_url(request.form.get('next')) or '' return redirect(c.auth_uri(redirect_uri=str.format('{0}/openid/{1}/login?next={2}', current_app.config['KINORSI_SERVER_HOST'], provider, next_url), scope='get_user_info,add_t', scope_delim=','))
def _redirect(request, provider): p = settings.SANCTION_PROVIDERS[provider] c = SanctionClient(auth_endpoint=p['auth_endpoint'], client_id=p['client_id']) kwargs = p.get('auth_params', {}) kwargs['redirect_uri'] = p['redirect_uri'] if 'scope' in p: kwargs['scope'] = p['scope'] response = redirect(c.auth_uri(**kwargs)) # inject the state query param if getattr(settings, 'SANCTION_USE_CSRF', True): CsrfViewMiddleware().process_view(request, response, [], {}) url = list(urlparse(response['location'])) urlp = dict(parse_qsl(url[4])) urlp.update({'state': csrf.get_token(request)}) url[4] = urlencode(urlp) response['location'] = urlunparse(url) return response
def _redirect(request, provider): p = settings.SANCTION_PROVIDERS[provider] c = SanctionClient(auth_endpoint=p['auth_endpoint'], client_id=p['client_id'], token_endpoint=p['token_endpoint'], client_secret=p['client_secret'], resource_endpoint=p['resource_endpoint']) kwargs = p.get('auth_params', {}) response = redirect( c.auth_uri(redirect_uri=p['redirect_uri'], scope=p['scope'] if 'scope' in p else None, **kwargs)) # inject the state query param if getattr(settings, 'SANCTION_USE_CSRF', True): CsrfViewMiddleware().process_view(request, response, [], {}) url = list(urlparse(response['location'])) urlp = dict(parse_qsl(url[4])) urlp.update({'state': csrf.get_token(request)}) url[4] = urlencode(urlp) response['location'] = urlunparse(url) return response
class TestClient(TestCase): def setUp(self): self.client = Client(auth_endpoint=AUTH_ENDPOINT, token_endpoint=TOKEN_ENDPOINT, resource_endpoint=RESOURCE_ENDPOINT, client_id=CLIENT_ID) def test_init(self): map(lambda c: self.assertEqual(*c), ( (self.client.auth_endpoint, AUTH_ENDPOINT), (self.client.token_endpoint, TOKEN_ENDPOINT), (self.client.resource_endpoint, RESOURCE_ENDPOINT), (self.client.client_id, CLIENT_ID), )) def test_auth_uri(self): parsed = urlparse(self.client.auth_uri(redirect_uri=REDIRECT_URI)) qs = dict(parse_qsl(parsed.query)) map(lambda c: self.assertEqual(*c), ((qs['redirect_uri'], REDIRECT_URI), (qs['response_type'], 'code'), (qs['client_id'], CLIENT_ID))) parsed = urlparse(self.client.auth_uri(scope=SCOPE)) qs = dict(parse_qsl(parsed.query)) self.assertEqual(qs['scope'], SCOPE) parsed = urlparse(self.client.auth_uri(state=STATE)) qs = dict(parse_qsl(parsed.query)) self.assertEqual(qs['state'], STATE) @with_patched_client( json.dumps({ 'access_token': 'test_token', 'expires_in': 300, })) def test_request_token_json(self): self.client.request_token() self.assertEqual(self.client.access_token, 'test_token') self.client.request_token(redirect_uri=REDIRECT_URI) self.assertEqual(self.client.access_token, 'test_token') @with_patched_client('access_token=test_token') def test_request_token_url(self): self.client.request_token() self.assertEqual(self.client.access_token, 'test_token') @with_patched_client(json.dumps({ 'access_token': 'refreshed_token', })) def test_refresh_token(self): self.client.refresh_token = 'refresh_token' self.client.refresh() self.assertEqual(self.client.access_token, 'refreshed_token') @with_patched_client(json.dumps({'userid': 1234})) def test_request(self): self.client.access_token = 'foo' data = self.client.request('/foo') self.assertEqual(data['userid'], 1234) @with_patched_client( zlib.compress(json.dumps({ 'userid': 1234 }).encode('utf8'))) def test_request_custom_parser(self): def _decompress(buf): return json.loads(zlib.decompress(buf).decode()) self.client.access_token = 'foo' data = self.client.request('/foo', parser=_decompress) self.assertEqual(data['userid'], 1234) @with_patched_client(json.dumps({'userid': 1234})) def test_request_transport_headers(self): self.client.token_transport = transport_headers self.client.access_token = 'foo' data = self.client.request('/foo') self.assertEqual(data['userid'], 1234) @with_patched_client(json.dumps({'userid': 1234}), headers={ 'Content-Type': 'text/html; charset=utf-8', }) def test_request_with_charset(self): self.client.access_token = 'foo' data = self.client.request('/foo') self.assertEqual(data['userid'], 1234) @with_patched_client(json.dumps({'userid': 1234})) def test_custom_transport(self): def _transport(url, access_token, data=None, method=None, headers=None): self.assertEqual(url, 'http://example.com/resource/foo') self.assertEqual(access_token, 'foo') self.client.access_token = 'foo' self.client.token_transport = _transport data = self.client.request( '/foo', headers={'Content-Type': 'application/json'}) self.assertEqual(data['userid'], 1234) @with_patched_client(json.dumps({'userid': 1234})) def test_query_transport_with_headers(self): self.client.access_token = 'foo' data = self.client.request( '/foo', headers={'Content-Type': 'application/json'}) self.assertEqual(data['userid'], 1234) @with_patched_client(json.dumps({'userid': 1234})) def test_header_transport_with_headers(self): self.client.access_token = 'foo' self.client.token_transport = transport_headers data = self.client.request( '/foo', headers={'Content-Type': 'application/json'}) self.assertEqual(data['userid'], 1234)
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
class TestClient(TestCase): def setUp(self): self.client = Client(auth_endpoint=AUTH_ENDPOINT, token_endpoint=TOKEN_ENDPOINT, resource_endpoint=RESOURCE_ENDPOINT, client_id=CLIENT_ID) def test_init(self): map(lambda c: self.assertEqual(*c), ((self.client.auth_endpoint, AUTH_ENDPOINT), (self.client.token_endpoint, TOKEN_ENDPOINT), (self.client.resource_endpoint, RESOURCE_ENDPOINT), (self.client.client_id, CLIENT_ID),)) def test_auth_uri(self): parsed = urlparse(self.client.auth_uri(redirect_uri=REDIRECT_URI)) qs = dict(parse_qsl(parsed.query)) map(lambda c: self.assertEqual(*c), ((qs['redirect_uri'], REDIRECT_URI), (qs['response_type'], 'code'), (qs['client_id'], CLIENT_ID))) parsed = urlparse(self.client.auth_uri(scope=SCOPE)) qs = dict(parse_qsl(parsed.query)) self.assertEqual(qs['scope'], SCOPE) parsed = urlparse(self.client.auth_uri(state=STATE)) qs = dict(parse_qsl(parsed.query)) self.assertEqual(qs['state'], STATE) @with_patched_client(json.dumps({ 'access_token':'test_token', 'expires_in': 300, })) def test_request_token_json(self): self.client.request_token() self.assertEqual(self.client.access_token, 'test_token') self.client.request_token(redirect_uri=REDIRECT_URI) self.assertEqual(self.client.access_token, 'test_token') @with_patched_client('access_token=test_token') def test_request_token_url(self): self.client.request_token() self.assertEqual(self.client.access_token, 'test_token') @with_patched_client(json.dumps({ 'access_token': 'refreshed_token', })) def test_refresh_token(self): self.client.refresh_token = 'refresh_token' self.client.refresh() self.assertEqual(self.client.access_token, 'refreshed_token') @with_patched_client(json.dumps({ 'userid': 1234 })) def test_request(self): self.client.access_token = 'foo' data = self.client.request('/foo') self.assertEqual(data['userid'], 1234) @with_patched_client(zlib.compress(json.dumps({ 'userid': 1234 }).encode('utf8'))) def test_request_custom_parser(self): def _decompress(buf): return json.loads(zlib.decompress(buf).decode()) self.client.access_token = 'foo' data = self.client.request('/foo', parser=_decompress) self.assertEqual(data['userid'], 1234) @with_patched_client(json.dumps({ 'userid': 1234 })) def test_request_transport_headers(self): self.client.token_transport = transport_headers self.client.access_token = 'foo' data = self.client.request('/foo') self.assertEqual(data['userid'], 1234) @with_patched_client(json.dumps({ 'userid': 1234 }), headers={ 'Content-Type': 'text/html; charset=utf-8', }) def test_request_with_charset(self): self.client.access_token = 'foo' data = self.client.request('/foo') self.assertEqual(data['userid'], 1234) @with_patched_client(json.dumps({ 'userid': 1234 })) def test_custom_transport(self): def _transport(url, access_token, data=None, method=None, headers=None): self.assertEqual(url, 'http://example.com/resource/foo') self.assertEqual(access_token, 'foo') self.client.access_token = 'foo' self.client.token_transport = _transport data = self.client.request('/foo', headers={ 'Content-Type': 'application/json'}) self.assertEqual(data['userid'], 1234) @with_patched_client(json.dumps({ 'userid': 1234 })) def test_query_transport_with_headers(self): self.client.access_token = 'foo' data = self.client.request('/foo', headers={'Content-Type': 'application/json'}) self.assertEqual(data['userid'], 1234) @with_patched_client(json.dumps({ 'userid': 1234 })) def test_header_transport_with_headers(self): self.client.access_token = 'foo' self.client.token_transport = transport_headers data = self.client.request('/foo', headers={'Content-Type': 'application/json'}) self.assertEqual(data['userid'], 1234)
def main(): # instantiating a client to process OAuth2 response c = Client( auth_endpoint=auth_endpoint, token_endpoint=token_endpoint, resource_endpoint=resource_endpoint, client_id=client_id, client_secret=client_secret, token_transport=transport_headers) # 3-legged (read/write) scope_req = 'public rides.read rides.request' url = c.auth_uri(scope=scope_req, scope_delim=' ', state='asdf') print "Welcome to the API client tool for" print "" print " IIIII7MMMMMMMMMMMMMMMMMMM7IIIIIII7MMMMMM" print " IIIII7MMMMMMMMMMMMMMMMMIIIIIIIIIIII7MMMM" print " IIIII7MMMMMMMMMMMMMMMMIIIIIIIIIIIIIIIMMM" print " IIIII7MMMMMMMMMMMMMMMMIIIIII7M7IIIIIIMMM" print " IIIII7MIIIIIIMNIIIIIZDIIIIINMMMZIIIIIIIM" print " IIIII7MIIIIIIMNIIIIIZ8IIIIIMMMM8IIIIIIIM" print " IIIII7MIIIIIIMNIIIIIZ8IIIIIIIIN8IIIIIIIM" print " IIIII7MIIIIIIMNIIIIIZ8IIIIIIIIN8IIIIIMMM" print " IIIII7MIIIIIIMNIIIIIZ8IIIIIIIIN8IIIIIMMM" print " IIIII7MIIIIIIMIIIIIIZ8IIIII777NMIIIII7MM" print " IIIII7MIIIIIIIIIIIIIZ8IIIIIMMMMMIIIIIIID" print " IIIIIIMIIIIIIIIIIIIIZ8IIIIIMMMMMMIIIIIID" print " MIIIII7MIIIIIIIIIIIIO8III7MMMMMMMMMIIIID" print " MMD7IIIMMMMMMMIIIIIIMD78MMMMMMMMMMMMMMOD" print " MMMMMMMMNIIIIIIIIIIIMMMMMMMMMMMMMMMMMMMM" print " MMMMMMMMNIIIIIIIIIIMMMMMMMMMMMMMMMMMMMMM" print " MMMMMMMMNIIIIIIII7MMMMMMMMMMMMMMMMMMMMMM" print " MMMMMMMMMMMZ78MMMMMMMMMMMMMMMMMMMMMMMMMM" print "" print "STEP 1: Authenticate a user by opening this URL in a browser (Command + Double Click):\n\n%s" % url print "" code = raw_input("STEP 2: After authenticating, paste the 'code' parameter in the redirect URL here: ") result = c.request_token(grant_type='authorization_code', code=code) print "\nSTEP 3: There is no Step 3. You are now authenticated to the Lyft API. Congratulations!" print "\nEnter a URI to start testing. Some examples:\n\n\t%s --> ETA for location\n\t%s --> Rides for location" % (example_url_eta, example_url_rides) command = raw_input(prompt) while command != 'Q': try: method = "GET" data = None if " " in command: (method, command, data) = command.split(" ") result = c.request(command, method=method, data=data) pretty(result) except Exception as ex: import traceback traceback.print_exc() command = raw_input(prompt)
def start_github_login(): c = Client( auth_endpoint=GITHUB_AUTH_ENDPOINT, client_id=current_app.config['GITHUB_OAUTH_CLIENT_ID'], ) return redirect(c.auth_uri(scope=GITHUB_SCOPE, state=csrf._get_token(), redirect_uri=OAUTH_REDIRECT_URI))
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'] }) auth_url = 'https://api.genius.com/oauth/authorize/?' r = requests.get('https://api.genius.com/oauth/authorize', params={ 'client_id': config['client_id'], 'redirect_uri': 'https://anthonywbaker.com',