-
Notifications
You must be signed in to change notification settings - Fork 0
/
strava_auth.py
95 lines (73 loc) · 2.61 KB
/
strava_auth.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import streamlit as st
import requests
from os import getenv
from dotenv import load_dotenv
from requests_oauthlib import OAuth2Session
from utils import get_url_from_s3
from datetime import datetime
load_dotenv()
CLIENT_ID = getenv("CLIENT_ID")
CLIENT_SECRET = getenv("CLIENT_SECRET")
S3_BUCKET_IMAGE = getenv("S3_BUCKET_IMAGE")
REDIRECT = (
"https://strava-marathon-prep.streamlit.app/"
if getenv("ENV") == "production"
else "http://localhost:8501/"
)
AUTH_URL = f"https://www.strava.com/oauth/authorize?client_id={CLIENT_ID}&redirect_uri={REDIRECT}&response_type=code&approval_prompt=auto&scope=activity:read_all,"
# STRAVA API GUIDELINES
# https://developers.strava.com/guidelines/
def authentication_needed():
current_time = datetime.now()
if "time" in st.session_state:
# Strava access token expires after 6 hours
time_difference = current_time - st.session_state.time
if time_difference.seconds > 21600:
authenticate()
elif "strava_auth" not in st.session_state:
authenticate()
def authenticate():
try:
# STRAVA REQUIRED - clickable image button
# 1.1 Connect with Strava buttons
image_url = get_url_from_s3(usage="auth")
content = f"""
<a href="{AUTH_URL}" id="image_link">
<img src="{image_url}">
</a>
"""
st.markdown(content, unsafe_allow_html=True)
# Parse query parameters from URL
query_code = st.query_params.get_all(key="code")
# Create session variable
session = strava_oauth_session(query_code)
if session is not None:
st.session_state.strava_auth = session
st.session_state.time = datetime.now()
st.rerun()
except Exception as e:
print(e)
def strava_oauth_session(query_code):
# If code is present in query parameters, exchange it for an access token
access_token = exchange_code_for_token(query_code)
if access_token:
# Create session variable
session = OAuth2Session(
client_id=CLIENT_ID,
redirect_uri=REDIRECT,
token={"access_token": access_token},
)
return session
def exchange_code_for_token(code):
token_url = "https://www.strava.com/oauth/token"
payload = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"code": code,
"grant_type": "authorization_code",
}
response = requests.post(token_url, data=payload)
if response.status_code == 200:
return response.json()["access_token"]
else:
print(response.status_code)