-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_user_profile.py
More file actions
386 lines (331 loc) · 13.5 KB
/
api_user_profile.py
File metadata and controls
386 lines (331 loc) · 13.5 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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
"""
This module provides supporting functions for API routes pertaining to user profiles.
"""
from flask import Blueprint, jsonify, request
import bcrypt
import constants
import db_query
import related_type_enum
import sql_query
user_profile_bp = Blueprint('user-profile', __name__)
@user_profile_bp.route("/api/user/profile")
def api_user_profile():
"""
Retrieves a user's profile information.
Example:
GET /api/user/profile?user=LastFmProfileName&partial=true
Returns JSON:
{
"userProfile": [
{ "id": int, "profile": str, "firstname": str, "lastname": str,
"email": str, "profileurl": str, "bootstrapped": int, "admin: int",
"lastlogin": str, "pfpsm": str, "pfpmed": str, "pfplg": str,
"pfpxl": str, "swag": int },
…
]
}
"""
user = request.args.get("user", "")
partial = request.args.get("partial", "false").lower() == "true"
if not user.strip():
return jsonify({"error": "Missing user parameter"}), 400
sql = """
SELECT User.UserID AS id, User.LastFmProfileName AS profile, User.FirstName AS firstname,
User.LastName AS lastname, User.EmailAddress AS email, LastFmProfileUrl AS profileurl,
User.BootstrappedUser AS bootstrapped, User.Admin AS admin, User.LastLogin AS lastlogin,
User.Pfpsmall AS pfpsm, User.PfpMedium as pfpmed, User.PfpLarge AS pfplg,
User.PfpExtraLarge AS pfpxl, User.Swag AS swag
FROM User
WHERE LastFmProfileName LIKE ?
ORDER BY LastFmProfileName
LIMIT 10
"""
conn = sql_query.get_db_connection()
if partial:
separator = "%"
search_term = separator + separator.join(user) + separator
else:
search_term = user
rows = conn.execute(sql, (search_term,)).fetchall()
conn.close()
if not rows and not partial:
return jsonify({"error": "Missing or invalid user"}), 400
user_profile = [
{
"id": row["id"],
"profile": row["profile"],
"firstname": row["firstname"],
"lastname": row["lastname"],
"email": row["email"],
"profileurl": row["profileurl"],
"bootstrapped": row["bootstrapped"],
"admin": row["admin"],
"lastlogin": row["lastlogin"],
"pfpsm": row["pfpsm"],
"pfpmed": row["pfpmed"],
"pfplg": row["pfplg"],
"pfpxl": row["pfpxl"],
"swag": row["swag"]
}
for row in rows
]
return jsonify({ "userProfile": user_profile })
@user_profile_bp.route("/api/user/get-users")
def api_user_get_users():
"""
Retrieves a list of user profiles.
Example:
GET /api/user/get-users?includebootstrapped=0&loggedinwithindays=7&search_term=&limit=50
Params:
includebootstrapped: 0 to exclude bootstrapped users, 1 to include them
loggedinwithindays: 0 for all, otherwise limit to number of days since user
has last logged in.
search_term: search for a matching user id, provided letters must be in correct order
limit: numeric value indicating the number of records to return
Returns JSON:
{
"userProfile": [
{
"id": int,
"profile": str,
"profileurl": str,
"bootstrapped": int,
"lastlogin": str,
"pfpsm": str,
"pfpmed": str,
"pfplg": str,
"pfpxl": str,
"swag": int
},
…
]
}
"""
includebootstrapped = request.args.get("includebootstrapped", "")
loggedinwithindays = request.args.get("loggedinwithindays", "")
search_term = request.args.get("search_term", "")
limit = request.args.get("limit", "")
# validate and set defaults
includebootstrapped = 0 if not includebootstrapped.isnumeric() else int(includebootstrapped)
loggedinwithindays = 0 if not loggedinwithindays.isnumeric() else int(loggedinwithindays)
limit = 50 if not limit.isnumeric() else int(limit)
sql = """
SELECT User.UserID AS id, User.LastFmProfileName AS profile,
User.LastFmProfileUrl AS profileurl, User.BootstrappedUser AS bootstrapped,
User.LastLogin AS lastlogin,
User.PfpSmall AS pfpsm, User.PfpMedium AS pfpmed,
User.PfpLarge AS pfplg, User.PfpExtraLarge AS pfpxl,
User.Swag AS swag
FROM User
WHERE 1=1
"""
if includebootstrapped != 1:
sql += """
AND BootstrappedUser = 0
"""
if loggedinwithindays != 0:
sql += f"""
AND LastLogin > DATE(CURRENT_TIMESTAMP, '-{loggedinwithindays} days')
"""
if search_term != "":
separator = "%"
search_term = separator + separator.join(search_term) + separator
sql += """
AND LastFmProfileName LIKE ?
"""
sql += """
ORDER BY User.LastFmProfileName
LIMIT ?
"""
conn = sql_query.get_db_connection()
if search_term != "":
rows = conn.execute(sql, (search_term, limit)).fetchall()
else:
rows = conn.execute(sql, (limit,)).fetchall()
conn.close()
users = [
{
"id": row["id"],
"profile": row["profile"],
"profileurl": row["profileurl"],
"bootstrapped": row["bootstrapped"],
"lastlogin": row["lastlogin"],
"pfpsm": row["pfpsm"],
"pfpmed": row["pfpmed"],
"pfplg": row["pfplg"],
"pfpxl": row["pfpxl"],
"swag": row["swag"]
}
for row in rows
]
return jsonify({ "userProfile": users })
@user_profile_bp.route("/api/user/create-profile", methods=['POST'])
def api_user_create_profile():
"""
Creates a user profile with provided data.
Example:
POST /api/user/create-profile?user=LastFmProfileName&firstname=fname
&lastname=lname&email=fname@domain.edu&password=pw&bootstrapped=n
Raises:
400 Bad Request: If the user already exists in the database (based on profile name).
400 Bad Request: If the user already exists in the database (based on email address).
400 Bad Request: If the user's email address is not provided.
400 Bad Request: If the user's first name is not provided.
400 Bad Request: If the user's last name is not provided.
400 Bad Request: If the user's password is not provided.
Returns:
201 Success: The database ID of the newly created user record.
"""
user = request.args.get("user", "")
first_name = request.args.get("firstname", "")
last_name = request.args.get("lastname", "")
email = request.args.get("email", "")
password = request.args.get("password", "")
bootstrapped = request.args.get("bootstrapped", "")
bootstrapped = 0 if bootstrapped == "" else int(bootstrapped)
user_id = sql_query.query_user_id(user)
user_id_by_email = sql_query.query_user_id_by_email(email)
if user_id != 0:
return jsonify({"error": "User with that profile name already exists"}), 400
if user_id_by_email != 0:
return jsonify({"error": "User with that email address already exists"}), 400
if not first_name.strip():
return jsonify({"error": "first name is required"}), 400
if not last_name.strip():
return jsonify({"error": "last name is required"}), 400
if not email.strip():
return jsonify({"error": "email is required"}), 400
if not password.strip():
return jsonify({"error": "password is required"}), 400
password_bytes = password.encode()
salt = bcrypt.gensalt() # 16-byte salt by default
hashed_password = bcrypt.hashpw(password_bytes, salt)
connection = sql_query.get_db_connection_isolation_none()
cursor = connection.cursor()
user_id = sql_query.store_user(user, first_name, last_name,
email, salt, hashed_password, bootstrapped)
cursor.close()
connection.close()
# Refresh/store all last.fm data for this user
db_query.refresh_user_data(user)
sql_query.store_broadcast(0,
constants.SYSTEM_ACCOUNT_ID,
"New Broadcastr",
f"{user} has joined Broadcastr. Welcome {user}!",
related_type_enum.RelatedType.USER.value,
user_id)
return jsonify({"success": user_id}), 201
@user_profile_bp.route("/api/user/login", methods=['POST'])
def api_user_login():
"""
Logs a user in. Validates profile name & password, sets last login timestamp.
Example:
POST /api/user/login?user=LastFmProfileName&password=pw
Raises:
400 Bad Request: If the user's profile could not be found.
400 Bad Request: If the user's password is not provided.
400 Bad Request: If the user's password was invalid.
400 Bad Request: If database integrity issues are detected.
Returns:
200 Success: The login was successful.
"""
user = request.args.get("user", "")
password = request.args.get("password", "")
user_id = sql_query.query_user_id(user)
# Prevent logging in as invalid or system account
if user_id in (0, constants.SYSTEM_ACCOUNT_ID):
return jsonify({"success": False, "error": "Missing or invalid user"}), 400
# if not password.strip():
# return jsonify({"error": "password is required"}), 400
if password.strip():
salt = sql_query.query_user_salt(user)
encoded_password = password.encode()
hashed_password = bcrypt.hashpw(encoded_password, salt)
else:
hashed_password = ""
user_id_pw = sql_query.query_user_id_by_password(user, hashed_password)
if user_id_pw == 0:
return jsonify({"success": False, "error": "Invalid password"}), 400
# This should never happen, but indicates a severe problem with database integrity if it does.
if user_id != user_id_pw:
return jsonify({"success": False, "error": "Data integrity issue"}), 400
connection = sql_query.get_db_connection_isolation_none()
cursor = connection.cursor()
cursor.execute(
"UPDATE User " \
"SET LastLogin = CURRENT_TIMESTAMP " \
"WHERE UserID = ?",
(user_id,))
cursor.close()
connection.close()
# If the user data has not been refreshed in the last day, refresh it.
if sql_query.user_refresh_due(user_id):
db_query.refresh_user_data(user)
return jsonify({"success": True, "error": ""}), 201
@user_profile_bp.route("/api/user/reset-password", methods=['POST'])
def api_user_reset_password():
"""
Resets a user's password.
Example:
POST /api/user/reset-password?user=LastFmProfileName&oldpassword=oldpw&newpassword=newpw
Raises:
400 Bad Request: If the user's profile could not be found.
400 Bad Request: If the user's old password was invalid.
400 Bad Request: If the user's new password is not provided.
400 Bad Request: If database integrity issues are detected.
Returns:
200 Success: The password reset was successful.
"""
user = request.args.get("user", "")
old_password = request.args.get("oldpassword", "")
new_password = request.args.get("newpassword", "")
user_id = sql_query.query_user_id(user)
if user_id == 0:
return jsonify({"error": "Missing or invalid user"}), 400
# Handle case where user currently does not have a password stored
if old_password == "":
user_id_pw = sql_query.query_user_id_by_password(user, "")
else:
salt = sql_query.query_user_salt(user)
encoded_password = old_password.encode()
hashed_password = bcrypt.hashpw(encoded_password, salt)
user_id_pw = sql_query.query_user_id_by_password(user, hashed_password)
if not new_password.strip():
return jsonify({"error": "new password is required"}), 400
if user_id_pw == 0:
return jsonify({"error": "Invalid password"}), 400
# This should never happen, but indicates a severe problem with database integrity if it does.
if user_id != user_id_pw:
return jsonify({"error": "Data integrity issue"}), 400
password_bytes = new_password.encode()
salt = bcrypt.gensalt() # 16-byte salt by default
hashed_password = bcrypt.hashpw(password_bytes, salt)
connection = sql_query.get_db_connection_isolation_none()
cursor = connection.cursor()
cursor.execute(
"UPDATE User " \
"SET Salt = ?, Password = ? " \
"WHERE UserID = ?",
(salt, hashed_password, user_id))
cursor.close()
connection.close()
return jsonify({"success": "password successfully updated"}), 200
@user_profile_bp.route("/api/user/add-swag", methods=['POST'])
def api_user_add_swag():
"""
Adds swag to a user.
Example:
POST /api/user/add-swag?user=LastFmProfileName&swag=n
Raises:
400 Bad Request: If the user's profile could not be found.
Returns:
200 Success: Updated swag balance for this user.
"""
user = request.args.get("user", "")
swag = request.args.get("swag", "")
swag = 0 if not swag.isnumeric() else int(swag)
user_id = sql_query.query_user_id(user)
if user_id == 0:
return jsonify({"error": "Missing or invalid user"}), 400
new_swag = sql_query.add_swag(user_id, swag)
return jsonify({"updated swag balance": new_swag}), 200