Files
military-tech-voice3.0/backend/app/db.py
T
lanhao 223761e717 feat: 登录验证 + 邀请码注册 + 用量监控后台
- 新增用户认证系统(登录/登出/邀请码注册)
- 新增管理后台(邀请码管理/用户管理/使用记录/用量统计)
- 合成接口加登录验证,每次调用记录用户和稿件内容
- SQLite存储用户数据和使用日志
- 默认admin账号: simonkoson

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-02 18:51:23 +08:00

70 lines
2.3 KiB
Python

import sqlite3
import os
from werkzeug.security import generate_password_hash
DB_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'data')
DB_PATH = os.path.join(DB_DIR, 'voice.db')
def get_db():
"""获取数据库连接"""
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
return conn
def init_db():
"""初始化数据库表 + 创建默认 admin 账号"""
os.makedirs(DB_DIR, exist_ok=True)
conn = get_db()
cursor = conn.cursor()
cursor.executescript('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
display_name TEXT NOT NULL,
password_hash TEXT NOT NULL,
role TEXT DEFAULT 'editor',
is_active INTEGER DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS invite_codes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
code TEXT UNIQUE NOT NULL,
editor_name TEXT NOT NULL,
is_used INTEGER DEFAULT 0,
used_by_user_id INTEGER,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
used_at DATETIME
);
CREATE TABLE IF NOT EXISTS usage_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
username TEXT NOT NULL,
display_name TEXT NOT NULL,
text_content TEXT NOT NULL,
text_length INTEGER NOT NULL,
engine TEXT NOT NULL,
emotion TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
);
''')
# 创建默认 admin 账号(如不存在)
existing = cursor.execute(
'SELECT id FROM users WHERE username = ?', ('simonkoson',)
).fetchone()
if not existing:
cursor.execute(
'INSERT INTO users (username, display_name, password_hash, role) VALUES (?, ?, ?, ?)',
('simonkoson', '蓝皓', generate_password_hash('liutong65'), 'admin')
)
conn.commit()
conn.close()