增加新功能

This commit is contained in:
wzj 2025-06-24 11:37:20 +08:00
parent 1a8d70465a
commit 8e469a09e2

68
app.py
View File

@ -1,5 +1,6 @@
from flask import Flask, render_template, request, jsonify, abort, redirect, url_for, session, flash
from functools import wraps
import subprocess
import os
import sqlite3
from werkzeug.security import generate_password_hash, check_password_hash
@ -61,6 +62,10 @@ def init_db():
"INSERT INTO settings (proxy_address, proxy_port) VALUES (?, ?)",
('proxy.example.com', '3128')
)
# 初始化squid_passwd文件
if not os.path.exists(SQUID_PASSWD_FILE):
with open(SQUID_PASSWD_FILE, 'w') as f:
f.write('')
conn.commit()
@ -79,11 +84,31 @@ def update_squid_passwd():
users = db.execute("SELECT * FROM squid_users").fetchall()
db.close()
with open(SQUID_PASSWD_FILE, 'w') as f:
for user in users:
line = f"{'#' if not user['is_active'] else ''}{user['username']}:{user['password']}\n"
f.write(line)
# 先创建临时文件
temp_file = SQUID_PASSWD_FILE + '.tmp'
# 清空或创建文件
with open(temp_file, 'w') as f:
f.write('')
# 使用htpasswd命令添加每个用户
for user in users:
if not user['is_active']:
continue # 跳过禁用的用户
try:
subprocess.run([
'htpasswd', '-b',
temp_file,
user['username'],
user['password']
], check=True)
except subprocess.CalledProcessError as e:
print(f"Failed to add user {user['username']}: {e}")
continue
# 替换原文件
os.replace(temp_file, SQUID_PASSWD_FILE)
# 登录装饰器
def login_required(f):
@ -240,12 +265,44 @@ def create_user():
db = get_db()
try:
# 先存入明文密码到数据库
db.execute(
"INSERT INTO squid_users (username, password) VALUES (?, ?)",
(username, password)
)
db.commit()
# 更新squid_passwd文件
update_squid_passwd()
return jsonify({'success': True})
except sqlite3.IntegrityError:
return jsonify({'success': False, 'error': '用户名已存在'}), 400
finally:
db.close()
@app.route('/api/create_user', methods=['POST'])
@login_required
def create_user():
username = request.json.get('username')
password = request.json.get('password')
if not username or not password:
return jsonify({'success': False, 'error': '用户名和密码不能为空'}), 400
db = get_db()
try:
# 先存入明文密码到数据库
db.execute(
"INSERT INTO squid_users (username, password) VALUES (?, ?)",
(username, password)
)
db.commit()
# 更新squid_passwd文件
update_squid_passwd()
return jsonify({'success': True})
except sqlite3.IntegrityError:
return jsonify({'success': False, 'error': '用户名已存在'}), 400
@ -268,7 +325,10 @@ def update_user_password():
(password, user_id)
)
db.commit()
# 更新squid_passwd文件
update_squid_passwd()
db.close()
return jsonify({'success': True})