Update strava_auth.py

This commit is contained in:
oldnapalm
2024-03-23 10:46:24 -03:00
parent 6d50cc1744
commit 77370c9362
+32 -47
View File
@@ -16,78 +16,64 @@ Example Usage:
presented in the browser after the exchange. Save this value into your config (e.g. into your test.ini) to run
functional tests.
"""
from __future__ import unicode_literals, absolute_import, print_function
from six.moves.BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import os
import sys
import argparse
from six.moves.urllib import parse as urlparse
import threading
import logging
import six
from socketserver import ThreadingTCPServer
from http.server import SimpleHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
from stravalib import Client
import os, sys
if getattr(sys, 'frozen', False):
# If we're running as a pyinstaller bundle
SCRIPT_DIR = os.path.dirname(sys.executable)
else:
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
class StravaAuthHTTPServer(HTTPServer):
class StravaAuthHTTPServer(ThreadingTCPServer):
def __init__(self, server_address, RequestHandlerClass, client_id, client_secret, bind_and_activate=True):
HTTPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate=bind_and_activate)
def __init__(self, server_address, RequestHandlerClass, client_id, client_secret):
ThreadingTCPServer.__init__(self, server_address, RequestHandlerClass)
self.logger = logging.getLogger('auth_server.http')
self.client_id = client_id
self.client_secret = client_secret
self.listening_event = threading.Event()
def serve_forever(self, *args, **kwargs):
self.listening_event.set()
return HTTPServer.serve_forever(self, *args, **kwargs)
class RequestHandler(BaseHTTPRequestHandler):
class RequestHandler(SimpleHTTPRequestHandler):
def do_GET(self):
request_path = self.path
parsed_path = urlparse.urlparse(request_path)
client = Client()
if request_path.startswith('/authorization'):
if self.path.startswith('/authorization'):
self.send_response(200)
self.send_header(six.b("Content-type"), six.b("text/html"))
self.send_header("Content-type", "text/html")
self.end_headers()
code = urlparse.parse_qs(parsed_path.query).get('code')
code = parse_qs(urlparse(self.path).query).get('code')
if code:
code = code[0]
token_response = client.exchange_code_for_token(client_id=self.server.client_id,
client_secret=self.server.client_secret,
code=code)
client_secret=self.server.client_secret,
code=code)
access_token = token_response['access_token']
refresh_token = token_response['refresh_token']
expires_at = token_response['expires_at']
self.server.logger.info("Exchanged code {} for access token {}".format(code, access_token))
self.wfile.write(six.b("<html><head><script>function download() {"))
self.wfile.write(six.b("var text = `{}\n".format(self.server.client_id)))
self.wfile.write(six.b("{}\n".format(self.server.client_secret)))
self.wfile.write(six.b("{}\n".format(access_token)))
self.wfile.write(six.b("{}\n".format(refresh_token)))
self.wfile.write(six.b("{}\n`;".format(expires_at)))
self.wfile.write(six.b("var pom = document.createElement('a');"))
self.wfile.write(six.b("pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));"))
self.wfile.write(six.b("pom.setAttribute('download', 'strava_token.txt');"))
self.wfile.write(six.b("pom.style.display = 'none'; document.body.appendChild(pom);"))
self.wfile.write(six.b("pom.click(); document.body.removeChild(pom); }"))
self.wfile.write(six.b("</script></head><body>Access token obtained successfully<br><br>"))
self.wfile.write(six.b("<button onclick=\"download()\">Download</button></body></html>"))
self.wfile.write("<html><head><script>function download() {".encode())
self.wfile.write("var text = `{}\n".format(self.server.client_id).encode())
self.wfile.write("{}\n".format(self.server.client_secret).encode())
self.wfile.write("{}\n".format(access_token).encode())
self.wfile.write("{}\n".format(refresh_token).encode())
self.wfile.write("{}\n`;".format(expires_at).encode())
self.wfile.write("var pom = document.createElement('a');".encode())
self.wfile.write("pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));".encode())
self.wfile.write("pom.setAttribute('download', 'strava_token.txt');".encode())
self.wfile.write("pom.style.display = 'none'; document.body.appendChild(pom);".encode())
self.wfile.write("pom.click(); document.body.removeChild(pom); }".encode())
self.wfile.write("</script></head><body>Access token obtained successfully<br><br>".encode())
self.wfile.write("<button onclick=\"download()\">Download</button></body></html>".encode())
with open('%s/strava_token.txt' % SCRIPT_DIR, 'w') as f:
f.write(str(self.server.client_id) + '\n')
f.write(self.server.client_secret + '\n')
@@ -96,17 +82,17 @@ class RequestHandler(BaseHTTPRequestHandler):
f.write(str(expires_at) + '\n')
else:
self.server.logger.error("No code param received.")
self.wfile.write(six.b("ERROR: No code param recevied.\n"))
self.wfile.write("ERROR: No code param recevied.\n".encode())
else:
url = client.authorization_url(client_id=self.server.client_id,
redirect_uri='http://localhost:{}/authorization'.format(self.server.server_port),
redirect_uri='http://localhost:{}/authorization'.format(self.server.server_address[1]),
scope=['activity:write'])
self.send_response(302)
self.send_header(six.b("Content-type"), six.b("text/plain"))
self.send_header("Content-type", "text/plain")
self.send_header('Location', url)
self.end_headers()
self.wfile.write(six.b("Redirect to URL: {}\n".format(url)))
self.wfile.write("Redirect to URL: {}\n".format(url).encode())
def main(port, client_id, client_secret):
@@ -126,9 +112,8 @@ if __name__ == "__main__":
parser.add_argument('-p', '--port', help='Which port to bind to',
action='store', type=int, default=8000)
parser.add_argument('--client-id', help='Strava API Client ID',
action='store', default=28117)
action='store', type=int, default=28117)
parser.add_argument('--client-secret', help='Strava API Client Secret',
action='store', default='41b7b7b76d8cfc5dc12ad5f020adfea17da35468')
args = parser.parse_args()