-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin_routes.py
More file actions
436 lines (348 loc) · 14.2 KB
/
admin_routes.py
File metadata and controls
436 lines (348 loc) · 14.2 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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
from functools import wraps
import os
import shutil
from flask import Blueprint, current_app, request, jsonify, send_file
from flask_jwt_extended import jwt_required, get_jwt_identity
from sqlalchemy.exc import SQLAlchemyError
from database import db
from models import ProofreadPrompt, SystemSetting, TranscribePrompt, User, Transcription, ErrorLog
from werkzeug.security import generate_password_hash
admin = Blueprint('admin', __name__)
def is_admin(username):
user = User.query.filter_by(username=username).first()
if user:
return user.is_admin
return False
def require_admin(func):
@wraps(func) # Keeps the original function metadata
def wrapper(*args, **kwargs):
current_user = get_jwt_identity()
if not is_admin(current_user):
return jsonify({"error": "Admin access required"}), 403
# Call the actual function only if authorized
return func(*args, **kwargs)
return wrapper
@admin.route('/users', methods=['GET'])
@jwt_required()
@require_admin
def get_users():
users = User.query.all()
return jsonify([user.to_dict() for user in users]), 200
@admin.route('/users', methods=['POST'])
@jwt_required()
@require_admin
def add_user():
data = request.json
username = data.get('username')
password = data.get('password')
is_new_user_admin = data.get('isAdmin', False)
if not username or not password:
return jsonify({"error": "Username and password are required"}), 400
if User.query.filter_by(username=username).first():
return jsonify({"error": "Username already exists"}), 400
new_user = User(username=username, password=generate_password_hash(
password), is_admin=is_new_user_admin)
db.session.add(new_user)
try:
db.session.commit()
return jsonify({"message": "User created successfully"}), 201
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e)}), 500
@admin.route('/users/<int:user_id>', methods=['DELETE'])
@jwt_required()
@require_admin
def delete_user(user_id):
user = User.query.get(user_id)
if not user:
return jsonify({"error": "User not found"}), 404
if user.is_admin:
return jsonify({"error": "User is admin"}), 404
try:
# Delete associated records from related tables
ErrorLog.query.filter_by(user_id=user_id).delete()
Transcription.query.filter_by(user_id=user_id).delete()
# Delete the user
db.session.delete(user)
# Delete associated files
user_folders = [
# os.path.join(current_app.config['AUDIO_FOLDER'], user.username),
os.path.join(current_app.config['TXT_FOLDER'], user.username),
os.path.join(current_app.config['MD_FOLDER'], user.username),
os.path.join(current_app.config['WORD_FOLDER'], user.username)
]
# Commit database changes first
db.session.commit()
# Then handle file system operations
for folder in user_folders:
if os.path.exists(folder):
shutil.rmtree(folder)
return jsonify({"message": "User and all associated data deleted successfully"}), 200
except OSError as e:
db.session.rollback()
return jsonify({"error": f"""Error deleting user files: {str(e)}"""}), 500
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": f"""Database error: {str(e)}"""}), 500
@admin.route('/transcriptions/<string:transcription_id>', methods=['DELETE'])
@jwt_required()
@require_admin
def delete_transcription(transcription_id):
transcription: Transcription = Transcription.query.get(transcription_id)
if not transcription:
return jsonify({"error": "Transcription not found"}), 404
try:
# Delete associated records from related tables
ErrorLog.query.filter_by(transcription_id=transcription_id).delete()
# Delete the user
db.session.delete(transcription)
# Delete associated files
transcription_folders = [
# os.path.join(current_app.config['AUDIO_FOLDER'], transcription.user.username, transcription_id),
os.path.join(current_app.config['TXT_FOLDER'], transcription.user.username, transcription_id),
os.path.join(current_app.config['MD_FOLDER'], transcription.user.username, transcription_id),
os.path.join(current_app.config['WORD_FOLDER'], transcription.user.username, transcription_id)
]
# Commit database changes first
db.session.commit()
# Then handle file system operations
for folder in transcription_folders:
if os.path.exists(folder):
shutil.rmtree(folder)
return jsonify({"message": "Transcription and all associated data deleted successfully"}), 200
except OSError as e:
db.session.rollback()
return jsonify({"error": f"""Error deleting transcription files: {str(e)}"""}), 500
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": f"""Database error: {str(e)}"""}), 500
@admin.route('/logs', methods=['GET'])
@jwt_required()
@require_admin
def get_logs():
logs = ErrorLog.query.order_by(ErrorLog.created_at.desc()).limit(100).all()
return jsonify([log.to_dict() for log in logs]), 200
@admin.route('/transcriptions', methods=['GET'])
@jwt_required()
@require_admin
def get_all_transcriptions():
transcriptions = Transcription.query.order_by(
Transcription.created_at.desc()).limit(100).all()
return jsonify([transcription.to_dict() for transcription in transcriptions]), 200
@admin.route('/transcribe-prompts', methods=['GET'])
@jwt_required()
@require_admin
def get_all_transcribe_prompts():
transcribe_prompts = TranscribePrompt.query.order_by(
TranscribePrompt.created_at.desc()).limit(100).all()
return jsonify([transcribe_prompt.to_dict() for transcribe_prompt in transcribe_prompts]), 200
@admin.route('/transcribe-prompts', methods=['POST'])
@jwt_required()
@require_admin
def add_transcribe_prompt():
data = request.json
version = data.get('version')
prompt = data.get('prompt')
if not version or not prompt:
return jsonify({"error": "Version and prompt are required"}), 400
new_prompt = TranscribePrompt(version=version, prompt=prompt)
db.session.add(new_prompt)
try:
db.session.commit()
return jsonify({"message": "Transcribe prompt created successfully"}), 201
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e)}), 500
@admin.route('/settings/active-transcribe-prompt', methods=['GET'])
@jwt_required()
@require_admin
def get_active_transcribe_prompt():
setting = SystemSetting.query.filter_by(
setting_key='active_transcribe_prompt_id').first()
if not setting:
return jsonify({"error": "No active transcribe prompt set"}), 404
prompt = TranscribePrompt.query.get(setting.setting_value)
if not prompt:
return jsonify({"error": "Active transcribe prompt not found"}), 404
return jsonify(prompt.to_dict()), 200
@admin.route('/settings/active-transcribe-prompt', methods=['POST'])
@jwt_required()
@require_admin
def set_active_transcribe_prompt():
data = request.json
transcribe_prompt_id = data.get('transcribe_prompt_id')
if not transcribe_prompt_id:
return jsonify({"error": "Transcribe prompt ID is required"}), 400
prompt = TranscribePrompt.query.get(transcribe_prompt_id)
if not prompt:
return jsonify({"error": "Transcribe prompt not found"}), 404
setting = SystemSetting.query.filter_by(
setting_key='active_transcribe_prompt_id').first()
if setting:
setting.setting_value = str(transcribe_prompt_id)
else:
setting = SystemSetting(
setting_key='active_transcribe_prompt_id',
setting_value=str(transcribe_prompt_id),
description='ID of the currently active transcribe prompt'
)
db.session.add(setting)
try:
db.session.commit()
return jsonify({"message": "Active transcribe prompt updated successfully"}), 200
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e)}), 500
@admin.route('/proofread-prompts', methods=['GET'])
@jwt_required()
@require_admin
def get_all_proofread_prompts():
proofread_prompts = ProofreadPrompt.query.order_by(
ProofreadPrompt.created_at.desc()).limit(100).all()
return jsonify([proofread_prompt.to_dict() for proofread_prompt in proofread_prompts]), 200
@admin.route('/proofread-prompts', methods=['POST'])
@jwt_required()
@require_admin
def add_proofread_prompt():
data = request.json
version = data.get('version')
prompt = data.get('prompt')
if not version or not prompt:
return jsonify({"error": "Version and prompt are required"}), 400
new_prompt = ProofreadPrompt(version=version, prompt=prompt)
db.session.add(new_prompt)
try:
db.session.commit()
return jsonify({"message": "Proofread prompt created successfully"}), 201
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e)}), 500
@admin.route('/settings/active-proofread-prompt', methods=['GET'])
@jwt_required()
@require_admin
def get_active_proofread_prompt():
setting = SystemSetting.query.filter_by(
setting_key='active_proofread_prompt_id').first()
if not setting:
return jsonify({"error": "No active proofread prompt set"}), 404
prompt = ProofreadPrompt.query.get(setting.setting_value)
if not prompt:
return jsonify({"error": "Active proofread prompt not found"}), 404
return jsonify(prompt.to_dict()), 200
@admin.route('/settings/active-proofread-prompt', methods=['POST'])
@jwt_required()
@require_admin
def set_active_proofread_prompt():
data = request.json
proofread_prompt_id = data.get('proofread_prompt_id')
if not proofread_prompt_id:
return jsonify({"error": "Proofread prompt ID is required"}), 400
prompt = ProofreadPrompt.query.get(proofread_prompt_id)
if not prompt:
return jsonify({"error": "Proofread prompt not found"}), 404
setting = SystemSetting.query.filter_by(
setting_key='active_proofread_prompt_id').first()
if setting:
setting.setting_value = str(proofread_prompt_id)
else:
setting = SystemSetting(
setting_key='active_proofread_prompt_id',
setting_value=str(proofread_prompt_id),
description='ID of the currently active proofread prompt'
)
db.session.add(setting)
try:
db.session.commit()
return jsonify({"message": "Active proofread prompt updated successfully"}), 200
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e)}), 500
@admin.route('/settings', methods=['GET'])
@jwt_required()
@require_admin
def get_settings():
settings = SystemSetting.query.all()
return jsonify([setting.to_dict() for setting in settings]), 200
@admin.route('/settings', methods=['POST'])
@jwt_required()
@require_admin
def add_setting():
data = request.json
key = data.get('setting_key')
value = data.get('setting_value')
description = data.get('description')
if not key or not value:
return jsonify({"error": "Setting key and value are required"}), 400
if SystemSetting.query.filter_by(setting_key=key).first():
return jsonify({"error": "Setting key already exists"}), 400
new_setting = SystemSetting(
setting_key=key, setting_value=value, description=description)
db.session.add(new_setting)
try:
db.session.commit()
return jsonify({"message": "Setting created successfully"}), 201
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e)}), 500
@admin.route('/settings/<int:setting_id>', methods=['PUT'])
@jwt_required()
@require_admin
def update_setting(setting_id):
setting = SystemSetting.query.get(setting_id)
if not setting:
return jsonify({"error": "Setting not found"}), 404
data = request.json
setting.setting_value = data.get('setting_value', setting.setting_value)
setting.description = data.get('description', setting.description)
try:
db.session.commit()
return jsonify({"message": "Setting updated successfully"}), 200
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e)}), 500
@admin.route('/settings/<int:setting_id>', methods=['DELETE'])
@jwt_required()
@require_admin
def delete_setting(setting_id):
setting = SystemSetting.query.get(setting_id)
if not setting:
return jsonify({"error": "Setting not found"}), 404
db.session.delete(setting)
try:
db.session.commit()
return jsonify({"message": "Setting deleted successfully"}), 200
except SQLAlchemyError as e:
db.session.rollback()
return jsonify({"error": str(e)}), 500
@admin.route('/stats', methods=['GET'])
@jwt_required()
@require_admin
def get_stats():
total_users = User.query.count()
total_transcriptions = Transcription.query.count()
total_errors = ErrorLog.query.count()
return jsonify({
"total_users": total_users,
"total_transcriptions": total_transcriptions,
"total_errors": total_errors
}), 200
@admin.route('/download/<file_type>/<transcription_id>', methods=['GET'])
@jwt_required()
@require_admin
def download_file(file_type, transcription_id):
transcription = Transcription.query.get(transcription_id)
if not transcription:
return jsonify({"error": "Transcription not found"}), 404
# Map file types to their corresponding database fields
file_type_mapping = {
'txt': transcription.txt_document_path,
'md': transcription.md_document_path,
'word': transcription.word_document_path,
'docx': transcription.word_document_path
}
if file_type not in file_type_mapping:
return jsonify({"error": "Invalid file type"}), 400
file_path = file_type_mapping[file_type]
if not file_path or not os.path.exists(file_path):
return jsonify({"error": f"{file_type.upper()} file not found"}), 404
return send_file(file_path, as_attachment=True)