-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
192 lines (149 loc) · 5.41 KB
/
app.py
File metadata and controls
192 lines (149 loc) · 5.41 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
192
"""Python Flask WebApp Auth0 integration example
"""
import json
from time import time
from userModel import UserModel
from spotipy import Spotify
from os import environ as env
from urllib.parse import quote_plus, urlencode
from hashids import Hashids
from authlib.integrations.flask_client import OAuth
from dotenv import find_dotenv, load_dotenv
from flask import Flask, send_file, redirect, send_from_directory, session, request, jsonify, Response
from werkzeug.serving import run_simple
from werkzeug.middleware.dispatcher import DispatcherMiddleware
import mimetypes
from flask_cors import cross_origin
from meta.releases import Releases
from meta.metadata import Metadata
from dataModels.track import SpotifyTrack
mimetypes.init()
mimetypes.types_map['.js'] = 'application/javascript; charset=utf-8'
ENV_FILE = find_dotenv()
if ENV_FILE:
load_dotenv(ENV_FILE)
app = Flask(__name__)
app.secret_key = env.get("APP_SECRET_KEY")
ranHashids = Hashids(str(time()), 10)
UserModel.create_table(read_capacity_units=1, write_capacity_units=1)
oauth = OAuth(app)
oauth.register(
"auth0",
client_id=env.get("AUTH0_CLIENT_ID"),
client_secret=env.get("AUTH0_CLIENT_SECRET"),
client_kwargs={
"scope": "openid profile email",
},
server_metadata_url=f'https://{env.get("AUTH0_DOMAIN")}/.well-known/openid-configuration',
)
# Controllers API
@app.route("/callback", methods=["GET", "POST"])
def callback():
token = oauth.auth0.authorize_access_token()
session["user"] = token
return redirect("/")
@app.route("/login")
def login():
return oauth.auth0.authorize_redirect(
redirect_uri = "https://reaudioplayer.tk/callback"
)
@app.route("/logout")
def logout():
session.clear()
return redirect(
"https://" + env.get("AUTH0_DOMAIN")
+ "/v2/logout?"
+ urlencode(
{
"returnTo": "https://reaudioplayer.tk/",
"client_id": env.get("AUTH0_CLIENT_ID"),
},
quote_via=quote_plus,
)
)
@app.route("/spotify/album", methods = ["POST"])
def spotifyAlbum():
token = request.json.get("accessToken")
spotify = Spotify(token)
tracks = SpotifyTrack.FromAlbum(spotify, request.json.get("albumId"))
metadatas = [ Metadata(spotify, track.url) for track in tracks ]
return jsonify([ metadata.toDict() for metadata in metadatas ])
@app.route("/spotify/releaseRadar", methods = ["POST"])
def releases():
token = request.json.get("accessToken")
spotify = Spotify(token)
return jsonify(Releases(spotify).toDict())
__accessTokens = { }
@app.route("/user/accessToken")
def getAccessToken():
user = session.get("user")
redirectTo = request.args.get('redirect')
if None in (user, redirectTo) or "<token>" not in redirectTo:
return redirect("/login")
find = next((token for (token, val) in __accessTokens.items() if val["access_token"] == user["access_token"]), None)
if find:
return redirect(redirectTo.replace("<token>", find))
token = ranHashids.encode(len(__accessTokens.values()))
__accessTokens[token] = user
return redirect(redirectTo.replace("<token>", token))
@app.route("/user/<accessToken>", methods = ["GET", "POST"])
@cross_origin()
def updateUserData(accessToken: str):
if not accessToken in __accessTokens:
return Response(status = 401)
user = __accessTokens[accessToken]
if request.method == "GET":
return prepareUserWithData(user)
_updateUserData(user, request.json)
return "success"
@app.route("/user", methods = ["GET", "POST"])
def getUser():
user = session.get("user")
if not user:
return Response("false", status = 401)
if request.method == "GET":
return prepareUserWithData(user)
_updateUserData(user, request.json)
return "success"
##
def _updateUserData(user: dict, data: dict):
name = user["userinfo"]["email"]
pw = user["userinfo"]["sub"]
query = f"\"username\" = '{name}' AND \"password\" = '{pw}'"
def toSetter(string: str) -> str:
return string.replace("'", "''")
return
with conn.cursor() as curs:
curs.execute('SELECT id FROM "UserDbs" WHERE ' + query)
row = curs.fetchone()
stringified = toSetter(json.dumps(data))
if row:
print("update existing")
curs.execute('UPDATE "UserDbs" SET data = \'' + stringified + '\' WHERE ' + query)
else:
print("create new")
query = f"('{name}', '{pw}', '{stringified}', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
curs.execute('INSERT INTO "UserDbs" (username, password, data, "createdAt", "updatedAt") VALUES ' + query)
conn.commit()
def prepareUserWithData(user: dict):
name = user["userinfo"]["email"]
pw = user["userinfo"]["sub"]
value = {
"user": user
}
for entry in UserModel.query(pw,
UserModel.username == name):
value["playlists"] = entry.playlists
value["tokens"] = entry.tokens.as_dict()
return value
@app.route('/assets/<path:path>')
def asset(path: str):
return send_from_directory('ui/dist/assets', path)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def wildcard(path: str):
#return path
return send_file('ui/dist/index.html')
app.wsgi_app = DispatcherMiddleware(run_simple, {'/default': app.wsgi_app})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=env.get("PORT", 3002))