Strava token

The missing part of the puzzle to make those Strava imports work is to get a Strava token for each user and store it in our user table.

As said earlier, this can be done via an OAuth2 dance where the connected user is redirected to Strava to authorize Runnerly, then redirected back to Runnerly with an OAuth2 code that can be converted into a token we can store.

The stravalib library provides some helpers to perform that dance. The first one is the authorization_url() method, which returns a full URL that can be presented to the users to initiate the OAuth2 dance:

    app.config['STRAVA_CLIENT_ID'] = 'runnerly-strava-id' 
app.config['STRAVA_CLIENT_SECRET'] = 'runnerly-strava-secret'

def get_strava_auth_url():
client = Client()
client_id = app.config['STRAVA_CLIENT_ID']
redirect = 'http://127.0.0.1:5000/strava_auth'
url = client.authorization_url(client_id=client_id,
redirect_uri=redirect)
return url

In the example, redirect is the URL Strava that will redirect once the application is granted access. In this example, it's the app running locally. The get_strava_auth_url() method can be used to present a link to a connected Runnerly user.

Once the user authorizes Runnerly on the Strava site, the /strava_auth view will get a code that can be exchanged for a token that will stay valid for future Strava requests on behalf of that user. The stravalib library's Client class has an exchange_code_for_token() method to do the conversion.

The view then simply copies the token into the user database entry:

    @app.route('/strava_auth') 
@login_required
def _strava_auth():
code = request.args.get('code')
client = Client()
xc = client.exchange_code_for_token
access_token = xc(client_id=app.config['STRAVA_CLIENT_ID'],
client_secret=app.config['STRAVA_CLIENT_SECRET'], code=code)
current_user.strava_token = access_token
db.session.add(current_user)
db.session.commit()
return redirect('/')

In that view, @login_required and current_user are part of the authentication and authorization processes presented in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset