Example #1
0
    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
Example #2
0
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
Example #4
0
def auth_code_grant():
    return AuthorizationCodeGrant(
        client_id=CLIENT_ID,
        scopes=SCOPES,
        client_secret=CLIENT_SECRET,
        redirect_url=REDIRECT_URL,
    )
Example #5
0
def get_auth_flow(state_token=None):
    return AuthorizationCodeGrant(
        credentials.get('client_id'),
        credentials.get('scopes'),
        credentials.get('client_secret'),
        credentials.get('redirect_url'),
        state_token
    )
Example #6
0
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')
Example #7
0
def get_auth_flow(config):
    redirect_url = 'https://bartybox.herokuapp.com/'
    return AuthorizationCodeGrant(
        config['uber']['client_id'],
        ['request'],  # permission scopes (Allow App 'Barty Box' access to your...?)
        config['uber']['client_secret'],
        redirect_url,  # redirect URL must match that on our Uber API account
        # As the name implies, it takes the user to this URL after they are authenticated by Uber
    )
Example #8
0
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 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
Example #10
0
    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)
Example #11
0
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')
Example #13
0
from uber_rides.auth import AuthorizationCodeGrant
from uber_rides.client import UberRidesClient
from uber_rides.session import Session
from geopy.geocoders import Nominatim
geolocator = Nominatim()


YOUR_CLIENT_ID = 'dkZUuhWTWVfrL1pEO7iM6Fueka0IteNF'
YOUR_CLIENT_SECRET = '7ZMw7r_gvf70djT86qebOSfTofB_zNnwyRwnoE_l'
YOUR_SERVER_TOKEN = '7jj733zk0UYqhcN5UjXsZFF9WPJ7Fkin6zSik9ZB'
YOUR_REDIRECT_URL = 'http://localhost'
YOUR_PERMISSION_SCOPES = ['profile', 'history', 'places', 'request', 'request_receipt']
auth_flow = AuthorizationCodeGrant(
    YOUR_CLIENT_ID,
    YOUR_PERMISSION_SCOPES,
    YOUR_CLIENT_SECRET,
    YOUR_REDIRECT_URL,
)

auth_url = auth_flow.get_authorization_url()

st = auth_url.find('state=')

ns = auth_url[st+len('state='):]
state = ns[:ns.find('&')]
print auth_url
print state



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)
Example #15
0
from uber_rides.auth import AuthorizationCodeGrant
from uber_rides.session import Session
from uber_rides.client import UberRidesClient

auth_flow = AuthorizationCodeGrant(
    '-iiIrHNDDp5khRs_dpGqq0rBvRwd1dQn',
    ['places', 'profile', 'all_trips'],
    'wScfIhscTdyv8dWw26Bb7M2899limPKQ1rF6CrZI',
    # 'KA.eyJ2ZXJzaW9uIjoyLCJpZCI6IjQ3WTlLcUl1VFNtbTdkWmJadVNVb2c9PSIsImV4cGlyZXNfYXQiOjE1MjcxMzI5MzgsInBpcGVsaW5lX2tleV9pZCI6Ik1RPT0iLCJwaXBlbGluZV9pZCI6MX0.DktH6vbpWIbh8qNMnduygBrvS3l-nvJD3wctIjftMx8',
    'http://localhost:8000')
auth_url = auth_flow.get_authorization_url()

print(auth_url)

# session = auth_flow.get_session(redirect_uri)
# client = UberRidesClient(session, sandbox_mode=True)
# credentials = session.oauth2credential

# print(auth_flow.state_token)
# print(auth_flow.client_id)
# print(auth_flow.get_authorization_url())
# print(auth_flow.redirect_url)
# print(auth_flow.scopes)
# session = Session(server_token='Ls6hCxMf0l3ZFM0qaD5RVHbfgASx8oGPLRHsXVb4')
# print(session)
# session = auth_flow.get_session(redirect_url='http://localhost:8000/autorization')
# print(session)

# client = UberRidesClient(session, sandbox_mode=True)

# print(UberRidesClient(session, sandbox_mode=True))
Example #16
0
from example import utils  # NOQA
from example.utils import import_app_credentials

from uber_rides.auth import AuthorizationCodeGrant
from uber_rides.client import UberRidesClient

import datetime

app = Flask(__name__, template_folder="./")

credentials = import_app_credentials('config.driver.yaml')

auth_flow = AuthorizationCodeGrant(
    credentials.get('client_id'),
    credentials.get('scopes'),
    credentials.get('client_secret'),
    credentials.get('redirect_url'),
)


@app.template_filter('date')
def date(value, format='%b %d, %Y at %H:%M'):
    return datetime.datetime.fromtimestamp(value).strftime(format)


@app.route('/')
def index():
    """Index controller to redirect user to sign in with uber."""
    return redirect(auth_flow.get_authorization_url())

Example #17
0
repo = client["Nightlife_Reccomendation"]
repo.authenticate('group5', 'group5')

# Setup Uber OAuth
with open('uber.rider.config.yaml', 'r') as config_file:
    uber_config = safe_load(config_file)
    
credentials = {}
credentials['client_id'] = uber_config['client_id']
credentials['client_secret'] = uber_config['client_secret']
credentials['redirect_url'] = uber_config['redirect_url']
credentials['scopes'] = set(uber_config['scopes'])

auth_flow = AuthorizationCodeGrant(
    credentials['client_id'],
    credentials['scopes'],
    credentials['client_secret'],
    credentials['redirect_url']
    )

uber_client = None

@app.route("/")
def authorize():
    """ Immediately authorize user with uber as soon as they enter the site
        Relatively integral to the entire use of the application             """
    return redirect(auth_flow.get_authorization_url())

@app.route("/home")
def home():
    """ Render the home page with the users information from Uber           """
    if type(uber_client) != None:
Example #18
0
from uber_rides.client import UberRidesClient

session = Session(server_token="2pWDz82lm8GvniDsrxaGYTRZtxjM0iB5uepR-itY")
client = UberRidesClient(session)

#Get a list of available products

response = client.get_products(37.77, -122.41)
products = response.json.get('products')

#Get price and time estimates

response = client.get_price_estimates(start_latitude=37.770,
                                      start_longitude=-122.411,
                                      end_latitude=37.791,
                                      end_longitude=-122.405,
                                      seat_count=2)

estimate = response.json.get('prices')

#Authorize a rider for your application

from uber_rides.auth import AuthorizationCodeGrant

auth_flow = AuthorizationCodeGrant(
    "neWKQtl-Fr3TKZeStdPdu2rkPMM0QH6p",
    "all_trips delivery history history_lite places profile request request_receipt ride_widgets",
    "q1DvUHO1KPj-GsqvxIm0qtPsnmUrqjyFBKMB-COU", "http://127.0.0.1/")
auth_url = auth_flow.get_authorization_url()
print(auth_url)
Example #19
0
    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."
            )
Example #20
0
import json
from uber_rides.session import Session
from uber_rides.client import UberRidesClient
from flask import Flask
from flask_restful import Resource, Api
from uber_rides.auth import AuthorizationCodeGrant

google_api_key = 'REPLACE'
session = Session(server_token='REPLACE')

uber_client = UberRidesClient(session)
uber_private_id = 'b8e5c464-5de2-4539-a35a-986d6e58f186' #uberx
uber_shared_id = '929fcc19-8cb4-4007-a54f-3ab34473700f'
auth_flow = AuthorizationCodeGrant(
    'REPLACE',
    'request',
    'REPLACE',
    'http://127.0.0.1:5000',
)
uber_fare = ()
redirect_url = 'REPLACE'

app = Flask(__name__)
api = Api(app)
last_request_coords = ()

class GetEstimates(Resource):
    def get(self, start, end):
        global last_request_coords
        start_coord, end_coord = getGoogleCoordinates(start, end)  
        last_request_coords = (start_coord, end_coord)
        #Make the uber request