-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdebug.py
More file actions
334 lines (282 loc) · 14.1 KB
/
debug.py
File metadata and controls
334 lines (282 loc) · 14.1 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
from flask import Flask, request, Blueprint, render_template, redirect, url_for, jsonify
from main import DI, Logger, Universal, FireConn, FireAuth, FireRTDB, AddonsManager, Analytics, Encryption, FolderManager
import os, sys, json, datetime, copy, shutil
debugBP = Blueprint("debug", __name__)
debugMode = os.environ.get("DebugMode") == "True"
@debugBP.route("/debug/<secretKey>")
def debugHome(secretKey):
if not debugMode:
return redirect(url_for('unauthorised', error="Debug mode is not enabled."))
if secretKey != os.environ.get("AppSecretKey"):
return redirect(url_for('unauthorised', error="Invalid credentials."))
options = """
Options:<br><br>
- View logs: /debug/[key]/logs<br>
- Clear logs: /debug/[key]/logs/clear<br>
- Reload DI: /debug/[key]/reloadDI<br>
- FireAuth sync: /debug/[key]/fireAuthSync<br>
- FireReset: /debug/[key]/fireReset (Wipes all Firebase data, including Firebase Auth accounts, and reloads DI. Use with caution.)<br>
- Toggle usage lock: /debug/[key]/toggleUsageLock<br>
- Create admin: /debug/[key]/createAdmin?email=[email]&password=[password]<br>
- Toggle GPT: /debug/[key]/toggleGPT<br>
- Presentation transform: /debug/[key]/presentationTransform (Wipes all data and creates a new Google login user, with sample post, and admin account. Use with extreme caution.)<br>
"""
return options
@debugBP.route("/debug/<secretKey>/logs")
def viewLogs(secretKey):
if not debugMode:
return redirect(url_for('unauthorised', error="Debug mode is not enabled."))
if secretKey != os.environ.get("AppSecretKey"):
return redirect(url_for('unauthorised', error="Invalid credentials."))
return "<br>".join(Logger.readAll())
@debugBP.route("/debug/<secretKey>/logs/clear")
def clearLogs(secretKey):
if not debugMode:
return redirect(url_for('unauthorised', error="Debug mode is not enabled."))
if secretKey != os.environ.get("AppSecretKey"):
return redirect(url_for('unauthorised', error="Invalid credentials."))
Logger.destroyAll()
return "Logs cleared."
@debugBP.route("/debug/<secretKey>/reloadDI")
def reloadDI(secretKey):
if not debugMode:
return redirect(url_for('unauthorised', error="Debug mode is not enabled."))
if secretKey != os.environ.get("AppSecretKey"):
return redirect(url_for('unauthorised', error="Invalid credentials."))
DI.load()
Logger.log("DEBUG RELOADDI: DI reloaded.")
return "DI reload success. DI sync status: {}".format(DI.syncStatus)
@debugBP.route("/debug/<secretKey>/fireAuthSync")
def fireAuthSync(secretKey):
if not debugMode:
return redirect(url_for('unauthorised', error="Debug mode is not enabled."))
if secretKey != os.environ.get("AppSecretKey"):
return redirect(url_for('unauthorised', error="Invalid credentials."))
try:
if FireConn.checkPermissions():
previousCopy = copy.deepcopy(DI.data["accounts"])
DI.data["accounts"] = FireAuth.generateAccountsObject(fireAuthUsers=FireAuth.listUsers(), existingAccounts=DI.data["accounts"], strategy="overwrite")
DI.save()
if previousCopy != DI.data["accounts"]:
return "FireAuth sync success. Accounts object updated with changes."
else:
return "FireAuth sync success. No changes detected."
else:
return "FireAuth sync failed. FireConn is not enabled."
except Exception as e:
return "FireAuth sync failed. Error: {}".format(e)
@debugBP.route("/debug/<secretKey>/fireReset")
def fireReset(secretKey):
if not debugMode:
return redirect(url_for('unauthorised', error="Debug mode is not enabled."))
if secretKey != os.environ.get("AppSecretKey"):
return redirect(url_for('unauthorised', error="Invalid credentials."))
try:
for fireUser in FireAuth.listUsers():
FireAuth.deleteAccount(fireUser.uid, admin=True)
FireRTDB.setRef({})
DI.load()
except Exception as e:
return "Firebase reset failed. Error: {}".format(e)
Logger.log("DEBUG FIRERESET: All Firebase RTDB and Auth data wiped. DI reloaded.")
return "Firebase reset success. Accounts and database data wiped."
@debugBP.route("/debug/<secretKey>/toggleUsageLock")
def toggleUsageLock(secretKey):
if not debugMode:
return redirect(url_for('unauthorised', error="Debug mode is not enabled."))
if secretKey != os.environ.get("AppSecretKey"):
return redirect(url_for('unauthorised', error="Invalid credentials."))
currentStatus = AddonsManager.readConfigKey("UsageLock") == True
AddonsManager.setConfigKey("UsageLock", not currentStatus)
Logger.log("DEBUG TOGGLEUSAGELOCK: Usage lock status toggled to {}.".format("True" if (not currentStatus) else "False"))
return "Usage lock status toggled to {}.".format("True" if (not currentStatus) else "False")
@debugBP.route("/debug/<secretKey>/createAdmin")
def createAdmin(secretKey):
if not debugMode:
return redirect(url_for('unauthorised', error="Debug mode is not enabled."))
if secretKey != os.environ.get("AppSecretKey"):
return redirect(url_for('unauthorised', error="Invalid credentials."))
if "email" not in request.args:
return "Please provide an email."
if "password" not in request.args:
return "Please provide a password."
email = request.args.get("email")
password = request.args.get("password")
username = Analytics.generateRandomID(customLength=5)
accID = Universal.generateUniqueID()
responseObject = FireAuth.createUser(email=email, password=password)
if "ERROR" in responseObject:
return "Error: {}".format(responseObject)
DI.data["accounts"][accID] = {
"id": accID,
"fireAuthID": responseObject["uid"],
"username": username,
"email": email,
"password": Encryption.encodeToSHA256(password),
"idToken": responseObject["idToken"],
"refreshToken": responseObject["refreshToken"],
"tokenExpiry": (datetime.datetime.now() + datetime.timedelta(hours=1)).strftime(Universal.systemWideStringDatetimeFormat),
"disabled": False,
"admin": True,
"name": "Admin",
"position": "Debug Admin",
"aboutMe": ""
}
Logger.log("DEBUG CREATEADMIN: Created admin account with ID {}.".format(accID))
DI.save()
return "Admin account created with that email and password. ID: {}, Username: {}".format(accID, username)
@debugBP.route("/debug/<secretKey>/toggleGPT")
def toggleGPT(secretKey):
if not debugMode:
return redirect(url_for('unauthorised', error="Debug mode is not enabled."))
if secretKey != os.environ.get("AppSecretKey"):
return redirect(url_for('unauthorised', error="Invalid credentials."))
currentStatus = AddonsManager.readConfigKey("VerdexGPTEnabled") == True
AddonsManager.setConfigKey("VerdexGPTEnabled", not currentStatus)
Logger.log("DEBUG TOGGLEGPT: GPT status toggled to {}.".format("True" if (not currentStatus) else "False"))
return "VerdexGPT status toggled to {}.".format("True" if (not currentStatus) else "False")
@debugBP.route("/debug/<secretKey>/presentationTransform", methods=["GET", "POST"])
def presentationTransform(secretKey):
if not debugMode:
return redirect(url_for('unauthorised', error="Debug mode is not enabled."))
if secretKey != os.environ.get("AppSecretKey"):
return redirect(url_for('unauthorised', error="Invalid credentials."))
if request.method == "GET":
return render_template("presentationTransform.html", secretKey=secretKey)
## POST
if "userEmail" not in request.form:
return "Please provide a user email."
# if "userPassword" not in request.form:
# return "Please provide a user password."
if "adminEmail" not in request.form:
return "Please provide an admin email."
if "adminPassword" not in request.form:
return "Please provide an admin password."
if "supportQueryEmail" not in request.form:
return "Please provide a support query email (query reply will be sent to this email)."
# Wipe all data
## Clear Firebase Authentication accounts
try:
for fireUser in FireAuth.listUsers():
FireAuth.deleteAccount(fireUser.uid, admin=True)
except Exception as e:
Logger.log("DEBUG PRESENTATIONTRANSFORM ERROR: Firebase Authentication reset failed. Error: {}".format(e))
return "Firebase Authentication reset failed. Error: {}".format(e)
## Clear DI
try:
DI.data = copy.deepcopy(DI.sampleData)
DI.save()
except Exception as e:
Logger.log("DEBUG PRESENTATIONTRANSFORM ERROR: DI reload failed. Error: {}".format(e))
return "DI reload failed. Error: {}".format(e)
## Create new user account
userAccEmail = request.form.get("userEmail")
userAccID = Universal.generateUniqueID()
userAccResponse = FireAuth.createUser(email=userAccEmail, password="googlelogin")
if "ERROR" in userAccResponse:
Logger.log("DEBUG PRESENTATIONTRANSFORM ERROR: User account creation failed. Error: {}".format(userAccResponse))
return "User account creation failed. Error: {}".format(userAccResponse)
### Auto-verify email
response = FireAuth.updateEmailVerifiedStatus(userAccResponse["uid"], True)
if response != True:
Logger.log("DEBUG PRESENTATIONTRANSFORM ERROR: Failed to auto-verify email for new Google OAuth Login account created via presentation transform; error: {}".format(response))
DI.data["accounts"][userAccID] = {
"id": userAccID,
"fireAuthID": userAccResponse["uid"],
"googleLogin": True,
"username": "john",
"email": userAccEmail,
"password": Encryption.encodeToSHA256("googlelogin"),
"idToken": userAccResponse['idToken'],
"refreshToken": userAccResponse['refreshToken'],
"tokenExpiry": (datetime.datetime.now() + datetime.timedelta(hours=1)).strftime(Universal.systemWideStringDatetimeFormat),
"disabled": False,
"admin": False,
"forumBanned": False,
"aboutMe": "",
"reports": {}
}
## Attach sample forum post to user account
newPostDatetime = datetime.datetime.now().strftime(Universal.systemWideStringDatetimeFormat)
newPost = {
"username": "john",
"post_title": "Green Singapore!",
"post_description": "Can't wait to land in the greenest of nations, Singapore! Verdex has been helping a lot, but, do you have any recommendations too?",
"likes": "0",
"postDateTime": newPostDatetime,
"users_who_liked": [],
"tag": "Nature",
"targetAccountIDOfPostAuthor": userAccID,
"comments": {},
"itineraries": {}
}
DI.data["forum"][newPostDatetime] = newPost
## Create new admin account
adminAccEmail = request.form.get("adminEmail")
adminAccPassword = request.form.get("adminPassword")
adminAccID = Universal.generateUniqueID()
adminAccResponse = FireAuth.createUser(email=adminAccEmail, password=adminAccPassword)
if "ERROR" in adminAccResponse:
Logger.log("DEBUG PRESENTATIONTRANSFORM ERROR: Admin account creation failed. Error: {}".format(adminAccResponse))
return "Admin account creation failed. Error: {}".format(adminAccResponse)
DI.data["accounts"][adminAccID] = {
"id": adminAccID,
"fireAuthID": adminAccResponse["uid"],
"username": "admin",
"email": adminAccEmail,
"password": Encryption.encodeToSHA256(adminAccPassword),
"idToken": adminAccResponse["idToken"],
"refreshToken": adminAccResponse["refreshToken"],
"tokenExpiry": (datetime.datetime.now() + datetime.timedelta(hours=1)).strftime(Universal.systemWideStringDatetimeFormat),
"disabled": False,
"admin": True,
"name": "Admin",
"position": "Verdex Admin",
"aboutMe": ""
}
## Make sample support query
supportQueryID = Universal.generateUniqueID()
time_stamp = datetime.datetime.now().strftime(Universal.systemWideStringDatetimeFormat)
if "supportQueries" not in DI.data["admin"]:
DI.data["admin"]["supportQueries"] = {}
DI.data["admin"]["supportQueries"][supportQueryID] = {
"name": 'John Appleseed',
"email": request.form.get("supportQueryEmail"),
"message": "I'm having trouble making a post on VerdexTalks. Can you guide me?",
"supportQueryID": supportQueryID,
"timestamp": time_stamp
}
DI.save()
## Reset other services
AddonsManager.clearConfig()
Logger.log("DEBUG PRESENTATIONTRANSFORM: AddonsManager cleared.")
with open(Analytics.filePath, "w") as f:
json.dump(Analytics.sampleMetricsObject, f)
if os.path.isdir(os.path.join(os.getcwd(), Analytics.reportsFolderPath)):
shutil.rmtree(Analytics.reportsFolderPath)
Analytics.setup()
Logger.log("DEBUG PRESENTATIONTRANSFORM: Analytics reset, including reports directory.")
if os.path.isdir(os.path.join(os.getcwd(), FolderManager.tldName)):
shutil.rmtree(os.path.join(os.getcwd(), FolderManager.tldName))
FolderManager.setup()
Logger.log("DEBUG PRESENTATIONTRANSFORM: FolderManager reset.")
Logger.log("DEBUG PRESENTATIONTRANSFORM: Presentation transform success. User account ID: {}, Admin account ID: {}".format(userAccID, adminAccID))
report = """
Presentation transform successful. Report:<br><br>
The user account is a Google login account. It cannot be signed into via the standard login flow.<br>
<strong>PLEASE WAIT 10 SECONDS BEFORE LOGGING INTO THE USER ACCOUNT. THIS IS DUE TO GOOGLE OAUTH API LIMITATIONS.</strong><br><br>
User account:<br>
- ID: {}<br>
- Username: {}<br>
- Email: {}<br>
- Password: NA (Google OAuth Login)<br>
<br><br><br>
Admin account:<br>
- ID: {}<br>
- Username: {}<br>
- Email: {}<br>
- Password: {}
<br><br><br>
Analytics data reset including reports data. Admin configuration cleared. UserFolders directory cleared.
""".format(userAccID, "john", userAccEmail, adminAccID, "admin", adminAccEmail, adminAccPassword)
return report