-
Notifications
You must be signed in to change notification settings - Fork 0
/
flask_spotify_auth.py
43 lines (34 loc) · 1.57 KB
/
flask_spotify_auth.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
import base64, json, requests
SPOTIFY_URL_AUTH = 'https://accounts.spotify.com/authorize/?'
SPOTIFY_URL_TOKEN = 'https://accounts.spotify.com/api/token/'
RESPONSE_TYPE = 'code'
HEADER = 'application/x-www-form-urlencoded'
REFRESH_TOKEN = ''
def getAuth(client_id, redirect_uri, scope):
data = "{}client_id={}&response_type=code&redirect_uri={}&scope={}".format(SPOTIFY_URL_AUTH, client_id, redirect_uri, scope)
return data
def getToken(code, client_id, client_secret, redirect_uri):
body = {
"grant_type": 'authorization_code',
"code" : code,
"redirect_uri": redirect_uri,
"client_id": client_id,
"client_secret": client_secret
}
auth_str = bytes('{}:{}'.format(client_id, client_secret), 'utf-8')
encoded = base64.b64encode(auth_str).decode('utf-8')
headers = {"Content-Type" : HEADER, "Authorization" : "Basic {}".format(encoded)}
post = requests.post(SPOTIFY_URL_TOKEN, params=body, headers=headers)
return handleToken(json.loads(post.text))
def handleToken(response):
auth_head = {"Authorization": "Bearer {}".format(response["access_token"])}
REFRESH_TOKEN = response["refresh_token"]
return [response["access_token"], auth_head, response["scope"], response["expires_in"]]
def refreshAuth():
body = {
"grant_type" : "refresh_token",
"refresh_token" : REFRESH_TOKEN
}
post_refresh = requests.post(SPOTIFY_URL_TOKEN, data=body, headers=HEADER)
p_back = json.dumps(post_refresh.text)
return handleToken(p_back)