def get_auth_url(filename=CREDENTIALS_FILENAME): with open(filename, 'r') as config_file: config = safe_load(config_file) client_id = config['client_id'] client_secret = config['client_secret'] redirect_url = config['redirect_url'] config_values = [client_id, client_secret, redirect_url] for value in config_values: if value in DEFAULT_CONFIG_VALUES: exit('Missing credentials in {}'.format(filename)) credentials = { 'client_id': client_id, 'client_secret': client_secret, 'redirect_url': redirect_url, 'scopes': set(config['scopes']), } auth_flow = AuthorizationCodeGrant(credentials['client_id'], credentials['scopes'], credentials['client_secret'], credentials['redirect_url']) auth = auth_flow.get_authorization_url() return auth, auth_flow
def authorization_code_grant_flow(credentials, storage_filename): """Get an access token through Authorization Code Grant. Parameters credentials (dict) All your app credentials and information imported from the configuration file. storage_filename (str) Filename to store OAuth 2.0 Credentials. Returns (UberRidesClient) An UberRidesClient with OAuth 2.0 Credentials. """ auth_flow = AuthorizationCodeGrant( credentials.get('client_id'), credentials.get('scopes'), credentials.get('client_secret'), credentials.get('redirect_url'), ) auth_url = auth_flow.get_authorization_url() login_message = 'Login and grant access by going to:\n{}\n' login_message = login_message.format(auth_url) response_print(login_message) redirect_url = 'Copy the URL you are redirected to and paste here: \n' result = raw_input(redirect_url).strip() try: session = auth_flow.get_session(result) except (ClientError, UberIllegalState), error: fail_print(error) return
def uber_profile_exists(self): ### ----- Check if user has Uber Profile -----------# contents = self.content client_id = contents['client_id'] scopes = set(contents['scopes']) client_secret = contents['client_secret'] redirect_uri = contents['redirect_uri'] code = contents['code'] auth_flow = AuthorizationCodeGrant(client_id, scopes, client_secret, redirect_uri) auth_url = auth_flow.get_authorization_url() r = requests.get(auth_url, allow_redirects=True) encodedStr = r.url # Get rid of Url encoding decoded_url = unquote(encodedStr) idx = decoded_url.index("state=") state_str = decoded_url[idx:] # TODO: FIGURE OUT Whats going on with redirect URI new_redirect_url = redirect_uri + "?" + code + "&" + state_str # TODO: Figure this out for new session session = auth_flow.get_session(new_redirect_url) client = UberRidesClient(session, sandbox_mode=True) credentials = session.oauth2credential response = client.get_user_profile() profile = response.json email = profile.get('email') #THIS Is all a guess: has_uber_profile = True if email is not None else False return has_uber_profile
def autorization(requests): auth_flow = AuthorizationCodeGrant( '-iiIrHNDDp5khRs_dpGqq0rBvRwd1dQn', ['places', 'profile', 'all_trips'], 'wScfIhscTdyv8dWw26Bb7M2899limPKQ1rF6CrZI', 'http://localhost:8000' ) auth_url = auth_flow.get_authorization_url() return render(auth_url, 'autorization.html')
def authorization_code_grant_flow(credentials, storage_filename): """Get an access token through Authorization Code Grant. Parameters credentials (dict) All your app credentials and information imported from the configuration file. storage_filename (str) Filename to store OAuth 2.0 Credentials. Returns (UberRidesClient) An UberRidesClient with OAuth 2.0 Credentials. """ print credentials.get('scopes') auth_flow = AuthorizationCodeGrant( credentials.get('client_id'), credentials.get('scopes'), credentials.get('client_secret'), credentials.get('redirect_url'), ) auth_url = auth_flow.get_authorization_url() login_message = 'Login and grant access by going to:\n{}\n' login_message = login_message.format(auth_url) print(login_message) redirect_url = 'Copy the URL you are redirected to and paste here: \n' result = input(redirect_url).strip() try: session = auth_flow.get_session(result) except (ClientError, UberIllegalState) as error: print "failed........" print(error) return credential = session.oauth2credential credential_data = { 'client_id': credential.client_id, 'redirect_url': credential.redirect_url, 'access_token': credential.access_token, 'expires_in_seconds': credential.expires_in_seconds, 'scopes': list(credential.scopes), 'grant_type': credential.grant_type, 'client_secret': credential.client_secret, 'refresh_token': credential.refresh_token, } with open(storage_filename, 'w') as fp: print "dumped to file!" json.dump(credential_data,fp) return UberRidesClient(session, sandbox_mode=True)
def uber_auth_url(): """Return url where Uber will ask the user if we are allowed to make requests.""" from uber_rides.auth import AuthorizationCodeGrant auth_flow = AuthorizationCodeGrant( CLIENT_ID, PERMISSION_SCOPES, CLIENT_SECRET, REDIRECT_URL, ) return auth_flow.get_authorization_url()
def authenticate(): global auth_flow auth_flow = AuthorizationCodeGrant( 'vvXhhV_qjiVbwcADOtvVjCK2aj91RJJd', {'request'}, 'LDqbDapADdf_ZFeZRe9fL_MKLga3mZ9Ryo3eIHMC', 'http://localhost:8000/uber/redirect' ) auth_url = auth_flow.get_authorization_url() call(['open', auth_url])
def login(): auth_flow = AuthorizationCodeGrant( credentials.get('client_id'), credentials.get('scopes'), credentials.get('client_secret'), credentials.get('redirect_url'), ) auth_url = auth_flow.get_authorization_url() return redirect(auth_url)
def get_auth(self, msisdn): auth_flow = AuthorizationCodeGrant(CLIENT_ID, SCOPES, CLIENT_SECRET, REDIRECT_URL) auth_url = auth_flow.get_authorization_url() self.state_uber = auth_flow.state_token # print auth_url incomingMsisdn = json.loads(self.redis.get("inc/%s" % (msisdn))) incomingMsisdn[1] = pickle.dumps(auth_flow) self.redis.set("inc/%s" % (msisdn), json.dumps(incomingMsisdn)) return auth_flow
def authorization_code_grant_flow(credentials, storage_filename): """Get an access token through Authorization Code Grant. Parameters credentials (dict) All your app credentials and information imported from the configuration file. storage_filename (str) Filename to store OAuth 2.0 Credentials. Returns (UberRidesClient) An UberRidesClient with OAuth 2.0 Credentials. """ auth_flow = AuthorizationCodeGrant( credentials.get('client_id'), credentials.get('scopes'), credentials.get('client_secret'), credentials.get('redirect_url'), ) auth_url = auth_flow.get_authorization_url() login_message = 'Login and grant access by going to:\n{}\n' login_message = login_message.format(auth_url) response_print(login_message) redirect_url = 'Copy the URL you are redirected to and paste here: \n' result = input(redirect_url).strip() try: session = auth_flow.get_session(result) except (ClientError, UberIllegalState) as error: fail_print(error) return credential = session.oauth2credential credential_data = { 'client_id': credential.client_id, 'redirect_url': credential.redirect_url, 'access_token': credential.access_token, 'expires_in_seconds': credential.expires_in_seconds, 'scopes': list(credential.scopes), 'grant_type': credential.grant_type, 'client_secret': credential.client_secret, 'refresh_token': credential.refresh_token, } with open(storage_filename, 'w') as yaml_file: yaml_file.write(safe_dump(credential_data, default_flow_style=False)) return UberRidesClient(session, sandbox_mode=True)
def __init__( self, client_id=os.environ["UBER_CLIENT_ID"], client_secret=os.environ["UBER_CLIENT_SECRET"], scopes={"profile"}, redirect_url="http://localhost:8000/uber/connect", ): auth_flow = AuthorizationCodeGrant( client_id=client_id, scopes=scopes, client_secret=client_secret, redirect_url=redirect_url ) auth_url = auth_flow.get_authorization_url() print(auth_url)
def get_uber_products(start_latitude, start_longitude, redirect_url): auth_flow = AuthorizationCodeGrant( CLIENT_ID, PERMISSION_SCOPE, CLIENT_SECRET, REDIRECT_URI) auth_url = auth_flow.get_authorization_url() session = auth_flow.get_session(redirect_url) client = UberRidesClient(session) credentials = session.oauth2credential response = client.get_products(37.77, -122.41) products = response.json.get('products') print products
def get_uber_rides_client(credential_storage_file_name): credentials = import_app_credentials('config.rider.yaml') auth_flow = AuthorizationCodeGrant( credentials.get('client_id'), credentials.get('scopes'), credentials.get('client_secret'), credentials.get('redirect_url'), ) auth_url = auth_flow.get_authorization_url() login_message = 'Login as a rider and grant access by going to:\n\n{}\n' login_message = login_message.format(auth_url) print(login_message) redirect_url = 'Copy the URL you are redirected to and paste here: \n\n' result = input(redirect_url).strip() try: session = auth_flow.get_session(result) except (ClientError, UberIllegalState) as error: print("Error getting authorization session.") raise SystemExit(error) credential = session.oauth2credential credential_data = { 'client_id': credential.client_id, 'redirect_url': credential.redirect_url, 'access_token': credential.access_token, 'expires_in_seconds': credential.expires_in_seconds, 'scopes': list(credential.scopes), 'grant_type': credential.grant_type, 'client_secret': credential.client_secret, 'refresh_token': credential.refresh_token, } with open(credential_storage_file_name, 'w') as yaml_file: yaml_file.write(safe_dump(credential_data, default_flow_style=False)) return UberRidesClient(session, sandbox_mode=True)
def call_uber(flight_number, flight_origin_date): coords = get_coords(flight_number, flight_origin_date) server_token = "GSYPRMkSl_a7qQn8FH6d4imBjBnvrTWhh-6OzVPX" session = Session(server_token) client = UberRidesClient(session) response = client.get_products(coords[0], coords[1]) products = response.json.get('products') auth_flow = AuthorizationCodeGrant( "gT2GLeVlXMQkrWWBO872bcjHK168Tr8W", None, "fQMuhWzwuvMiy2yl31qDu4xIRMP0DIVQQUtJy3hj", None, ) auth_url = auth_flow.get_authorization_url() session = auth_flow.get_session() client = UberRidesClient(session, sandbox_mode=True) credentials = session.oauth2credential get_coords() response = client.request_ride( start_latitude=coords[0], start_longitude=coords[1], ) ride_details = response.json ride_id = ride_details.get('request_id')
import json import requests from uber_rides.auth import AuthorizationCodeGrant from uber_rides.session import Session from uber_rides.client import UberRidesClient client_id = 'V4XWn0beV4JnKHHANILZdPXSMwPgh5-Y' scopes = 'partner.accounts' client_secret = 'v0RvnHN-EmCD0uG_1ybPwaFGQ2_VP9Z7UORf-oTn' redirect_url = 'http://localhost:7000/submit' auth_flow = AuthorizationCodeGrant(client_id, scopes, client_secret, redirect_url) api_url = auth_flow.get_authorization_url() print('Please go to %s and authorize access.' % api_url) authorization_response = input('Enter the full callback URL: ') session = auth_flow.get_session(authorization_response) client = UberRidesClient(session, sandbox_mode=True) credentials = session.oauth2credential response = client.get_driver_trips() trips = response.json print(history)
def __uber_action(self, nlu_entities=None): uber = None if nlu_entities is not None: if 'location' in nlu_entities: entities3 = nlu_entities['search_query'][0]["value"] entities1 = nlu_entities['location'][0]["value"] entities2 = nlu_entities['location'][1]["value"] print(entities3) print(entities1) print(entities2) if entities1 and entities2 is not None: response = requests.get( 'https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=AIzaSyAx_nPgGLpiiak3Ey0YgDaJjoqlcjZko1A' % entities1) # add key resp_json_payload = response.json() lat1 = ( resp_json_payload['results'][0]['geometry']['location']['lat']) lng1 = ( resp_json_payload['results'][0]['geometry']['location']['lng']) response = requests.get( 'https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=AIzaSyAx_nPgGLpiiak3Ey0YgDaJjoqlcjZko1A' % entities2) # add key resp_json_payload = response.json() lat2 = ( resp_json_payload['results'][0]['geometry']['location']['lat']) lng2 = ( resp_json_payload['results'][0]['geometry']['location']['lng']) oauth2credential = OAuth2Credential( client_id='FxkO4ImvByXu-7Dm1vYMHcKIt3C-3-LX ', # add client id access_token= 'JA. -HsSUvO2XciOsCC3M25dwxYZTxyr4T9WKRKW8SawMVLucIKNmSZSZtvuE2LUMfb_ykrWxDAAAAIhIo1wfiuri3URzNyQAAABiMGQ4NTgwMy0zOGEwLTQyYjMtODA2ZS03YTRjZjhlMTk2ZWU', # get access token expires_in_seconds='2592000', scopes= 'all_trips delivery history history_lite places profile request request_receipt ride_widgets', grant_type='authorization_code', redirect_url= 'http://localhost:8080/redirect_uri', # add redirect_url client_secret= 'hAjOfJ-OPiQ3dntDT9KtiLxwitcXrxu8-pNPRuzP', # add client secret refresh_token='', # add refresh token ) from uber_rides.auth import AuthorizationCodeGrant redirect_url = 'https://localhost:8080/redirect_uri', # add redirect_url auth_flow = AuthorizationCodeGrant( client_id='FxkO4ImvByXu-7Dm1vYMHcKIt3C-3-LX ', # add client id # access_token='JA.VUNmGAAAAAAAEgASAAAABwAIAAwAAAAAAAAAEgAAAAAAAAG8AAAAFAAAAAAADgAQAAQAAAAIAAwAAAAOAAAAkAAAABwAAAAEAAAAEAAAAKJLlVbnq3rq5cidLOUCeZZsAAAAxfnlfHgkh1D_dT92vApueOOrPLV79RicmAdIVBZXV4jUZfneV1jq3pcF2Xwdd5AIaCpvZxVY32u-HsSUvO2XciOsCC3M25dwxYZTxyr4T9WKRKW8SawMVLucIKNmSZSZtvuE2LUMfb_ykrWxDAAAAIhIo1wfiuri3URzNyQAAABiMGQ4NTgwMy0zOGEwLTQyYjMtODA2ZS03YTRjZjhlMTk2ZWU', # get access token # expires_in_seconds='2592000', scopes= 'all_trips delivery history history_lite places profile request request_receipt ride_widgets', # scopes='ride_widgets', # grant_type='authorization_code', redirect_url= 'https://localhost:8080/redirect_uri', # add redirect_url client_secret= 'hAjOfJ-OPiQ3dntDT9KtiLxwitcXrxu8-pNPRuzP', # add client secret # refresh_token='', # add refresh token ) redirect_url = 'https://localhost:8080/redirect_uri', # add redirect_url auth_url = auth_flow.get_authorization_url() #session = auth_flow.get_session(redirect_url) session = Session(oauth2credential=oauth2credential) print(session) client = UberRidesClient(session, sandbox_mode=True) print(client) response = client.get_products(lat1, lng1) credentials = session.oauth2credential print(response) response = client.get_user_profile() profile = response.json print(profile) # response_uber = client.get_price_estimates( # start_latitude=lat1, # start_longitude=lng1, # end_latitude=lat2, # end_longitude=lng2, # seat_count=1 # ) # estimate = response_uber.json.get('prices') # print estimate[0]['high_estimate'] # print estimate[0]['low_estimate'] # print estimate[0]['localized_display_name'] # print estimate[0]['currency_code'] # currency = estimate[0]['currency_code'] # hi_est = str(estimate[0]['high_estimate']) + str(estimate[0]['currency_code']) # low_est = str(estimate[0]['low_estimate']) + str(estimate[0]['currency_code']) # type_cab = estimate[0]['localized_display_name'] # print estimate[0] response = client.get_products(lat1, lng1) products = response.json.get('products') # print(products) if entities3 == 'Uber go': for i in range(1, 5): if products[i]['display_name'] == 'uberGO': product_id = products[i].get('product_id') type_cab = products[i].get('display_name') elif entities3 == 'Uber pool': for i in range(1, 5): if products[i]['display_name'] == 'POOL': product_id = products[i].get('product_id') type_cab = products[i].get('display_name') else: product_id = products[0].get('product_id') type_cab = products[0].get('display_name') estimate = client.estimate_ride(product_id=product_id, start_latitude=lat1, start_longitude=lng1, end_latitude=lat2, end_longitude=lng2, seat_count=1) fare = estimate.json.get('fare') bas = fare['display'] client.cancel_current_ride() response = client.request_ride(product_id=product_id, start_latitude=lat1, start_longitude=lng1, end_latitude=lat2, end_longitude=lng2, seat_count=1, fare_id=fare['fare_id']) request = response.json print(request) request_id = request.get('request_id') url = 'https://sandbox-api.uber.com/v1.2/sandbox/requests/' + request ur = 'https://sandbox-api.uber.com/v1.2/requests/' + request + '/map' token = "hAjOfJ-OPiQ3dntDT9KtiLxwitcXrxu8-pNPRuzP" # insert token data = {"status": "accepted"} headers = { 'Authorization': 'Bearer ' + token, "Content-Type": "application/json" } # Call REST API response = requests.put(url, data=json.dumps(data), headers=headers) response = requests.get(ur, headers=headers) response = client.get_ride_details(request_id) ride = response.json print(ride) status = ride.get('status') dri_name = ride.get('driver').get('name') dri_pic = ride.get('driver').get('picture_url') eta = ride.get('destination').get('eta') car_pix = ride.get('vehicle').get('picture_url') # product_name1 = products[3]['display_name'] #GO # product_nam2 = products[2]['display_name'] #POOL uber_action = "Sure. Booking your uber from %s to %s. Your cab type is %s and estimated time of arrival is %s and fare will be approx %s" % ( entities1, entities2, type_cab, eta, bas) cab_data = { "cabtype": type_cab, 'maxfare': bas, "minfare": eta, 'to': entities2, 'from': entities1, 'status': status, 'driver': dri_name, 'pic': dri_pic, 'car': car_pix, 'map': ur } # print cab_data requests.post("http://localhost:8080/cab", data=json.dumps(cab_data)) self.speech.synthesize_text(uber_action) else: self.__text_action( "I'm sorry, I don't think that their is any cab available between these two locations." )
# geolocator = geopy.geocoders.GoogleV3() # Step 1 in 3-legged OAuth handshake: # Prepare OAuth 2.0 service that is used to make requests credentials = import_app_credentials() auth_flow = AuthorizationCodeGrant( credentials.get('client_id'), credentials.get('scopes'), credentials.get('client_secret'), credentials.get('redirect_url'), ) # Generate authorization url auth_url = auth_flow.get_authorization_url() @app.route('/') def index(): """Homepage.""" return render_template('home.html') @app.route('/authenticate') def login(): """Redirect to https://login.uber.com/login"""