-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_strava.py
More file actions
95 lines (71 loc) · 2.45 KB
/
auth_strava.py
File metadata and controls
95 lines (71 loc) · 2.45 KB
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 webbrowser
from stravalib.client import Client
from flask import Flask, request
import os
from dotenv import load_dotenv
import threading
import time
# Define your client ID and secret
load_dotenv()
client_id = os.getenv("STRAVA_CLIENT_ID")
client_secret = os.getenv("STRAVA_CLIENT_SECRET")
# Define the scope
request_scope = ["read_all", "activity:read_all", "activity:write"]
# Set a redirect URL
redirect_url = "http://127.0.0.1:5000/authorization"
# Create a client object
client = Client()
# Create Flask app
app = Flask(__name__)
# Global variable to store the authorization code
auth_code = None
@app.route("/authorization")
def authorization():
global auth_code
code = request.args.get("code")
if code:
auth_code = code
return "Authorization successful! You can close this window."
return "Authorization failed. Please try again."
def run_flask():
app.run(port=5000)
# Start Flask server in a separate thread
flask_thread = threading.Thread(target=run_flask)
flask_thread.daemon = True
flask_thread.start()
# Generate the authorization URL
url = client.authorization_url(
client_id=client_id, redirect_uri=redirect_url, scope=request_scope
)
# Open the URL in a web browser
webbrowser.open(url)
# Wait for the authorization code
while auth_code is None:
time.sleep(0.1)
# Exchange the code for an access token
token_response = client.exchange_code_for_token(
client_id=client_id, client_secret=client_secret, code=auth_code
)
# Use the access token to interact with Strava
client.access_token = token_response["access_token"]
# Save the tokens to .env file
def update_env_file(token_data):
env_path = ".env"
if not os.path.exists(env_path):
print("Error: .env file not found")
return
with open(env_path, "r") as f:
lines = f.readlines()
with open(env_path, "w") as f:
for line in lines:
if line.startswith("STRAVA_ACCESS_TOKEN="):
f.write(f"STRAVA_ACCESS_TOKEN={token_data['access_token']}\n")
elif line.startswith("STRAVA_REFRESH_TOKEN="):
f.write(f"STRAVA_REFRESH_TOKEN={token_data['refresh_token']}\n")
elif line.startswith("STRAVA_TOKEN_EXPIRES_AT="):
f.write(f"STRAVA_TOKEN_EXPIRES_AT={token_data['expires_at']}\n")
else:
f.write(line)
# Update the .env file with the new tokens
update_env_file(token_response)
print("Successfully authenticated with Strava!")