-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreset_admin.py
More file actions
94 lines (75 loc) · 3.63 KB
/
Copy pathreset_admin.py
File metadata and controls
94 lines (75 loc) · 3.63 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
import sqlite3
import bcrypt
# 数据库文件路径
db_path = './data/docutranslate.db'
# 新密码
new_password = "admin"
print(f"开始重置admin密码为: {new_password}")
# 连接到SQLite数据库
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
try:
# 先检查用户表是否存在
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='users';")
table_exists = cursor.fetchone()
if table_exists:
print("✅ 用户表存在")
# 查询当前admin用户信息,包括密码哈希
cursor.execute("SELECT id, username, is_admin, password_hash FROM users WHERE username = 'admin';")
admin_user = cursor.fetchone()
if admin_user:
user_id, username, is_admin, current_hash = admin_user
print(f"✅ 找到admin用户: ID={user_id}, 用户名={username}, 是管理员={is_admin}")
print(f"当前密码哈希: {current_hash}")
# 直接更新密码,不进行前置验证
print("🔄 直接更新admin密码...")
# 生成新的bcrypt哈希密码
password_bytes = new_password.encode('utf-8')[:72] # bcrypt限制密码长度为72字节
hashed_bytes = bcrypt.hashpw(password_bytes, bcrypt.gensalt())
hashed_password = hashed_bytes.decode('utf-8')
print(f"生成的新哈希密码: {hashed_password}")
# 执行更新操作
cursor.execute("UPDATE users SET password_hash = ? WHERE id = ?", (hashed_password, user_id))
# 获取更新的行数
updated_rows = cursor.rowcount
print(f"更新语句执行后影响的行数: {updated_rows}")
# 提交更改
conn.commit()
print("✅ 事务已提交")
# 再次查询数据库,验证密码是否已更新
cursor.execute("SELECT password_hash FROM users WHERE id = ?", (user_id,))
updated_hash = cursor.fetchone()[0]
print(f"更新后的密码哈希: {updated_hash}")
if updated_hash == hashed_password:
print(f"✅ Admin密码已成功重置为:{new_password}")
else:
print("❌ 密码更新失败,哈希值不匹配")
else:
# 如果没有找到admin用户,尝试创建一个
print("⚠️ 未找到admin用户,尝试创建...")
# 生成bcrypt哈希密码
password_bytes = new_password.encode('utf-8')[:72] # bcrypt限制密码长度为72字节
hashed_bytes = bcrypt.hashpw(password_bytes, bcrypt.gensalt())
hashed_password = hashed_bytes.decode('utf-8')
cursor.execute("INSERT INTO users (username, password_hash, is_admin) VALUES (?, ?, ?)",
("admin", hashed_password, 1))
inserted_rows = cursor.rowcount
conn.commit()
if inserted_rows > 0:
print(f"✅ 已创建新的admin用户,密码为:{new_password}")
else:
print("❌ 创建admin用户失败")
else:
print("❌ 用户表不存在,无法重置密码")
# 列出所有表
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()
print(f"当前数据库中的表: {tables}")
except Exception as e:
print(f"❌ 重置密码失败:{str(e)}")
import traceback
traceback.print_exc()
conn.rollback()
finally:
# 关闭连接
conn.close()