feat: 增加用户修改密码与管理员重置密码
This commit is contained in:
+33
-1
@@ -7,7 +7,7 @@ ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT_DIR not in sys.path:
|
||||
sys.path.insert(0, ROOT_DIR)
|
||||
|
||||
from server.auth import admin_required, authenticate, create_user, login_required
|
||||
from server.auth import admin_required, authenticate, create_user, login_required, set_password
|
||||
from server.db import BASE_DIR, get_db, init_db
|
||||
from server.entries_api import entries_bp
|
||||
from server.settings_api import settings_bp
|
||||
@@ -80,6 +80,19 @@ def create_app():
|
||||
session.clear()
|
||||
return jsonify({"ok": True})
|
||||
|
||||
@app.post("/api/change-password")
|
||||
@login_required
|
||||
def change_password(user):
|
||||
data = request.get_json(silent=True) or {}
|
||||
old_password = data.get("oldPassword") or ""
|
||||
new_password = data.get("newPassword") or ""
|
||||
if len(new_password) < 6:
|
||||
return jsonify({"error": "新密码至少 6 位"}), 400
|
||||
if authenticate(user["username"], old_password) is None:
|
||||
return jsonify({"error": "当前密码不正确"}), 400
|
||||
set_password(user["id"], new_password)
|
||||
return jsonify({"ok": True})
|
||||
|
||||
@app.get("/api/me")
|
||||
@login_required
|
||||
def me(user):
|
||||
@@ -185,6 +198,25 @@ def create_app():
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@app.put("/api/admin/users/<int:user_id>/password")
|
||||
@admin_required
|
||||
def admin_reset_password(user, user_id):
|
||||
data = request.get_json(silent=True) or {}
|
||||
new_password = data.get("password") or data.get("newPassword") or ""
|
||||
if len(new_password) < 6:
|
||||
return jsonify({"error": "新密码至少 6 位"}), 400
|
||||
conn = get_db()
|
||||
try:
|
||||
target = conn.execute(
|
||||
"SELECT id FROM users WHERE id = ?", (user_id,)
|
||||
).fetchone()
|
||||
finally:
|
||||
conn.close()
|
||||
if target is None:
|
||||
return jsonify({"error": "用户不存在"}), 404
|
||||
set_password(user_id, new_password)
|
||||
return jsonify({"ok": True})
|
||||
|
||||
@app.get("/")
|
||||
def index():
|
||||
return send_from_directory(BASE_DIR, "index.html")
|
||||
|
||||
@@ -71,6 +71,18 @@ def create_user(username, password, display_name, is_admin=False, is_active=True
|
||||
conn.close()
|
||||
|
||||
|
||||
def set_password(user_id, new_password):
|
||||
conn = get_db()
|
||||
try:
|
||||
conn.execute(
|
||||
"UPDATE users SET password_hash = ? WHERE id = ?",
|
||||
(generate_password_hash(new_password), user_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def authenticate(username, password):
|
||||
conn = get_db()
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user