-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtest_client.py
122 lines (94 loc) · 4.68 KB
/
test_client.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
from requests_oauthlib import OAuth2Session
from flask import Flask, request, redirect, session, url_for
from flask.json import jsonify
from oauthlib.oauth2.rfc6749.errors import TokenExpiredError
import logging
import os
import argparse
logger = logging.getLogger(__name__)
app = Flask(__name__)
# This information is obtained upon registration for the komoot-connect beta program.
client_id = None
client_secret = None
base_url = None
# must match the host and port of this application (step 2)
redirect_uri = 'http://localhost:5000/callback'
@app.route("/")
def index():
"""Step 1: User Authorization.
Redirect the user/resource owner to the OAuth provider (komoot)
using an URL with a few key OAuth parameters.
"""
authorization_base_url = base_url + 'oauth/authorize'
oauth_session = OAuth2Session(client_id, redirect_uri=redirect_uri)
authorization_url, state = oauth_session.authorization_url(authorization_base_url)
# State is used to prevent CSRF, keep this for later.
logger.info("authorization url: {} state: {}".format(authorization_url, state))
session['oauth_state'] = state
return redirect(authorization_url)
# Step 2: User authorization, this happens on the provider.
@app.route("/callback", methods=["GET"])
def callback():
""" Step 2: Retrieving an access token.
The user has been redirected back from the provider to your registered
callback URL. With this redirection comes an authorization code included
in the redirect URL. We will use that to obtain an access token.
"""
# Requests oauth2 credentials (refresh-token, access-token, username)
# Request uses Basic Authentication with client_id and client_secret
token_url = base_url + 'oauth/token'
if len(session) == 0:
raise ValueError("Cookie session is empty: {}".format(session))
oauth_session = OAuth2Session(client_id, redirect_uri=redirect_uri, state=session['oauth_state'])
token = oauth_session.fetch_token(token_url, username=client_id, password=client_secret,
authorization_response=request.url)
# At this point you can fetch protected resources but lets save
# the token and show how this is done from a persisted token
# in /profile.
session['oauth_token'] = token
return redirect(url_for('.profile'))
@app.route("/profile", methods=["GET"])
def profile():
""" Step 3: Fetching a protected resource using an OAuth 2 token.
"""
if not 'oauth_token' in session:
return redirect(url_for('.index'))
token_url = base_url + 'oauth/token'
oauth_session = OAuth2Session(client_id, token=session['oauth_token'])
# the username is needed for most requests and therefore in the token response
username = session['oauth_token']['username']
# fetch json document from main api
try:
response = oauth_session.get('https://external-api.komoot.de/v007/users/{}/tours/'.format(username))
except TokenExpiredError:
# access_token has expired, refresh
# Check 'expires_in' property before sending the request and act on 401 "error"="invalid_token"
# Request uses Basic Authentication with client_id and client_secret
new_token = oauth_session.refresh_token(token_url, refresh_token=session['oauth_token']['refresh_token'], auth=(client_id, client_secret))
# retry request
oauth_session = OAuth2Session(client_id, token=new_token)
session['oauth_token'] = new_token
url = 'https://external-api.komoot.de/v007/users/{}/tours/'.format(username)
response = oauth_session.get(url, headers={'Accept': 'application/hal+json'})
tours = response.json()
return jsonify(tours)
if __name__ == "__main__":
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
# Enable logging of all requests: headers, bodies, responses
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
parser = argparse.ArgumentParser(description='komoot oauth2 test client.')
parser.add_argument('--client-id', dest='cid', help='client id you got from komoot')
parser.add_argument('--client-secret', dest='csecret', help='client secret you got from komoot')
parser.add_argument('--base-url', dest='baseurl', default='https://auth-api.main.komoot.net/', help='base url for authentication requests')
args = parser.parse_args()
client_id = args.cid
client_secret = args.csecret
base_url = args.baseurl
# Since this is a test client running on localhost: Don't enforce SSL.
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
os.environ['DEBUG'] = "1"
app.secret_key = os.urandom(24)
app.run(debug=True)