-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoauth_server.py
More file actions
86 lines (74 loc) · 2.33 KB
/
oauth_server.py
File metadata and controls
86 lines (74 loc) · 2.33 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
import os
import json
from urllib.parse import urlencode
import requests
from dotenv import load_dotenv
from flask import Flask, redirect, request, render_template
import requests.auth
# load env variables here
load_dotenv()
CLIENT_ID = os.getenv("SPOTIFY_CLIENT_ID")
CLIENT_SECRET = os.getenv("SPOTIFY_CLIENT_SECRETE")
REDIRECT_URL = os.getenv("SPOTIFY_REDIRECT_URI")
SCOPE= "user-library-read playlist-modify-private playlist-modify-public user-read-email"
URL = "https://accounts.spotify.com/"
TOKENS_PATH = "user_token.json"
app = Flask(__name__)
def save_tokens(token):
with open(TOKENS_PATH, 'w') as file:
json.dump(token, file, indent=3)
def load_tokens():
if os.path.exists(TOKENS_PATH):
return json.load(open(TOKENS_PATH))
return {}
@app.route('/')
def login():
endpoint = 'authorize?'
params = {
'client_id': CLIENT_ID,
'response_type': 'code',
'scope': SCOPE,
'redirect_uri': REDIRECT_URL
}
url = URL + endpoint + urlencode(params)
return redirect(url)
@app.route('/callback')
def callback():
endpoint = "api/token"
url = URL + endpoint
code = request.args.get('code')
if not code:
print(code)
return "Missing code", 400
payload = {
'grant_type': "authorization_code",
"code": code,
"redirect_uri": REDIRECT_URL
}
auth_header = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
res = requests.post(url=url, data=payload, auth=auth_header)
if res.raise_for_status():
return "Authentication failed"
tokens = res.json()
save_tokens(tokens)
return render_template("index.html")
@app.route("/refresh")
def refresh():
endpoint = 'api/token'
url = URL + endpoint
old_tokens = load_tokens()["refresh_token"]
payload = {
"grant_type": "refresh_token",
"refresh_token": old_tokens,
"client_id": CLIENT_ID
}
auth_header = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
res = requests.post(url=url, data=payload, auth=auth_header)
if res.raise_for_status():
return "An error occured"
new_tokens = res.json()
new_tokens["refresh_token"] = new_tokens.get("refresh_token",old_tokens)
save_tokens(new_tokens)
return render_template("refresh.html")
if __name__ == "__main__":
app.run(port=8888)