-
Notifications
You must be signed in to change notification settings - Fork 4
/
app.py
74 lines (61 loc) · 2.06 KB
/
app.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
from urllib import urlencode
from uuid import uuid4
import os
from flask import Flask, request
import requests
app = Flask(__name__)
API_BASE = os.environ.get('API_BASE', 'https://api.marvelapp.com')
CLIENT_ID = os.environ.get('CLIENT_ID')
CLIENT_SECRET = os.environ.get('CLIENT_SECRET')
REDIRECT_URI = os.environ.get('REDIRECT_URI')
@app.route('/')
def index():
connect_url = API_BASE + '/oauth/authorize/?' + urlencode({
'state': uuid4().hex,
'client_id': CLIENT_ID,
'response_type': 'code',
'scope': 'user:read',
'redirect_uri': REDIRECT_URI,
})
return '<html><a href=%s>Connect with Marvel</a></html>' % connect_url
@app.route('/redirect')
def redirect_handler():
assert 'error' not in request.args, request.args
# in the real world we should validate that `state` matches the state we set before redirecting the user
state = request.args.get('state')
# using the code we've just been given, make a request to obtain
# an access token for this user
code = request.args.get('code')
response = requests.post(API_BASE + '/oauth/token/', data={
'grant_type': 'authorization_code',
'code': code,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI,
})
assert response.ok, 'Token request failed: %s' % response.content
data = response.json()
token = data['access_token']
headers = {
'Authorization': 'Bearer %s' % token,
}
# now we can make API requests using this token in the headers
response = requests.post(API_BASE + '/graphql', json={
'query': '''
query {
user {
email
}
}
'''
}, headers=headers)
assert response.ok, 'Request to graphql API failed'
email = response.json()['data']['user']['email']
return '''
<html>
%s has authorised their Marvel account
Their access token is %s
</html>
''' % (email, token)
if __name__ == '__main__':
app.run(debug=True)