-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
191 lines (151 loc) · 4.98 KB
/
app.py
File metadata and controls
191 lines (151 loc) · 4.98 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
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
''' Example of Spotify authorization code flow (refreshable user auth).
Displays profile information of authenticated user and access token
information that can be refreshed by clicking a button.
Basic flow:
-> '/'
-> Spotify login page
-> '/callback'
-> get tokens
-> use tokens to access API
Required environment variables:
FLASK_APP, CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, SECRET_KEY
More info:
https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow
'''
from flask import (
abort,
Flask,
make_response,
redirect,
render_template,
request,
session,
url_for,
)
import json
import logging
import os
import requests
import secrets
import string
from urllib.parse import urlencode
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(message)s', level=logging.DEBUG
)
# Client info
CLIENT_ID = os.getenv('CLIENT_ID')
CLIENT_SECRET = os.getenv('CLIENT_SECRET')
REDIRECT_URI = os.getenv('REDIRECT_URI')
# Spotify API endpoints
AUTH_URL = 'https://accounts.spotify.com/authorize'
TOKEN_URL = 'https://accounts.spotify.com/api/token'
ME_URL = 'https://api.spotify.com/v1/me'
# Start 'er up
app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/<loginout>')
def login(loginout):
'''Login or logout user.
Note:
Login and logout process are essentially the same. Logout forces
re-login to appear, even if their token hasn't expired.
'''
# redirect_uri can be guessed, so let's generate
# a random `state` string to prevent csrf forgery.
state = ''.join(
secrets.choice(string.ascii_uppercase + string.digits) for _ in range(16)
)
# Request authorization from user
scope = 'user-read-private user-read-email'
if loginout == 'logout':
payload = {
'client_id': CLIENT_ID,
'response_type': 'code',
'redirect_uri': REDIRECT_URI,
'state': state,
'scope': scope,
'show_dialog': True,
}
elif loginout == 'login':
payload = {
'client_id': CLIENT_ID,
'response_type': 'code',
'redirect_uri': REDIRECT_URI,
'state': state,
'scope': scope,
}
else:
abort(404)
res = make_response(redirect(f'{AUTH_URL}/?{urlencode(payload)}'))
res.set_cookie('spotify_auth_state', state)
return res
@app.route('/callback')
def callback():
error = request.args.get('error')
code = request.args.get('code')
state = request.args.get('state')
stored_state = request.cookies.get('spotify_auth_state')
# Check state
if state is None or state != stored_state:
app.logger.error('Error message: %s', repr(error))
app.logger.error('State mismatch: %s != %s', stored_state, state)
abort(400)
# Request tokens with code we obtained
payload = {
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI,
}
# `auth=(CLIENT_ID, SECRET)` basically wraps an 'Authorization'
# header with value:
# b'Basic ' + b64encode((CLIENT_ID + ':' + SECRET).encode())
res = requests.post(TOKEN_URL, auth=(CLIENT_ID, CLIENT_SECRET), data=payload)
res_data = res.json()
if res_data.get('error') or res.status_code != 200:
app.logger.error(
'Failed to receive token: %s',
res_data.get('error', 'No error information received.'),
)
abort(res.status_code)
# Load tokens into session
session['tokens'] = {
'access_token': res_data.get('access_token'),
'refresh_token': res_data.get('refresh_token'),
}
return redirect(url_for('me'))
@app.route('/refresh')
def refresh():
'''Refresh access token.'''
payload = {
'grant_type': 'refresh_token',
'refresh_token': session.get('tokens').get('refresh_token'),
}
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
res = requests.post(
TOKEN_URL, auth=(CLIENT_ID, CLIENT_SECRET), data=payload, headers=headers
)
res_data = res.json()
# Load new token into session
session['tokens']['access_token'] = res_data.get('access_token')
return json.dumps(session['tokens'])
@app.route('/me')
def me():
'''Get profile info as a API example.'''
# Check for tokens
if 'tokens' not in session:
app.logger.error('No tokens in session.')
abort(400)
# Get profile info
headers = {'Authorization': f"Bearer {session['tokens'].get('access_token')}"}
res = requests.get(ME_URL, headers=headers)
res_data = res.json()
if res.status_code != 200:
app.logger.error(
'Failed to get profile info: %s',
res_data.get('error', 'No error message returned.'),
)
abort(res.status_code)
return render_template('me.html', data=res_data, tokens=session.get('tokens'))