Beispiel #1
0
def login():
    client = Client()
    authorize_url = client.authorization_url(
        client_id=CONSTANTS.CLIENT_ID, redirect_uri=CONSTANTS.CALLBACK_URL)
    # Have the user click the authorization URL,
    # a 'code' param will be added to the redirect_uris
    return jsonify({"status": "success", "url": authorize_url})
Beispiel #2
0
    def __fetch_token(self):
        host = '127.0.0.1'
        port = 5000

        client = Client()
        url = client.authorization_url(
            client_id=self.__client_id,
            redirect_uri='http://127.0.0.1:5000/authorization')
        print("follow this link (ctrl-c to cancel): {}".format(url))

        client_id = self.__client_id
        secret = self.__secret

        class Handler(http.server.BaseHTTPRequestHandler):
            def do_GET(self):
                code = urllib.parse.parse_qs(
                    urllib.parse.urlparse(self.path).query).get('code',
                                                                None)[0]
                token = client.exchange_code_for_token(client_id=client_id,
                                                       client_secret=secret,
                                                       code=code)
                keyring.set_password('bike2cern', 'strava', token)

        s = http.server.HTTPServer((host, port), Handler)
        try:
            s.handle_request()
        except KeyboardInterrupt:
            pass
        s.server_close()
Beispiel #3
0
def login():
    c = Client()
    url = c.authorization_url(client_id=app.config['STRAVA_CLIENT_ID'],
                              redirect_uri=url_for('.logged_in',
                                                   _external=True),
                              approval_prompt='auto')
    return render_template('login.html', authorize_url=url)
def authenticate():

    ## Strava API uses OAuth2, which requires users to manually allow permission, which generates
    ## a token only valid for a number of hours.

    ## get API client id and secret from config file

    config = configparser.ConfigParser()
    config.read("credentials.cfg")
    client_id = config.get('credentials', 'client_id')
    client_secret = config.get('credentials', 'client_secret')

    client = Client(rate_limiter=limiter.DefaultRateLimiter())
    authorize_url = client.authorization_url(
        client_id=client_id, redirect_uri='http://localhost:8282/authorized')

    ## getting token -- pretty manual process for now

    webbrowser.open_new_tab(authorize_url)

    code = input('Enter Temporary Code: ')
    code = str(code)

    ## authenticate using API credntials + token

    token_response = client.exchange_code_for_token(
        client_id=client_id, client_secret=client_secret, code=code)

    return client
Beispiel #5
0
def strava_authorize_url(page=None):
    client = Client()
    url = url_for('query.authorized', _external=True, page=page)
    return client.authorization_url(
        scope=['profile:read_all', 'activity:read_all'],
        client_id=CLIENT_ID,
        redirect_uri=url)
Beispiel #6
0
def make_authorization_url():
    client = Client()
    authorize_url = client.authorization_url(client_id=CLIENT_ID,
                                             redirect_uri=REDIRECT_URI,
                                             scope='view_private,write')
    print(authorize_url)
    return authorize_url
Beispiel #7
0
def get_authorization_url():
    client = Client()
    return client.authorization_url(
        client_id=STRAVA_CLIENT_ID,
        redirect_uri=url_for("authenticate", _external=True),
        scope=["activity:write", "activity:read_all"],
    )
def get_code(client_id: int) -> None:

    """Build an authorization URL"""

    client = Client()
    url = client.authorization_url(client_id = client_id, redirect_uri="http://localhost/get_the_code_parameter", scope=["read", "read_all", "profile:read_all", "profile:write", "activity:read","activity:read_all", "activity:write"])

    print("[+] Authorization URL is: {}".format(url))
Beispiel #9
0
def login():
    params = {
        'client_id': CLIENT_ID,
        'redirect_uri': HOSTNAME + '/oauth_authorized/'
    }
    client = Client()
    url = client.authorization_url(**params)
    return redirect(url)
Beispiel #10
0
def login():
    params = {
        'client_id': CLIENT_ID,
        'redirect_uri': HOSTNAME + '/oauth_authorized/'
    }
    client = Client()
    url = client.authorization_url(**params)
    return redirect(url)
Beispiel #11
0
def auth(request):
    client = Client()
    auth_link = client.authorization_url(
        5928, 'https://elevation-challenge.herokuapp.com/auth_success/')
    return render(request, 'auth.html', {
        'leaderboard': get_leaderboard(),
        'auth_link': auth_link
    })
Beispiel #12
0
 def __init__(self, token):
     if not token:
         client = Client()
         url = client.authorization_url(client_id=STRAVA_APP_ID, redirect_uri='http://localhost:8000/')
         code = input(f"Open {url}, copy code once redirected: ")
         token_response = client.exchange_code_for_token(client_id=STRAVA_APP_ID, client_secret=STRAVA_CLIENT_SECRET, code=code)
         self.STRAVA_ACCESS_TOKEN = token_response['access_token']
     else:
         self.STRAVA_ACCESS_TOKEN = token
Beispiel #13
0
def create_authentication_token():
    logger = logging.getLogger("authenticator.create_authentication_token")

    client = Client()

    logger.info(
        "This is a one-time operation to generate the required authentication tokens for the app. Please follow the steps carefully"
    )
    logger.info("")
    logger.info(
        "Follow the instructions here: https://developers.strava.com/docs/getting-started/#account to create an 'API Application'"
    )
    logger.info(
        "The important bits: Set the 'authorization callback domain' to 'localhost'"
    )
    logger.info(
        "Make a note of the 'Client ID' and 'Client Secret' values (you may have to click 'show' to see the value of the secret"
    )
    logger.info("")
    logger.info(
        "Create a file called 'client.secret' and place it in the strava_data directory"
    )
    input("Once you have performed the above steps, hit enter")

    MY_STRAVA_CLIENT_ID, MY_STRAVA_CLIENT_SECRET = open(
        '/opt/strava_data/client.secret').read().strip().split(',')

    logger.info(
        'Client ID ({}) and secret read from file'.format(MY_STRAVA_CLIENT_ID))

    url = client.authorization_url(
        client_id=MY_STRAVA_CLIENT_ID,
        redirect_uri='http://127.0.0.1:5000/authorization',
        scope=[
            'read_all', 'profile:read_all', 'activity:read_all',
            'profile:write', 'activity:write'
        ])

    logger.info("Open the following URL in a browser and approve access:")
    logger.info(url)

    auth_url_eg = "http://127.0.0.1:5000/authorization?state=&code=1e6878eb4b0175123e87bd8d708c40717448ac33&scope=read,activity:read_all,profile:read_all,read_all"
    code_eg = "1e6878eb4b0175123e87bd8d708c40717448ac33"
    logger.info(
        "The re-directed URL will look something like this: {}, please enter just the 'code' value now e.g. {}"
        .format(auth_url_eg, code_eg))
    CODE = input()

    access_token = client.exchange_code_for_token(
        client_id=MY_STRAVA_CLIENT_ID,
        client_secret=MY_STRAVA_CLIENT_SECRET,
        code=CODE)
    logger.info(
        "Access_token: {}, outputting to local file".format(access_token))
    with open('/opt/strava_data/access_token.pickle', 'wb') as f:
        pickle.dump(access_token, f)
Beispiel #14
0
def auth():
    access_token = request.cookies.get('access_token')
    if access_token:
        # Success!
        return show_images_demo()
    else:
        client = Client()
        url = client.authorization_url(client_id=MY_STRAVA_CLIENT_ID, redirect_uri=DOMAIN + '/authorization')
        print("DEBUG: auth url :" + url)
        return redirect(url, code=302)
Beispiel #15
0
def login():
    c = Client()
    url = c.authorization_url(
        client_id=config['client_id'],
        redirect_uri=url_for('.logged_in', _external=True),
        approval_prompt='auto',
        # Change to None if you don't want private activities included
        # scope=['read', 'read_all', 'profile:read_all', 'profile:write', 'activity:read','activity:read_all', 'activity:write']
        scope=['activity:read', 'activity:read_all', 'activity:write'])

    return render_template('login.html', authorize_url=url)
Beispiel #16
0
def parse_args(args):
    access_token_file_name = args.output_file

    client = Client()
    access_token_does_exist = os.path.isfile(access_token_file_name)
    access_token_doesnt_exist = not (access_token_does_exist)
    access_token_expired = True

    if access_token_does_exist:
        with open(access_token_file_name, "r") as f:
            token_response = json.load(f)
            token_response = json.loads(token_response)
            token_expiry_time = token_response["expires_at"]
            current_time = time.time()
            access_token_expired = current_time > token_expiry_time

    if access_token_doesnt_exist or access_token_expired:
        client_id = args.client_id
        client_secret = args.client_secret
        scope = [
            "read",
            "read_all",
            "profile:read_all",
            "activity:read",
            "activity:read_all",
        ]
        authorize_url = client.authorization_url(
            client_id=client_id,
            redirect_uri="http://localhost:5000/authorized",
            scope=scope,
        )

        # Open the authorization url
        print("Opening: " + authorize_url)
        webbrowser.open(authorize_url)

        # Get code
        entered_code = str(input("Please enter code: "))
        # Exchange code for token:
        token_response = client.exchange_code_for_token(
            client_id=client_id, client_secret=client_secret, code=entered_code
        )
        # Save it to file so we can use it until it expires.
        access_token_string = json.dumps(token_response)
        with open(access_token_file_name, "w+") as f:
            json.dump(access_token_string, f)

    # Now we have a token_response dict either from file or from the
    # Strava API
    access_token = token_response["access_token"]
    refresh_token = token_response["refresh_token"]

    print("access_token:", access_token)
    print("refresh_token", refresh_token)
Beispiel #17
0
 def authenticate(self, host_url, state):
     client = Client(requests_session=self.session)
     # chop last character of host url to avoid double slash in middle of url
     authorize_url = client.authorization_url(
         client_id=self.CLIENT_ID,
         redirect_uri=host_url[:-1] +
         url_for('handle_strava_auth_response'),
         state=state)
     self.logger.info(
         'Redirect: %s',
         host_url[:-1] + url_for('handle_strava_auth_response'))
     return redirect(authorize_url)
Beispiel #18
0
def index():
    """Home authentication page
    """ 
    conn = get_conn()
    client_id, client_secret = get_app_credentials(conn)
    client    = Client() # stravalib v3
    auth_link = client.authorization_url(client_id, REDIRECT_URI, scope=AUTH_SCOPE)
    title = "STRAVA buddies | Please log in to STRAVA"
    
    conn.close()
    return render_template("index.html", title=title, auth_link=auth_link,
                           tab="authenticate", examples=cached_athletes)
Beispiel #19
0
    def get(self):
        client = Client()
        authorize_url = client.authorization_url(client_id=conf.SV_CLIENT_ID, redirect_uri=conf.SV_AUTH_URL)


        template_values = {
            'url': authorize_url,
            'url_linktext': 'Connect with STAVA'
        }

        template = JINJA_ENVIRONMENT.get_template('index.html')
        self.response.write(template.render(template_values))
Beispiel #20
0
def get_stravauth_url(approval_prompt="auto", scope="write"):
    from django.conf import settings
    logger.info('get_stravauth_url begging')

    client = Client()
    authorize_url = client.authorization_url(
        client_id=settings.CLIENT_ID,
        redirect_uri=settings.STRAVA_REDIRECT,
        approval_prompt=approval_prompt,
        scope=scope)
    # TODO: check scope and approval_prompt are reasonable

    return authorize_url
Beispiel #21
0
def get_client():
    client = Client()
    authorize_url = client.authorization_url(
        client_id=26273,
        redirect_uri='https://localhost:8080',
        scope=['read', 'read_all', 'activity:read_all'])
    code = '299ad7943b6eb478247684620d87e341cfdcb6a2'
    access_token = client.exchange_code_for_token(
        client_id=26273,
        client_secret='80f4236b6e958701dbeebb8c09c99e9d2fb71d1a',
        code=code)
    client.access_token = access_token['access_token']
    return client
    def get(request):
        """ Request oauth via strava. """

        client = Client()

        return_uri = 'http://{}{}?start_date={}&end_date={}'.format(
            request.META['HTTP_HOST'],
            reverse_lazy('strava-authorized'),
            request.GET.get('start_date'),
            request.GET.get('end_date'),
        )
        authorize_url = client.authorization_url(
            client_id=settings.STRAVA_CLIENT_ID,
            redirect_uri=return_uri
        )
        return HttpResponseRedirect(authorize_url)
Beispiel #23
0
def index(request):

    user = None 

    if (request.user.is_authenticated):
        user = AuthUser.objects.get(user_id=request.user.id)

    client = Client()
    authorize_url = client.authorization_url(client_id=24429, redirect_uri="http://localhost:8000/main")

    #get code from get
    #Get Code from webapp response
    code = request.GET.get('code') if (request.GET.get('code') != None) else ''

    start_pos, end_pos, a_polyline = '', '', ''
    if (code != '' and request.user.is_authenticated):

        access_token = client.exchange_code_for_token(client_id=24429, client_secret=config_vars.STRAVA_CLIENT_SECRET, code=code)

        user_model = AuthUser.objects.get(user_id=request.user.id)
        
        # Store User Access Token in DB
        if (user_model is not None):
            user_model.auth_code = access_token
            user_model.save()

    # Set Access Token On Client
    if (request.user.is_authenticated and user.auth_code != ''):
        
        pprint("User Logged in and has an auth code")
        client.access_token = user.auth_code
        athlete = client.get_athlete()

        full_activity = client.get_activity(1486441471, True)
        
        a_polyline = full_activity.map.polyline
        start_pos = full_activity.start_latlng
        end_pos = full_activity.end_latlng


    return render(request, "index.html", {
        "auth_url": authorize_url, 
        "start_pos": start_pos,
        "end_pos": end_pos,
        "polyline": a_polyline,
        "user_is_authenticated": request.user.is_authenticated 
    })
    def authorize(self):
        client = Client()
        authorize_url = client.authorization_url(
            client_id=9531, redirect_uri='http://127.0.0.1:5000/authorization')
        # Have the user click the authorization URL, a 'code' param will be added to the redirect_uri
        # .....

        # Extract the code from your webapp response
        # code = request.args.get('code') # or whatever your framework does
        # access_token = client.exchange_code_for_token(client_id=9531, client_secret='111b5017534c4bd4049f8ff941790b0762b63701', code=code)

        access_token = "990aa3bd5897c731ee759794edeecd7c058939de"
        # Now store that access token somewhere (a database?)
        client.access_token = access_token
        athlete = client.get_athlete()
        print("For {id}, I now have an access token {token}".format(
            id=athlete.id, token=access_token))
        athlete = client.get_athlete(227615)
        print("Hello, {}".format(athlete.firstname))
Beispiel #25
0
def strava_client(client_id=None,
                  client_secret=None,
                  refresh_token=None,
                  access_token=None):
    client = Client()
    if access_token is None:
        authorize_url = client.authorization_url(
            client_id=client_id,
            redirect_uri='http://localhost:8282/authorized',
            scope='view_private,write')
        logging.info("Go to %s" % (authorize_url))
        code = raw_input("Code: ")
        client.access_token = client.exchange_code_for_token(
            client_id=client_id, client_secret=client_secret, code=code)
        logging.info("Access Token = %s" % (client.access_token))
    else:
        client.access_token = access_token

    return client
def main():
    global leader_list

    client = Client()
    authorize_url = client.authorization_url(
        client_id=16694, redirect_uri='http://localhost:8282/authorized')

    access_token = '1a424f23c2b57360dab45e720a9a45bd0868f299'

    client.access_token = access_token
    rex = client.get_athlete(168768)
    abdul = client.get_athlete(9954274)
    addison = client.get_athlete(3070847)
    jd = client.get_athlete(2903427)

    leaders = client.get_segment_leaderboard(7769406)
    for leader in leaders:
        name = (str(leader.athlete_name))
        leader_list.append(name)
    print(leader_list)
Beispiel #27
0
def main():
    user_id = input("user id: ")
    access_token = input("access token: ")
    client = Client(access_token)

    #Build url or authorizing app
    url = client.authorization_url(
        client_id=user_id,
        redirect_uri='http://127.0.0.1:5000/authorization',
        approval_prompt='auto',
        scope='activity:read_all')
    print(url)

    #Extract access code from url response
    access_code = input("access code: ")
    client_secret = input("client secret: ")

    #Get permanent access token
    permanent_access_token = client.exchange_code_for_token(
        user_id, client_secret, access_code)
    print(permanent_access_token)
Beispiel #28
0
class StrvaSignIn(StravaAuthSignIn):
    def __init__(self):
        super(StrvaSignIn, self).__init__('Strava')
        self.StravaClient = Client()

    def authorize(self):
        return redirect(
            self.StravaClient.authorization_url(
                client_id=self.consumer_id,
                redirect_uri=self.get_callback_url()))

    def callback(self):
        if 'code' not in request.args:
            return None
        access_token = self.StravaClient.exchange_code_for_token(
            client_id=self.consumer_id,
            client_secret=self.consumer_secret,
            code=request.args['code'])
        social_id = session['social_id']
        user = User.query.filter_by(social_id=social_id).first()
        user.stravatoken = access_token
        self.StravaClient.access_token = access_token
        user.athlete_id = self.StravaClient.get_athlete().id
        db.session.commit()
        a = Athlete.query.get(user.athlete_id)
        if a is None:
            dbathlete = Athlete(
                id=user.athlete_id,
                stravatoken=access_token,
                firstname=self.StravaClient.get_athlete().firstname,
                lastname=self.StravaClient.get_athlete().lastname)
            db.session.add(dbathlete)
        else:
            dbathlete = Athlete.query.filter_by(id=user.athlete_id).first()
            dbathlete.stravatoken = access_token
            dbathlete.firstname = self.StravaClient.get_athlete().firstname
            dbathlete.lastname = self.StravaClient.get_athlete().lastname
            db.session.add(dbathlete)
        db.session.commit()
        return (user, self.StravaClient.get_athlete())
Beispiel #29
0
        i += 1

    print('{} activities written to mongodb'.format(i))


# id and port info
client_id = open('client.id')
client_secret = os.environ['STRAVA_CLIENT_SECRET']
access_token = os.environ['STRAVA_ACCESS_TOKEN']
port = 5000
url = 'http://localhost:%d/authorized' % port

if __name__ == '__main__':
    # initialize stravalib client
    client = Client()
    authorize_url = client.authorization_url(client_id=client_id,
                                             redirect_uri=url)

    # get athlete
    client.access_token = access_token
    athlete = get_athlete(client)

    # get activities for athlete
    activities = get_activities(client, limit=10)

    # initiate mongo database, connect, make collection
    db_client = MongoClient(
        'localhost', 27017)  # Establish connection to persistent storage
    db = db_client.Strava  # Access/Initiate Database
    coll_name = '{}_{}_user'.format(athlete.firstname, athlete.lastname)
    collection = db[coll_name]
Beispiel #30
0
			if "code" in q:
				# Add the resulting code to global array
				# checked by the while loop below.
				code.extend(q["code"])
			self.send_response(200)
			self.end_headers()
			self.wfile.write("Thanks! Now go back to your terminal. :-)")
		else:
			self.send_error(404)

# Port doesn't matter so let the kernel pick one.
httpd = SocketServer.TCPServer(("", 0), Handler)
port = httpd.server_address[1]

authorize_url = client.authorization_url(
	client_id=APP["id"],
	redirect_uri="http://localhost:%d/authorized" % port,
	scope="write")

print "Now open the following URL and authorise this application."
print "Then Strava should send you to a localhost:%d URL handled by this script." % port
print "If that fails, rerun this script passing the code= value as an argument."
print
print authorize_url

# "code" gets updated once Strava calls us back.
while not code:
	httpd.handle_request()

access_token = client.exchange_code_for_token(
	client_id=APP["id"],
	client_secret=APP["client_secret"], code=code)
Beispiel #31
0
class Strava(object):
    def __init__(self):
        self.client_id = current_app.config['STRAVA_CLIENT_ID']
        self.client_secret = current_app.config['STRAVA_CLIENT_SECRET']
        self.redirect_uri = url_for('strava.confirm_auth', _external=True)

        self.client = StravaClient()

        self._activity_type = 'ride'  # rides or runs
        self._activities = None

    @property
    def activity_type(self):
        return self._activity_type

    @activity_type.setter
    def activity_type(self, value):
        self._activity_type = value
        self._activities = None

    @property
    def athlete(self):
        return self.client.get_athlete()

    @property
    def activities(self):
        if not self._activities:
            # current_year = datetime.datetime.now().year
            # after = datetime.datetime(current_year - 2, 12, 25)
            self._activities = Activities(self.client.get_activities(),
                                          self.activity_type)
        return self._activities

    @classmethod
    def authorization_url(cls):
        self = cls()
        return self.client.authorization_url(client_id=self.client_id,
                                             redirect_uri=self.redirect_uri)

    def get_access_token(self, code):
        return self.client.exchange_code_for_token(
            client_id=self.client_id,
            client_secret=self.client_secret,
            code=code)

    @classmethod
    def athlete_by_code(cls, code):
        self = cls()
        self.client.access_token = self.get_access_token(code)
        return self.athlete

    @classmethod
    def athlete_by_token(cls, token):
        self = cls()
        self.client.access_token = token
        return self.athlete

    @classmethod
    def activities_by_token(cls, token):
        self = cls()
        self.client.access_token = token
        return self.activities

    @classmethod
    def by_token(cls, token):
        self = cls()
        self.client.access_token = token
        return self
Beispiel #32
0
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Authenticate to the Strava API."""
    from stravalib.client import Client

    hass.http.register_view(StravaAuthCallbackView())

    client_id = config.get(CONF_CLIENT_ID)
    client_secret = config.get(CONF_CLIENT_SECRET)

    client = Client()

    config_path = hass.config.path(STRAVA_CONFIG_PATH)

    @asyncio.coroutine
    def _read_config():
        if not os.path.isfile(config_path):
            return None
        with open(config_path, 'r') as auth_file:
            config = json.load(auth_file)
            if config['client_id'] == client_id:
                return config['access_token']

    @asyncio.coroutine
    def _write_config():
        with open(config_path, 'w') as auth_file:
            json.dump(
                {
                    'client_id': client_id,
                    'access_token': client.access_token,
                }, auth_file)

    @asyncio.coroutine
    def _add_device():
        strava = StravaSensor(hass, client)
        yield from strava.async_update()
        return async_add_devices([strava])

    access_token = yield from _read_config()
    if access_token is not None:
        client.access_token = access_token
        yield from _add_device()
    else:
        callback_url = '{}{}'.format(hass.config.api.base_url,
                                     StravaAuthCallbackView.url)
        authorize_url = client.authorization_url(client_id=client_id,
                                                 redirect_uri=callback_url)

        configurator = hass.components.configurator
        request_id = configurator.async_request_config(
            'Strava',
            description='Authorization required for Strava account.',
            link_name='Authorize Home Assistant',
            link_url=authorize_url,
            entity_picture='/local/images/logo_strava.png')

    @asyncio.coroutine
    def initialize_callback(code):
        """Handle OAuth callback from Strava authorization flow."""
        client.access_token = client.exchange_code_for_token(
            client_id=client_id, client_secret=client_secret, code=code)
        yield from _write_config()
        yield from _add_device()
        configurator.async_request_done(request_id)

    hass.data[DATA_CALLBACK] = initialize_callback
    return True
Beispiel #33
0
def get_strava_url():
    client = Client()
    cid = app.config['STRAVA_CLIENT_ID']
    redirect = app.config['STRAVA_REDIRECT']
    url = client.authorization_url(client_id=cid, redirect_uri=redirect)
    print(url)
from stravalib.client import Client

client_id = 26296  # Replace this ID
client = Client()
url = client.authorization_url(
    client_id=client_id,
    redirect_uri='http://127.0.0.1:8000/authorization',
    scope='view_private')
print(url)
Beispiel #35
0
import configparser
from stravalib.client import Client

cfg = configparser.ConfigParser()
cfg._interpolation = configparser.ExtendedInterpolation()

cfg.read("token_id.ini")

cfg.sections()
cfg.items('strava')
token_entry = cfg.get('strava', 'token_entry')
clientid = cfg.get('strava', 'clientid')
activity = cfg.get('strava', 'activity')

client = Client()
authorize_url = client.authorization_url(
    clientid, redirect_uri='http://127.0.0.0.0:8100/authorized')
# Have the user click the authorization URL, a 'code' param will be added to the redirect_uri

client = Client(access_token=token_entry)

# Currently-authenticated (based on provided token) athlete
curr_athlete = client.get_athlete()  # This is now me

# Saying hello
athlete = client.get_athlete()
print("Hello, {}".format(athlete.firstname))

# Showing the friends
athlete = client.get_athlete_clubs()
for a in athlete:
    print("{} is your club.".format(a))
Beispiel #36
0
''' Script to grab activities from strava '''

import sys
import stravalib
from stravalib.client import Client
from configparser import SafeConfigParser

config = SafeConfigParser()
config.read('config.yaml')

client = Client()
authorize_url = client.authorization_url(
    client_id=config.get('strava', 'client_id'),
    redirect_uri='http://localhost:8282/authorized')
# Extract the code from your webapp response
# access_token = client.exchange_code_for_token(client_id=config.get('strava', 'client_id'), client_secret=config.get('strava', 'client_secret'), code=config.get('strava', 'code'))

# Now store that access token somewhere (a database?)
client.access_token = config.get('strava', 'Bearer')
athlete = client.get_athlete()

activities = client.get_activities(after="2017-11-17T00:00:00Z", limit=15)
activity_data = []
for activity in activities:
    activity_stream = client.get_activity_streams(activity.id,
                                                  types=['latlng', 'distance'])
    activity_data.append(activity_stream['latlng'].data)
    # get a strava client
    client = StravaClient()
    
    # if we haven't authorized yet, let's do it:
    if not token:
        # get token from strava
        client_id = cfg.get("StravaClient", "ClientId")
        client_secret = cfg.get("StravaClient", "ClientSecret")
        port = int(cfg.get("Application", "Port"))
        
        # setup webserver for authentication redirect
        httpd = http.server.HTTPServer(('127.0.0.1', port), AuthHandler)

        # The url to authorize from
        authorize_url = client.authorization_url(client_id=client_id, redirect_uri='http://localhost:{port}/authorized'.format(port=port), scope='view_private,write')
        # Open the url in your browser
        webbrowser.open(authorize_url, new=0, autoraise=True)

        # wait until you click the authorize link in the browser
        httpd.handle_request()
        code = httpd.code

        # Get the token
        token = client.exchange_code_for_token(client_id=client_id, client_secret=client_secret, code=code)

        # Now store that access token in the config
        cfg.set("UserAcct", "Token", token)
        with open("stravamng.cfg", "w") as cfg_file:
            cfg.write(cfg_file)
Beispiel #38
0
#                                               client_secret=MY_STRAVA_CLIENT_SECRET,
#                                               code=code)

from stravalib.client import Client

# test = np.load('/home/lgum/BitBucket/STRONZO/efforts.npz')

with open('/home/lgum/BitBucket/STRONZO/credentials.json', 'r') as credentials_file:
    credentials = json.load(credentials_file)


client = Client()

# authorize_url = client.authorization_url(client_id=10889082,
#                                redirect_uri='http://localhost:8282/authorized')
authorize_url = client.authorization_url(client_id=credentials['client_id'],
                               redirect_uri='http://localhost:8282/authorized')
# Have the user click the authorization URL, a 'code' param will be added to the redirect_uri
# .....
# Extract the code from your webapp response
# code = requests.get('code') # or whatever your framework does

access_token = str(credentials['access_token'])

# Now store that access token somewhere (a database?)
client.access_token = access_token
athlete = client.get_athlete()

# datetime.datetime(2005, 7, 14, 12, 30)
# start = datetime.datetime(2015, 10, 1, 0, 0)
# end = datetime.datetime(2015, 11, 20, 0, 0)
Beispiel #39
0
class Strava(object):
    def __init__(self):
        self.client_id = current_app.config['STRAVA_CLIENT_ID']
        self.client_secret = current_app.config['STRAVA_CLIENT_SECRET']
        self.redirect_uri = url_for('strava.confirm_auth', _external=True)

        self.client = StravaClient()

        self._activity_type = 'ride'  # rides or runs
        self._activities = None

    @property
    def activity_type(self):
        return self._activity_type

    @activity_type.setter
    def activity_type(self, value):
        self._activity_type = value
        self._activities = None

    @property
    def athlete(self):
        return self.client.get_athlete()

    @property
    def activities(self):
        if not self._activities:
            # current_year = datetime.datetime.now().year
            # after = datetime.datetime(current_year - 2, 12, 25)
            self._activities = Activities(self.client.get_activities(), self.activity_type)
        return self._activities

    @classmethod
    def authorization_url(cls):
        self = cls()
        return self.client.authorization_url(client_id=self.client_id,
                                             redirect_uri=self.redirect_uri)

    def get_access_token(self, code):
        return self.client.exchange_code_for_token(client_id=self.client_id,
                                                   client_secret=self.client_secret,
                                                   code=code)

    @classmethod
    def athlete_by_code(cls, code):
        self = cls()
        self.client.access_token = self.get_access_token(code)
        return self.athlete

    @classmethod
    def athlete_by_token(cls, token):
        self = cls()
        self.client.access_token = token
        return self.athlete

    @classmethod
    def activities_by_token(cls, token):
        self = cls()
        self.client.access_token = token
        return self.activities

    @classmethod
    def by_token(cls, token):
        self = cls()
        self.client.access_token = token
        return self
Beispiel #40
0
def auth(request):
    client = Client()
    auth_link = client.authorization_url(5928,'https://elevation-challenge.herokuapp.com/auth_success/')
    return render(request, 'auth.html', {'leaderboard':get_leaderboard(), 'auth_link':auth_link})