-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdb_instance_api.py
More file actions
3407 lines (2969 loc) · 118 KB
/
db_instance_api.py
File metadata and controls
3407 lines (2969 loc) · 118 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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
数据库相关管理 API
认证:/api/db-instances、/api/backup-jobs、/api/backup-files 需请求头
Authorization: Bearer <accessToken>(登录接口除外)。
定时任务调 POST /api/backup-jobs/<id>/execute 无用户 token 时:
- 设置 BACKUP_CRON_SECRET,脚本 curl 会带 X-Backup-Cron-Secret;或
- 默认 BACKUP_ALLOW_LOCAL_EXECUTE=1 时仅允许本机 127.0.0.1 / ::1 调用 execute(生产可设为 0 并改用密钥)。
数据库实例信息管理
- GET /api/db-instances 列表
- POST /api/db-instances 新增
- PUT /api/db-instances/<id> 编辑
- DELETE /api/db-instances/<id> 删除
- POST /api/db-instances/test-connection 校验当前填写的连接信息能否访问 MySQL
- POST /api/db-instances/<id>/backup 立即执行该实例备份
- POST /api/db-instances/<id>/restore myloader 还原备份目录到目标库
任务调度(备份计划/定时任务配置)
- GET /api/backup-jobs 列表(可选 query keyword)
- POST /api/backup-jobs 新增
- PUT /api/backup-jobs/<id> 编辑
- POST /api/backup-jobs/delete/<id> 删除(推荐)
- DELETE /api/backup-jobs/<id> 删除(兼容旧版)
备份文件
- GET /api/backup-files 列表(可选 query keyword)
- DELETE /api/backup-files/<dirName> 删除记录并删除已解析且路径安全的会话备份目录(磁盘上不存在则仅删记录)
- GET /api/backup-files/<dirName>/download 下载 backupDir 目录打包的 tar.gz
- GET /api/backup-files/<dirName>/tables 解析 metadata(data/metadata、.partial 及旧版根目录);目录解析支持 back/backup/<dirName> 回退
- GET /api/backup-files/<dirName>/logs 读取会话目录下 backup.log、restore.log 文本(有长度上限)
- 执行即时备份:先往 json/backup-files.json 写入基础信息(size=0),接口立即返回;脚本在后台线程执行,结束后更新 size 或移除预登记
- 执行即时还原:接口立即返回,myloader 在后台线程执行(结果写入会话目录 restore.log)
账号(${BACK_DIR}/json/account.json)
- 每条记录字段:account_id、username、password(不再区分 role)
- 注册时自动生成 account_id;旧数据会在加载时自动补齐 account_id 并移除 role
"""
import json
import os
import re
import shlex
import shutil
import subprocess
import threading
import time
import uuid
from typing import Any, Optional, Tuple
from urllib.parse import unquote
from flask import Flask, Response, jsonify, request, stream_with_context
from werkzeug.utils import secure_filename
# --- 登录密码加密(RSA-OAEP-SHA256)---
try:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.hazmat.primitives.serialization import (
Encoding,
NoEncryption,
PrivateFormat,
PublicFormat,
load_pem_private_key,
)
except Exception: # pragma: no cover
rsa = None # type: ignore[assignment]
padding = None # type: ignore[assignment]
hashes = None # type: ignore[assignment]
Encoding = None # type: ignore[assignment]
PublicFormat = None # type: ignore[assignment]
PrivateFormat = None # type: ignore[assignment]
NoEncryption = None # type: ignore[assignment]
load_pem_private_key = None # type: ignore[assignment]
app = Flask(__name__)
# 代码运行目录(容器内通常是 /app/backup)
REPO_DIR = os.path.dirname(os.path.abspath(__file__))
# 后端持久化基准目录(json/jobs/data 统一放这里)
BACK_DIR = (
os.environ.get("BACK_DIR")
or os.environ.get("APP_BACK_DIR")
or "/app/backup_data"
)
# 脚本目录默认位于 ${REPO_DIR}/scripts(如 /app/backup/scripts)
SCRIPT_DIR = os.environ.get("SCRIPT_DIR") or os.path.join(REPO_DIR, "scripts")
# 持久化统一放在 ${BACK_DIR}/json 目录
JSON_DIR = os.path.join(BACK_DIR, "json")
DB_INSTANCES_FILE = os.path.join(JSON_DIR, "db-instances.json")
BACKUP_JOBS_FILE = os.path.join(JSON_DIR, "backup-jobs.json")
BACKUP_FILES_FILE = os.path.join(JSON_DIR, "backup-files.json")
ACCOUNT_FILE = os.path.join(JSON_DIR, "account.json")
TIMEZONE_FILE = os.path.join(JSON_DIR, "timezone.json")
AUTH_TOKENS_FILE = os.path.join(JSON_DIR, "auth-tokens.json")
RSA_LOGIN_SESSIONS_FILE = os.path.join(JSON_DIR, "rsa-login-sessions.json")
JOBS_DIR = os.path.join(BACK_DIR, "jobs")
JOB_LOGS_DIR = os.path.join(BACK_DIR, "job-logs")
JOB_SCRIPT_LOGS_DIR = os.path.join(JOBS_DIR, "logs")
CRON_MARK_PREFIX = "# back backup-job "
# 与 mysql-backup-mydumper.sh 默认 -b 一致(未传 backup_dir 时)
_DEFAULT_BACKUP_ROOT = os.path.join(BACK_DIR, "data")
_file_lock = threading.Lock()
_JOB_LOG_MAX_BYTES = 200_000
def _load_auth_tokens_unlocked() -> dict[str, dict[str, str]]:
if not os.path.isfile(AUTH_TOKENS_FILE):
return {"access": {}, "refresh": {}}
try:
with open(AUTH_TOKENS_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
except (OSError, json.JSONDecodeError):
return {"access": {}, "refresh": {}}
return {
"access": dict((data or {}).get("access") or {}),
"refresh": dict((data or {}).get("refresh") or {}),
}
def _save_auth_tokens_unlocked(payload: dict[str, dict[str, str]]) -> None:
os.makedirs(JSON_DIR, exist_ok=True)
tmp = f"{AUTH_TOKENS_FILE}.tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(payload, f, ensure_ascii=False, indent=2)
os.replace(tmp, AUTH_TOKENS_FILE)
def _auth_tokens_snapshot() -> dict[str, dict[str, str]]:
with _file_lock:
return _load_auth_tokens_unlocked()
def _auth_tokens_mutate(mutator) -> None:
with _file_lock:
data = _load_auth_tokens_unlocked()
mutator(data)
_save_auth_tokens_unlocked(data)
def _make_access_token(username: str) -> str:
return f"access-{username}-{int(time.time())}-{os.urandom(6).hex()}"
def _make_refresh_token(username: str) -> str:
return f"refresh-{username}-{int(time.time())}-{os.urandom(8).hex()}"
def _make_account_id() -> str:
# account_id 使用 UUID:避免基于时间/随机数拼接带来的可预测性
return str(uuid.uuid4())
def _get_bearer_token() -> str:
auth = (request.headers.get("Authorization") or "").strip()
if not auth.lower().startswith("bearer "):
return ""
return auth[7:].strip()
def _get_user_by_access_token() -> Optional[dict]:
token = _get_bearer_token()
if not token:
return None
snap = _auth_tokens_snapshot()
username = (snap.get("access") or {}).get(token)
if not username:
return None
with _file_lock:
accounts = _load_accounts()
return next((x for x in accounts if (x.get("username") or "").strip() == username), None)
def _get_current_account_id() -> str:
"""
当前登录用户 account_id。
对于 cron 放行的内部触发(无 token)场景,返回空字符串。
注意:内部会获取 _file_lock(读 auth-tokens.json),切勿在已持有 _file_lock 的代码块内调用,否则死锁。
"""
user = _get_user_by_access_token()
if not user:
return ""
return (user.get("account_id") or "").strip()
def _legacy_default_account_id() -> str:
"""
兼容历史数据:当 db-instances / backup-jobs / backup-files 记录缺少 account_id 时,
默认归属到 zhangsan 账号,尽量保证老数据对 zhangsan 可见、其他账号不可见。
"""
accounts = _load_accounts()
zhangsan = next(
(
x
for x in accounts
if (x.get("username") or "").strip().lower() == "zhangsan"
and (x.get("account_id") or "").strip()
),
None,
)
if zhangsan:
return (zhangsan.get("account_id") or "").strip()
for x in accounts:
aid = (x.get("account_id") or "").strip()
if aid:
return aid
return ""
def _get_userinfo_payload_for_account(acc: dict) -> dict:
"""统一为普通用户,并尽量对齐 mock user/info 的字段习惯。"""
username = (acc.get("username") or "").strip()
account_id = (acc.get("account_id") or "").strip()
return {
"avatar": "",
"desc": "This is a local account user.",
"homePath": "/backup/db-instance",
"id": account_id or username,
"realName": username,
"roles": ["user"],
"token": "",
"userId": username,
"username": username,
}
# 后端权限模式(accessMode=backend)下 /menu/all 使用;结构与 apps/backend-mock 中 MOCK_MENUS 一致
def _backend_menus_for_account(_acc: dict) -> list[dict]:
return _BACKEND_MENU_TREES["user"]
# 自 mock-data.ts 同步的精简菜单(dashboard + demos/access 下按角色可见页)
_BACKEND_MENU_TREES: dict[str, list[dict]] = {
"admin": [
{
"meta": {"order": -1, "title": "page.dashboard.title"},
"name": "Dashboard",
"path": "/dashboard",
"redirect": "/workspace",
"children": [
{
"name": "Workspace",
"path": "/workspace",
"component": "/dashboard/workspace/index",
"meta": {"title": "page.dashboard.workspace"},
},
],
},
],
"user": [
{
"meta": {"order": -1, "title": "page.dashboard.title"},
"name": "Dashboard",
"path": "/dashboard",
"redirect": "/workspace",
"children": [
{
"name": "Workspace",
"path": "/workspace",
"component": "/dashboard/workspace/index",
"meta": {"title": "page.dashboard.workspace"},
},
],
},
],
}
def _success(data: Any = None, message: str = "success"):
return jsonify({"code": 0, "data": data, "message": message})
def _error(message: str = "error", code: int = 1, http_status: int = 400):
return jsonify({"code": code, "data": None, "message": message}), http_status
# 需登录才可访问的业务前缀(备份相关)
_BACKUP_PROTECTED_PREFIXES = (
"/api/db-instances",
"/api/backup-jobs",
"/api/backup-files",
)
# --- /api/auth/rsa:临时 RSA 密钥(仅用于登录时前端加密,避免明文密码上传)---
# 会话落盘到 ${JSON_DIR}/rsa-login-sessions.json,便于多 worker / 多进程共享(仅内存会导致 GET /rsa 与 POST /login 落到不同进程时密钥「无效」)。
_RSA_LOGIN_TTL_SECONDS = int(os.environ.get("AUTH_RSA_TTL_SECONDS") or 300) # 5 min
def _rsa_now() -> float:
return time.time()
def _load_rsa_sessions_unlocked() -> dict[str, Any]:
if not os.path.isfile(RSA_LOGIN_SESSIONS_FILE):
return {}
try:
with open(RSA_LOGIN_SESSIONS_FILE, "r", encoding="utf-8") as f:
raw = json.load(f)
return raw if isinstance(raw, dict) else {}
except (OSError, json.JSONDecodeError):
return {}
def _save_rsa_sessions_unlocked(store: dict[str, Any]) -> None:
os.makedirs(JSON_DIR, exist_ok=True)
tmp = f"{RSA_LOGIN_SESSIONS_FILE}.tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(store, f, ensure_ascii=False, indent=2)
os.replace(tmp, RSA_LOGIN_SESSIONS_FILE)
def _rsa_gc_expired_store(store: dict[str, Any]) -> None:
t = _rsa_now()
for k in list(store.keys()):
v = store.get(k) or {}
if float(v.get("expires_at") or 0) <= t:
store.pop(k, None)
def _rsa_available() -> bool:
return (
rsa is not None
and padding is not None
and hashes is not None
and Encoding is not None
and PublicFormat is not None
and PrivateFormat is not None
and NoEncryption is not None
and load_pem_private_key is not None
)
def _rsa_issue_login_public_key() -> dict[str, Any]:
if not _rsa_available():
raise RuntimeError("cryptography not installed")
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()
public_pem = public_key.public_bytes(encoding=Encoding.PEM, format=PublicFormat.SubjectPublicKeyInfo).decode(
"utf-8", errors="ignore"
)
pem_bytes = private_key.private_bytes(
encoding=Encoding.PEM,
format=PrivateFormat.PKCS8,
encryption_algorithm=NoEncryption(),
)
pem_str = pem_bytes.decode("utf-8", errors="ignore")
key_id = f"k_{int(_rsa_now() * 1000)}_{os.urandom(8).hex()}"
expires_at = _rsa_now() + max(30, _RSA_LOGIN_TTL_SECONDS)
with _file_lock:
store = _load_rsa_sessions_unlocked()
_rsa_gc_expired_store(store)
store[key_id] = {"expires_at": expires_at, "private_key_pem": pem_str}
_save_rsa_sessions_unlocked(store)
return {
"algorithm": "RSA-OAEP-SHA256",
"expiresAt": int(expires_at * 1000),
"keyId": key_id,
"publicKey": public_pem,
}
def _rsa_decrypt_login_password_once(key_id: str, encrypted_b64: str) -> Optional[str]:
if not _rsa_available():
return None
pem_str = ""
with _file_lock:
store = _load_rsa_sessions_unlocked()
_rsa_gc_expired_store(store)
sess = store.get(key_id)
if not sess:
return None
expires_at = float(sess.get("expires_at") or 0)
if expires_at <= _rsa_now():
store.pop(key_id, None)
_save_rsa_sessions_unlocked(store)
return None
pem_str = (sess.get("private_key_pem") or "").strip()
if not pem_str:
return None
try:
import base64
private_key = load_pem_private_key(pem_str.encode("utf-8"), password=None)
cipher = base64.b64decode(encrypted_b64.encode("utf-8"), validate=True)
plain = private_key.decrypt(
cipher,
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None),
)
with _file_lock:
store = _load_rsa_sessions_unlocked()
store.pop(key_id, None)
_save_rsa_sessions_unlocked(store)
return plain.decode("utf-8", errors="ignore")
except Exception:
return None
def _is_backup_protected_path(path: str) -> bool:
if not path:
return False
return any(path.startswith(p) for p in _BACKUP_PROTECTED_PREFIXES)
def _cron_execute_bypass_ok() -> bool:
"""
定时任务脚本用 curl 调 POST /api/backup-jobs/<id>/execute,无用户 Bearer。
放行方式(二选一):
- 环境变量 BACKUP_CRON_SECRET 非空,且请求头 X-Backup-Cron-Secret 与其一致;
- 环境变量 BACKUP_ALLOW_LOCAL_EXECUTE 为 1/true/yes,且请求来自本机 127.0.0.1 / ::1。
"""
if request.method != "POST":
return False
p = (request.path or "").rstrip("/")
if not p.startswith("/api/backup-jobs/") or not p.endswith("/execute"):
return False
secret = (os.environ.get("BACKUP_CRON_SECRET") or "").strip()
if secret and (request.headers.get("X-Backup-Cron-Secret") or "").strip() == secret:
return True
allow_local = (os.environ.get("BACKUP_ALLOW_LOCAL_EXECUTE") or "1").strip().lower()
if allow_local in ("1", "true", "yes", "on"):
addr = (request.remote_addr or "").strip()
if addr in ("127.0.0.1", "::1"):
return True
return False
def _api_cors_allow_headers() -> str:
return (
"Authorization, Content-Type, Accept-Language, X-Requested-With, "
"X-Backup-Cron-Secret"
)
@app.before_request
def _require_login_for_backup_apis():
path = request.path or ""
# 跨域预检(含 DELETE/PUT 等非简单请求):须在鉴权前响应,并声明允许的方法与头
if request.method == "OPTIONS" and path.startswith("/api/"):
r = Response(status=204)
r.headers["Access-Control-Allow-Origin"] = "*"
r.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, PATCH, OPTIONS"
r.headers["Access-Control-Allow-Headers"] = _api_cors_allow_headers()
r.headers["Access-Control-Max-Age"] = "86400"
return r
if not _is_backup_protected_path(path):
return None
if _cron_execute_bypass_ok():
return None
if not _get_user_by_access_token():
return _error("未登录或 token 无效", code=401, http_status=401)
return None
@app.after_request
def _add_cors_headers_for_api(resp: Response):
path = request.path or ""
if not path.startswith("/api/"):
return resp
resp.headers.setdefault("Access-Control-Allow-Origin", "*")
resp.headers.setdefault(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, PATCH, OPTIONS",
)
resp.headers.setdefault("Access-Control-Allow-Headers", _api_cors_allow_headers())
return resp
@app.route("/api/auth/rsa", methods=["GET"])
def auth_rsa_key():
if not _rsa_available():
return _error("服务端未安装 cryptography,无法启用登录密码加密", http_status=501)
try:
return _success(_rsa_issue_login_public_key())
except Exception:
return _error("生成 RSA 公钥失败", http_status=500)
@app.route("/api/auth/login", methods=["POST"])
def login():
payload = request.get_json(silent=True) or {}
username = (payload.get("username") or "").strip()
password = payload.get("password") or ""
encrypted_password = (payload.get("encryptedPassword") or "").strip()
key_id = (payload.get("keyId") or "").strip()
if not username or (not password and not (encrypted_password and key_id)):
return _error("用户名或密码不能为空", http_status=400)
if encrypted_password and key_id:
plain = _rsa_decrypt_login_password_once(key_id, encrypted_password)
if not plain:
return _error("RSA 密钥无效或已过期", http_status=400)
password = plain
with _file_lock:
accounts = _load_accounts()
target = next(
(
x
for x in accounts
if (x.get("username") or "").strip() == username
and (x.get("password") or "") == password
),
None,
)
if not target:
return _error("用户名或密码错误", http_status=401)
access_token = _make_access_token(username)
refresh_token = _make_refresh_token(username)
def _login_put_tokens(d: dict[str, dict[str, str]]) -> None:
d["access"][access_token] = username
d["refresh"][refresh_token] = username
_auth_tokens_mutate(_login_put_tokens)
response = _success({"accessToken": access_token}, "登录成功")
# 与 mock 行为一致:refresh token 走 httpOnly cookie
response.set_cookie(
"refreshToken",
refresh_token,
httponly=True,
samesite="Lax",
path="/",
)
return response
@app.route("/api/auth/register", methods=["POST"])
def register():
payload = request.get_json(silent=True) or {}
username = (payload.get("username") or "").strip()
password = payload.get("password") or ""
encrypted_password = (payload.get("encryptedPassword") or "").strip()
key_id = (payload.get("keyId") or "").strip()
if encrypted_password and key_id:
plain = _rsa_decrypt_login_password_once(key_id, encrypted_password)
if not plain:
return _error("RSA 密钥无效或已过期", http_status=400)
password = plain
if not username or not password:
return _error("用户名或密码不能为空", http_status=400)
if len(username) < 3:
return _error("用户名至少 3 位", http_status=400)
if len(password) < 6:
return _error("密码至少 6 位", http_status=400)
with _file_lock:
accounts = _load_accounts()
if any((x.get("username") or "").strip() == username for x in accounts):
return _error("用户名已存在", http_status=400)
accounts.append(
{"account_id": _make_account_id(), "password": password, "username": username},
)
_save_accounts(accounts)
return _success({"account_id": (accounts[-1].get("account_id") or ""), "username": username}, "注册成功")
@app.route("/api/auth/password", methods=["POST"])
def change_password():
"""
密码修改:要求用户已登录(Authorization: Bearer <accessToken>)
支持明文或 RSA-OAEP(SHA-256) 密文字段:
- oldPassword / newPassword
- encryptedOldPassword + oldKeyId
- encryptedNewPassword + newKeyId
"""
user = _get_user_by_access_token()
if not user:
return _unauthorized_like_nitro_mock()
payload = request.get_json(silent=True) or {}
username = (user.get("username") or "").strip()
old_password = (payload.get("oldPassword") or "").strip()
new_password = (payload.get("newPassword") or "").strip()
encrypted_old = (payload.get("encryptedOldPassword") or "").strip()
old_key_id = (payload.get("oldKeyId") or "").strip()
encrypted_new = (payload.get("encryptedNewPassword") or "").strip()
new_key_id = (payload.get("newKeyId") or "").strip()
if encrypted_old and old_key_id:
plain_old = _rsa_decrypt_login_password_once(old_key_id, encrypted_old)
if not plain_old:
return _error("旧密码 RSA 密钥无效或已过期", http_status=400)
old_password = plain_old
if encrypted_new and new_key_id:
plain_new = _rsa_decrypt_login_password_once(new_key_id, encrypted_new)
if not plain_new:
return _error("新密码 RSA 密钥无效或已过期", http_status=400)
new_password = plain_new
if not old_password or not new_password:
return _error("旧密码或新密码不能为空", http_status=400)
if len(new_password) < 6:
return _error("密码至少 6 位", http_status=400)
with _file_lock:
accounts = _load_accounts()
changed = False
for x in accounts:
if (x.get("username") or "").strip() != username:
continue
if (x.get("password") or "") != old_password:
continue
x["password"] = new_password
changed = True
break
if not changed:
return _error("旧密码错误", http_status=401)
with _file_lock:
_save_accounts(accounts)
return _success({}, "密码修改成功")
@app.route("/api/auth/codes", methods=["GET"])
def get_auth_codes():
user = _get_user_by_access_token()
if not user:
return _error("未登录或 token 无效", code=401, http_status=401)
return _success(["AC_1000001", "AC_1000002"])
@app.route("/api/user/info", methods=["GET"])
def get_user_info():
user = _get_user_by_access_token()
if not user:
return _unauthorized_like_nitro_mock()
return _success(_get_userinfo_payload_for_account(user))
@app.route("/api/menu/all", methods=["GET"])
def get_menu_all():
"""与 Nitro mock 的 /menu/all 对齐,供 accessMode=backend / mixed 使用(非 JWT token 也可)。"""
user = _get_user_by_access_token()
if not user:
return _error("未登录或 token 无效", code=401, http_status=401)
menus = _backend_menus_for_account(user)
return _success(menus)
@app.route("/api/timezone/getTimezone", methods=["GET"])
def get_timezone():
"""
对齐前端 getTimezoneApi 与 mock 返回:
- 已设置返回时区字符串
- 未设置返回 null
"""
user = _get_user_by_access_token()
if not user:
return _error("未登录或 token 无效", code=401, http_status=401)
username = (user.get("username") or "").strip()
with _file_lock:
timezone_map = _load_timezones()
return _success(timezone_map.get(username))
def _unauthorized_like_nitro_mock():
"""与 apps/backend-mock 中 unAuthorizedResponse 一致,避免前端对响应体格式敏感。"""
return (
jsonify(
{
"code": -1,
"data": None,
"error": "Unauthorized Exception",
"message": "Unauthorized Exception",
},
),
401,
)
def _require_account_for_system() -> Optional[dict]:
return _get_user_by_access_token()
# --- playground「系统管理」接口:原 Nitro mock 仅校验 JWT,本地 access token 会 401 并触发登出 ---
@app.route("/api/system/role/list", methods=["GET"])
def system_role_list():
if not _require_account_for_system():
return _unauthorized_like_nitro_mock()
page = max(1, int(request.args.get("page") or 1))
page_size = min(100, max(1, int(request.args.get("pageSize") or 20)))
# 占位数据;需要持久化时可改为读写 json
items_all: list[dict] = []
name_q = (request.args.get("name") or "").strip().lower()
if name_q:
items_all = [x for x in items_all if name_q in str(x.get("name", "")).lower()]
total = len(items_all)
start = (page - 1) * page_size
return _success({"items": items_all[start : start + page_size], "total": total})
@app.route("/api/system/menu/list", methods=["GET"])
def system_menu_list():
if not _require_account_for_system():
return _unauthorized_like_nitro_mock()
return _success([])
@app.route("/api/system/menu/name-exists", methods=["GET"])
def system_menu_name_exists():
if not _require_account_for_system():
return _unauthorized_like_nitro_mock()
return _success(False)
@app.route("/api/system/menu/path-exists", methods=["GET"])
def system_menu_path_exists():
if not _require_account_for_system():
return _unauthorized_like_nitro_mock()
return _success(False)
@app.route("/api/system/dept/list", methods=["GET"])
def system_dept_list():
if not _require_account_for_system():
return _unauthorized_like_nitro_mock()
return _success([])
@app.route("/api/auth/logout", methods=["POST"])
def logout():
token = _get_bearer_token()
refresh_token = (request.cookies.get("refreshToken") or "").strip()
def _logout_mut(d: dict[str, dict[str, str]]) -> None:
if token:
d["access"].pop(token, None)
if refresh_token:
d["refresh"].pop(refresh_token, None)
_auth_tokens_mutate(_logout_mut)
response = _success("", "退出成功")
response.delete_cookie("refreshToken", path="/")
return response
@app.route("/api/auth/refresh", methods=["POST"])
def refresh_token():
refresh_token = (request.cookies.get("refreshToken") or "").strip()
if not refresh_token:
return ("", 403)
snap = _auth_tokens_snapshot()
username = (snap.get("refresh") or {}).get(refresh_token)
if not username:
return ("", 403)
access_token = _make_access_token(username)
def _refresh_mut(d: dict[str, dict[str, str]]) -> None:
d["access"][access_token] = username
_auth_tokens_mutate(_refresh_mut)
# 与 mock 一致:refresh 接口返回纯字符串 token
return access_token
def _ensure_store_file() -> None:
os.makedirs(JSON_DIR, exist_ok=True)
if not os.path.isfile(DB_INSTANCES_FILE):
with open(DB_INSTANCES_FILE, "w", encoding="utf-8") as f:
json.dump([], f, ensure_ascii=False, indent=2)
def _ensure_jobs_store_file() -> None:
os.makedirs(JSON_DIR, exist_ok=True)
if not os.path.isfile(BACKUP_JOBS_FILE):
with open(BACKUP_JOBS_FILE, "w", encoding="utf-8") as f:
json.dump([], f, ensure_ascii=False, indent=2)
def _ensure_account_store_file() -> None:
os.makedirs(JSON_DIR, exist_ok=True)
if not os.path.isfile(ACCOUNT_FILE):
with open(ACCOUNT_FILE, "w", encoding="utf-8") as f:
# 默认账号:admin / 123456(首次启动可直接登录,后续可手工改文件)
json.dump(
[
{
"account_id": _make_account_id(),
"password": "123456",
"username": "admin",
},
],
f,
ensure_ascii=False,
indent=2,
)
def _load_accounts() -> list[dict]:
_ensure_account_store_file()
with open(ACCOUNT_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
if not isinstance(data, list):
return []
changed = False
out: list[dict] = []
for x in data:
if not isinstance(x, dict):
continue
username = (x.get("username") or "").strip()
password = x.get("password") or ""
if not username or not isinstance(password, str):
continue
account_id = (x.get("account_id") or "").strip()
if not account_id:
account_id = _make_account_id()
changed = True
if "role" in x:
changed = True
out.append(
{
"account_id": account_id,
"password": password,
"username": username,
},
)
if changed:
_save_accounts(out)
return out
def _save_accounts(items: list[dict]) -> None:
_ensure_account_store_file()
tmp_file = f"{ACCOUNT_FILE}.tmp"
with open(tmp_file, "w", encoding="utf-8") as f:
json.dump(items, f, ensure_ascii=False, indent=2)
os.replace(tmp_file, ACCOUNT_FILE)
def _ensure_timezone_store_file() -> None:
os.makedirs(JSON_DIR, exist_ok=True)
if not os.path.isfile(TIMEZONE_FILE):
with open(TIMEZONE_FILE, "w", encoding="utf-8") as f:
json.dump({}, f, ensure_ascii=False, indent=2)
def _load_timezones() -> dict[str, str]:
_ensure_timezone_store_file()
with open(TIMEZONE_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
if not isinstance(data, dict):
return {}
out: dict[str, str] = {}
for k, v in data.items():
if not isinstance(k, str) or not isinstance(v, str):
continue
username = k.strip()
tz = v.strip()
if username and tz:
out[username] = tz
return out
def _load_instances() -> list[dict]:
_ensure_store_file()
with open(DB_INSTANCES_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, list):
items = [item for item in data if isinstance(item, dict)]
legacy_account_id = _legacy_default_account_id()
changed = False
for x in items:
if not (x.get("account_id") or "").strip():
x["account_id"] = legacy_account_id
changed = True
if changed:
_save_instances(items)
return items
return []
def _save_instances(items: list[dict]) -> None:
_ensure_store_file()
tmp_file = f"{DB_INSTANCES_FILE}.tmp"
with open(tmp_file, "w", encoding="utf-8") as f:
json.dump(items, f, ensure_ascii=False, indent=2)
os.replace(tmp_file, DB_INSTANCES_FILE)
def _load_jobs() -> list[dict]:
_ensure_jobs_store_file()
with open(BACKUP_JOBS_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, list):
items = [item for item in data if isinstance(item, dict)]
legacy_account_id = _legacy_default_account_id()
changed = False
for x in items:
if not (x.get("account_id") or "").strip():
x["account_id"] = legacy_account_id
changed = True
if changed:
_save_jobs(items)
return items
return []
def _save_jobs(items: list[dict]) -> None:
_ensure_jobs_store_file()
tmp_file = f"{BACKUP_JOBS_FILE}.tmp"
with open(tmp_file, "w", encoding="utf-8") as f:
json.dump(items, f, ensure_ascii=False, indent=2)
os.replace(tmp_file, BACKUP_JOBS_FILE)
def _read_crontab_lines() -> list[str]:
"""读取当前用户 crontab(按行返回)。"""
try:
result = subprocess.run(
["crontab", "-l"],
capture_output=True,
text=True,
timeout=10,
env=os.environ,
check=False,
)
stdout = (result.stdout or "").strip()
stderr = (result.stderr or "").strip()
if result.returncode != 0:
if "no crontab" in stderr.lower() or "no crontab" in stdout.lower():
return []
return []
return stdout.splitlines()
except (subprocess.TimeoutExpired, Exception): # noqa: BLE001
return []
def _write_crontab_lines(lines: list[str]) -> bool:
"""覆盖写入 crontab 内容。"""
try:
text = "\n".join(lines).rstrip() + "\n" if lines else ""
result = subprocess.run(
["crontab", "-"],
input=text,
text=True,
timeout=10,
env=os.environ,
capture_output=True,
check=False,
)
return result.returncode == 0
except (subprocess.TimeoutExpired, Exception): # noqa: BLE001
return False
def _crontab_has_job_marker(job_id: str) -> bool:
"""判断当前用户 crontab 中是否存在该 job 的标记行(与 _sync_job_crontab 写入格式一致)。"""
jid = (job_id or "").strip()
if not jid:
return False
expected = f"{CRON_MARK_PREFIX}{jid}"
for line in _read_crontab_lines():
if line.strip() == expected:
return True
return False
def _build_job_script(job: dict) -> str:
job_id = (job.get("id") or "").strip()
api_url = f"http://127.0.0.1:8081/api/backup-jobs/{job_id}/execute"
meta_log_path = os.path.join(JOB_SCRIPT_LOGS_DIR, f"{job_id}.log")
run_log_path = os.path.join(JOB_SCRIPT_LOGS_DIR, f"{job_id}.run.log")
logs_dir = JOB_SCRIPT_LOGS_DIR
cron_secret = (os.environ.get("BACKUP_CRON_SECRET") or "").strip()
curl_extra = ""
if cron_secret:
curl_extra = f" -H {shlex.quote(f'X-Backup-Cron-Secret: {cron_secret}')}"
return "\n".join(
[
"#!/bin/bash",
'PATH="/usr/local/bin:/usr/bin:/bin:$PATH"',
f'mkdir -p {shlex.quote(logs_dir)}',
f'echo "$(date +\'%Y-%m-%d %H:%M:%S\') cron trigger job={job_id}" >> {shlex.quote(meta_log_path)}',