File size: 1,411 Bytes
3b1ab70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Dev tool:重設 admin 密碼(產生新隨機密碼 + 解鎖 + 強制改密 + 撤銷舊 token)。

用法:
    py reset_admin.py
"""
import secrets
import sqlite3
from pathlib import Path

import bcrypt

DB = Path(__file__).parent / "kbv5.db"
MARKER = Path(__file__).parent / "ADMIN_INITIAL_PASSWORD.txt"

ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789!@#$%^&*"
pwd = "".join(secrets.choice(ALPHABET) for _ in range(16))
hashed = bcrypt.hashpw(pwd.encode("utf-8"), bcrypt.gensalt(rounds=12)).decode("utf-8")

c = sqlite3.connect(str(DB))
c.execute(
    "UPDATE users SET password_hash=?, failed_login_count=0, locked_until=NULL, "
    "force_password_change=1, jwt_version=jwt_version+1, totp_enabled=0, totp_secret=NULL "
    "WHERE username='admin'",
    (hashed,),
)
c.execute("DELETE FROM sessions WHERE user_id IN (SELECT id FROM users WHERE username='admin')")
c.commit()
n = c.execute("SELECT COUNT(*) FROM users WHERE username='admin'").fetchone()[0]
c.close()

if n == 0:
    print("ERROR: admin 帳號不存在")
    raise SystemExit(1)

MARKER.write_text(
    f"username: admin\npassword: {pwd}\n"
    f"force_password_change: 1\n首次登入後系統會要求改密碼。\n",
    encoding="utf-8",
)
print("admin 密碼已重設")
print(f"新密碼:{pwd}")
print("(同時:解鎖、強制改密、撤銷舊 token、關閉 2FA)")
print(f"已寫入:{MARKER}")