-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
681 lines (542 loc) · 21.4 KB
/
app.py
File metadata and controls
681 lines (542 loc) · 21.4 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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
"""Zoom Capture - Flask web application and entry point."""
import hashlib
import logging
import os
import secrets
from datetime import date, datetime, timedelta
from functools import wraps
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
from flask import (
Flask, render_template, request, jsonify, session,
send_file, abort, redirect, url_for,
)
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from config_manager import ConfigManager
from scheduler import SchedulerService
from file_manager import FileManager
from zoom_api import ZoomClient, ZoomAuthError, ZoomAPIError
# --- App Initialization ---
app = Flask(__name__)
_flask_secret = os.environ.get("FLASK_SECRET_KEY", "")
if not _flask_secret or _flask_secret == "CHANGE_ME_TO_RANDOM_SECRET":
_flask_secret = secrets.token_hex(32)
logging.getLogger(__name__).warning(
"FLASK_SECRET_KEY not set or still default. "
"Using a random key (sessions will not survive restarts). "
"Set FLASK_SECRET_KEY to a stable random value in production."
)
app.secret_key = _flask_secret
limiter = Limiter(
get_remote_address,
app=app,
default_limits=["200 per hour", "50 per minute"],
storage_uri="memory://",
)
config_manager = ConfigManager()
scheduler_service = SchedulerService(config_manager)
# --- CSRF Protection ---
CSRF_TOKEN_MAX_AGE_SECONDS = 3600 # 1 hour
@app.before_request
def csrf_protect():
"""Validate CSRF token on state-changing requests.
Tokens expire after CSRF_TOKEN_MAX_AGE_SECONDS and are rotated.
"""
if request.method in ("GET", "HEAD", "OPTIONS"):
return
# Skip CSRF for login/setup endpoints (they have their own protection)
if request.endpoint in ("api_login", "api_setup"):
token = (
request.headers.get("X-CSRF-Token")
or request.form.get("csrf_token")
)
if not token or token != session.get("csrf_token"):
return jsonify({"error": "CSRF token invalid"}), 403
return
token = (
request.headers.get("X-CSRF-Token")
or request.form.get("csrf_token")
)
if not token or token != session.get("csrf_token"):
return jsonify({"error": "CSRF token invalid"}), 403
# Check token age and rotate if expired
token_time_str = session.get("csrf_token_time")
if token_time_str:
try:
token_time = datetime.fromisoformat(token_time_str)
age = (datetime.now() - token_time).total_seconds()
if age > CSRF_TOKEN_MAX_AGE_SECONDS:
# Token is stale - rotate it after this request
session["csrf_token"] = secrets.token_hex(32)
session["csrf_token_time"] = datetime.now().isoformat()
except (ValueError, TypeError):
pass
@app.context_processor
def inject_csrf_token():
"""Inject csrf_token into all Jinja2 templates."""
if "csrf_token" not in session:
session["csrf_token"] = secrets.token_hex(32)
session["csrf_token_time"] = datetime.now().isoformat()
return {"csrf_token": session["csrf_token"]}
# --- Authentication ---
def _hash_password(password: str, salt: str) -> str:
"""Hash a password with the given salt using SHA-256."""
return hashlib.sha256((salt + password).encode()).hexdigest()
def login_required(f):
"""Decorator that requires an authenticated session."""
@wraps(f)
def decorated(*args, **kwargs):
auth = config_manager.get_auth()
if not auth.get("password_hash"):
# No password set yet - allow access to setup
if request.endpoint not in ("setup_page", "api_setup", "static"):
return redirect(url_for("setup_page"))
elif not session.get("authenticated"):
if request.endpoint not in ("login_page", "api_login", "static"):
return redirect(url_for("login_page"))
return f(*args, **kwargs)
return decorated
@app.before_request
def require_auth():
"""Check authentication on every request (except static files)."""
if request.endpoint == "static":
return
auth = config_manager.get_auth()
if not auth.get("password_hash"):
if request.endpoint not in ("setup_page", "api_setup"):
return redirect(url_for("setup_page"))
elif not session.get("authenticated"):
if request.endpoint not in ("login_page", "api_login"):
return redirect(url_for("login_page"))
@app.route("/login")
def login_page():
"""Login page."""
if session.get("authenticated"):
return redirect(url_for("dashboard"))
return render_template("login.html")
@app.route("/api/login", methods=["POST"])
@limiter.limit("10 per minute")
def api_login():
"""Authenticate user with password."""
data = request.get_json() or {}
password = data.get("password", "")
auth = config_manager.get_auth()
if not auth.get("password_hash"):
return jsonify({"error": "No password configured"}), 400
hashed = _hash_password(password, auth["salt"])
if not secrets.compare_digest(hashed, auth["password_hash"]):
return jsonify({"error": "Invalid password"}), 401
session["authenticated"] = True
return jsonify({"success": True})
@app.route("/setup")
def setup_page():
"""First-run password setup page."""
auth = config_manager.get_auth()
if auth.get("password_hash"):
return redirect(url_for("login_page"))
return render_template("setup.html")
@app.route("/api/setup", methods=["POST"])
def api_setup():
"""Set the initial dashboard password."""
auth = config_manager.get_auth()
if auth.get("password_hash"):
return jsonify({"error": "Password already configured"}), 400
data = request.get_json() or {}
password = data.get("password", "").strip()
if len(password) < 8:
return jsonify({"error": "Password must be at least 8 characters"}), 400
salt = secrets.token_hex(16)
password_hash = _hash_password(password, salt)
config_manager.set_auth(salt=salt, password_hash=password_hash)
session["authenticated"] = True
return jsonify({"success": True})
@app.route("/logout", methods=["POST"])
def logout():
"""Clear the session."""
session.clear()
return redirect(url_for("login_page"))
# --- Security Headers ---
@app.after_request
def set_security_headers(response):
"""Add standard security headers to every response."""
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["X-XSS-Protection"] = "1; mode=block"
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
response.headers["Content-Security-Policy"] = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
"font-src 'self' https://cdn.jsdelivr.net; "
"img-src 'self' data:; "
"frame-ancestors 'none'"
)
if request.is_secure:
response.headers["Strict-Transport-Security"] = (
"max-age=31536000; includeSubDomains"
)
return response
# --- Helpers ---
def mask_secret(secret: str) -> str:
"""Return masked secret showing only last 4 characters."""
if not secret or len(secret) < 4:
return "****"
return "****" + secret[-4:]
def mask_account(account: dict) -> dict:
"""Return account dict with client_secret masked."""
masked = account.copy()
masked["client_secret"] = mask_secret(masked.get("client_secret", ""))
return masked
# ===================== PAGE ROUTES =====================
@app.route("/")
def dashboard():
"""Dashboard page with system status overview."""
status = scheduler_service.get_status()
accounts = config_manager.get_accounts()
settings = config_manager.get_settings()
archive_stats = {"total_files": 0, "total_size_human": "0 B",
"date_folders": 0}
if settings.get("base_archive_path"):
try:
fm = FileManager(settings["base_archive_path"])
archive_stats = fm.get_archive_stats()
except Exception:
pass
enabled_count = sum(1 for a in accounts if a.get("enabled"))
return render_template(
"dashboard.html",
status=status,
archive_stats=archive_stats,
enabled_count=enabled_count,
total_count=len(accounts),
)
@app.route("/accounts")
def accounts_page():
"""Accounts management page."""
accounts = [mask_account(a) for a in config_manager.get_accounts()]
return render_template("accounts.html", accounts=accounts)
@app.route("/settings")
def settings_page():
"""Settings configuration page."""
settings = config_manager.get_settings()
return render_template("settings.html", settings=settings)
@app.route("/logs")
def logs_page():
"""Log viewer page."""
today = date.today().strftime("%Y-%m-%d")
return render_template("logs.html", today=today)
@app.route("/manual-run")
def manual_run_page():
"""Manual run trigger page."""
yesterday = (date.today() - timedelta(days=1)).strftime("%Y-%m-%d")
accounts = [mask_account(a) for a in config_manager.get_accounts()]
return render_template("manual_run.html", yesterday=yesterday,
accounts=accounts)
# ===================== API ROUTES =====================
# --- Accounts ---
@app.route("/api/accounts", methods=["GET"])
def api_get_accounts():
"""Return all accounts with masked secrets."""
accounts = [mask_account(a) for a in config_manager.get_accounts()]
return jsonify(accounts)
@app.route("/api/accounts", methods=["POST"])
def api_create_account():
"""Create a new account."""
data = request.get_json()
if not data:
return jsonify({"error": "Request body required"}), 400
required = ["custom_name", "account_id", "client_id", "client_secret"]
for field in required:
if not data.get(field, "").strip():
return jsonify({"error": f"{field} is required"}), 400
# Check for duplicate name
existing = config_manager.get_accounts()
for acct in existing:
if acct["custom_name"].lower() == data["custom_name"].strip().lower():
return jsonify(
{"error": "Account name already exists. Choose unique name."}
), 409
account = config_manager.add_account(
name=data["custom_name"].strip(),
account_id=data["account_id"].strip(),
client_id=data["client_id"].strip(),
client_secret=data["client_secret"].strip(),
)
return jsonify(mask_account(account)), 201
@app.route("/api/accounts/<account_id>", methods=["GET"])
def api_get_account(account_id):
"""Return a single account with masked secret."""
account = config_manager.get_account(account_id)
if not account:
return jsonify({"error": "Account not found"}), 404
return jsonify(mask_account(account))
@app.route("/api/accounts/<account_id>", methods=["PUT"])
def api_update_account(account_id):
"""Update account fields."""
data = request.get_json()
if not data:
return jsonify({"error": "Request body required"}), 400
# If client_secret starts with **** or is empty, preserve existing
if not data.get("client_secret") or data["client_secret"].startswith("****"):
data.pop("client_secret", None)
account = config_manager.update_account(account_id, data)
if not account:
return jsonify({"error": "Account not found"}), 404
return jsonify(mask_account(account))
@app.route("/api/accounts/<account_id>", methods=["DELETE"])
def api_delete_account(account_id):
"""Delete an account."""
if config_manager.delete_account(account_id):
return "", 204
return jsonify({"error": "Account not found"}), 404
@app.route("/api/accounts/<account_id>/toggle", methods=["PATCH"])
def api_toggle_account(account_id):
"""Toggle account enabled/disabled."""
account = config_manager.toggle_account(account_id)
if not account:
return jsonify({"error": "Account not found"}), 404
return jsonify(mask_account(account))
@app.route("/api/accounts/<account_id>/test", methods=["POST"])
def api_test_account(account_id):
"""Test account credentials by authenticating with Zoom."""
account = config_manager.get_account(account_id)
if not account:
return jsonify({"error": "Account not found"}), 404
client = ZoomClient(
account_id=account["account_id"],
client_id=account["client_id"],
client_secret=account["client_secret"],
account_name=account["custom_name"],
)
try:
user_info = client.test_connection()
return jsonify({
"success": True,
"user_info": {
"email": user_info.get("email", ""),
"type": user_info.get("type", ""),
},
})
except ZoomAuthError as e:
logging.getLogger(__name__).error("Auth test failed for account %s: %s", account_id, e)
return jsonify({
"success": False,
"error": "Authentication failed. Check your credentials.",
})
except ZoomAPIError as e:
logging.getLogger(__name__).error("API test failed for account %s: %s", account_id, e)
return jsonify({
"success": False,
"error": "API connection error. Please try again.",
})
finally:
client.close()
# --- Settings ---
@app.route("/api/settings", methods=["GET"])
def api_get_settings():
"""Return current settings."""
return jsonify(config_manager.get_settings())
@app.route("/api/settings", methods=["PUT"])
def api_update_settings():
"""Update settings."""
data = request.get_json()
if not data:
return jsonify({"error": "Request body required"}), 400
# Validate run_time format strictly with datetime parsing
run_time = data.get("run_time", "")
if run_time:
import re as _re
if not _re.match(r'^\d{1,2}:\d{2}$', run_time):
return jsonify(
{"error": "Run time must be in HH:MM format (00:00-23:59)"}
), 400
try:
parsed = datetime.strptime(run_time, "%H:%M")
# Normalise to HH:MM
run_time = parsed.strftime("%H:%M")
data["run_time"] = run_time
except ValueError:
return jsonify(
{"error": "Run time must be in HH:MM format (00:00-23:59)"}
), 400
old_settings = config_manager.get_settings()
updated = config_manager.update_settings(data)
# Reschedule if run_time changed
if run_time and run_time != old_settings.get("run_time"):
try:
scheduler_service.reschedule(run_time)
except Exception as e:
logging.error("Failed to reschedule: %s", e)
return jsonify(updated)
@app.route("/api/settings/test-paths", methods=["POST"])
def api_test_paths():
"""Test if archive and log paths are writable."""
data = request.get_json()
if not data:
return jsonify({"error": "Request body required"}), 400
errors = []
for key in ("base_archive_path", "log_path"):
path = data.get(key, "").strip()
if not path:
continue
p = Path(path).resolve()
# Block obviously dangerous paths
dangerous = [Path("/"), Path("C:\\"), Path("C:\\Windows"),
Path("C:\\Windows\\System32"), Path("/etc"), Path("/usr")]
if p in [d.resolve() for d in dangerous]:
errors.append(f"{key}: path not allowed")
continue
try:
p.mkdir(parents=True, exist_ok=True)
# Test write
test_file = p / ".write_test"
test_file.write_text("test")
test_file.unlink()
except OSError as e:
errors.append(f"{key}: path is not writable")
if errors:
return jsonify({"success": False, "error": "; ".join(errors)})
return jsonify({"success": True})
@app.route("/api/browse-folder", methods=["POST"])
def api_browse_folder():
"""Open a native folder picker dialog and return the selected path.
The initial_dir is validated to be a real directory. The dialog itself
is the native OS picker, so the user can navigate freely, but we
log the selection for audit purposes.
"""
import threading
data = request.get_json() or {}
initial_dir = data.get("initial_dir", "").strip() or None
# Validate initial_dir exists and resolve to real path
if initial_dir:
resolved = Path(initial_dir).resolve()
if not resolved.is_dir():
initial_dir = None
else:
initial_dir = str(resolved)
result = {"path": None}
def open_dialog():
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
root.attributes("-topmost", True)
selected = filedialog.askdirectory(
title="Select Folder",
initialdir=initial_dir,
)
root.destroy()
result["path"] = selected if selected else None
# tkinter must run on a dedicated thread with its own mainloop
t = threading.Thread(target=open_dialog)
t.start()
t.join(timeout=120)
if result["path"]:
# Resolve to prevent path traversal in the returned value
resolved_path = str(Path(result["path"]).resolve())
return jsonify({"path": resolved_path})
return jsonify({"path": None})
# --- Logs ---
@app.route("/api/logs/<log_date>", methods=["GET"])
def api_get_log(log_date):
"""Return log file content for a given date (YYYYMMDD)."""
import re as _re
# Validate log_date is strictly YYYYMMDD to prevent path traversal
if not _re.match(r'^\d{8}$', log_date):
return jsonify({"error": "Invalid date format"}), 400
settings = config_manager.get_settings()
log_path = settings.get("log_path", "")
if not log_path:
return jsonify({"content": None, "error": "Log path not configured"})
log_file = Path(log_path) / f"zoom_archival_{log_date}.log"
if not log_file.exists():
return jsonify({"content": None, "date": log_date})
content = log_file.read_text(encoding="utf-8")
errors_only = request.args.get("errors_only", "").lower() == "true"
if errors_only:
lines = content.splitlines()
filtered = [l for l in lines if "ERROR" in l or "WARNING" in l]
content = "\n".join(filtered) if filtered else "No errors found."
return jsonify({"content": content, "date": log_date})
@app.route("/api/logs/<log_date>/download", methods=["GET"])
def api_download_log(log_date):
"""Download a log file."""
import re as _re
if not _re.match(r'^\d{8}$', log_date):
abort(400)
settings = config_manager.get_settings()
log_path = settings.get("log_path", "")
if not log_path:
abort(404)
log_file = Path(log_path) / f"zoom_archival_{log_date}.log"
if not log_file.exists():
abort(404)
return send_file(
log_file,
as_attachment=True,
download_name=f"zoom_archival_{log_date}.log",
)
# --- Manual Run ---
@app.route("/api/manual-run", methods=["POST"])
@limiter.limit("5 per minute")
def api_manual_run():
"""Trigger a manual download job."""
data = request.get_json() or {}
download_all = data.get("download_all", False)
# Parse date (not required when download_all is True)
date_str = data.get("date")
target_date = None
if date_str:
try:
target_date = datetime.strptime(date_str, "%Y-%m-%d").date()
except ValueError:
return jsonify({"error": "Invalid date format. Use YYYY-MM-DD"}), 400
account_ids = data.get("account_ids")
try:
scheduler_service.run_now(target_date=target_date,
account_ids=account_ids,
download_all=download_all)
except RuntimeError:
return jsonify({"error": "A download job is already running"}), 409
return jsonify({"message": "Download job started"}), 202
# --- Status ---
@app.route("/api/status", methods=["GET"])
def api_get_status():
"""Return current scheduler and job status."""
return jsonify(scheduler_service.get_status())
@app.route("/api/scheduler/start", methods=["POST"])
def api_start_scheduler():
"""Start the scheduler."""
try:
scheduler_service.start()
return jsonify({"message": "Scheduler started"})
except Exception as e:
logging.getLogger(__name__).error("Failed to start scheduler: %s", e)
return jsonify({"error": "Failed to start scheduler"}), 500
@app.route("/api/scheduler/stop", methods=["POST"])
def api_stop_scheduler():
"""Stop the scheduler."""
try:
scheduler_service.stop()
return jsonify({"message": "Scheduler stopped"})
except Exception as e:
logging.getLogger(__name__).error("Failed to stop scheduler: %s", e)
return jsonify({"error": "Failed to stop scheduler"}), 500
# ===================== ENTRY POINT =====================
def setup_logging():
"""Configure root logger with console handler."""
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
handlers=[logging.StreamHandler()],
)
if __name__ == "__main__":
setup_logging()
config_manager.ensure_config_exists()
scheduler_service.start()
try:
app.run(host="0.0.0.0", port=5000, debug=False, use_reloader=False)
finally:
scheduler_service.stop()