forked from plamere/spotify_token_swap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspotify_token_swap.py
75 lines (61 loc) · 2 KB
/
spotify_token_swap.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
import cherrypy
from cherrypy import tools
import simplejson as json
import requests
import os
import base64
from os.path import join, dirname
from dotenv import load_dotenv
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
ENVIRONMENT = os.environ.get('ENVIRONMENT', 'production')
CLIENT_ID = os.environ.get('CLIENT_ID')
CLIENT_SECRET = os.environ.get('CLIENT_SECRET')
CALLBACK_URL = os.environ.get('CALLBACK_URL')
SPOTIFY_TOKEN_URL = os.environ.get('SPOTIFY_TOKEN_URL', 'https://accounts.spotify.com/api/token')
AUTH_HEADER = 'Basic %s' % base64.b64encode('%s:%s' % (CLIENT_ID, CLIENT_SECRET))
class SpotifyTokenSwap(object):
@cherrypy.expose
@tools.json_out()
def swap(self, code=None):
headers = {
'Authorization': AUTH_HEADER
}
params = {
'grant_type': 'authorization_code',
'redirect_uri': CALLBACK_URL,
'code' : code
}
r = requests.post(SPOTIFY_TOKEN_URL, params, headers=headers)
cherrypy.response.status = r.status_code
return r.json()
@cherrypy.expose
@tools.json_out()
def refresh(self, refresh_token=None):
headers = {
'Authorization': AUTH_HEADER
}
params = {
'grant_type': 'refresh_token',
'refresh_token': refresh_token
}
r = requests.post(SPOTIFY_TOKEN_URL, params, headers=headers)
cherrypy.response.status = r.status_code
return r.json()
def CORS():
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
if __name__ == '__main__':
cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS)
root = SpotifyTokenSwap()
config = {
'global' : {
'server.socket_host' : '0.0.0.0',
'server.socket_port' : 9020,
'server.thread_pool' : 10,
'environment' : ENVIRONMENT,
},
'/' : {
'tools.CORS.on' : True,
}
}
cherrypy.quickstart(root, '/', config=config)