- 新增 users 数据库表,存储用户名、密码哈希、角色 - 启动时自动从 .env 创建初始管理员账号 - 登录改为数据库校验,不再硬编码比对 - 新增 /api/users 管理接口(仅管理员) - ConfigView 新增用户管理页(创建、改密码、切换角色、删除)
58 lines
1.6 KiB
Python
58 lines
1.6 KiB
Python
"""数据库配置"""
|
|
from sqlalchemy import create_engine, text
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
from .config import DATABASE_URL
|
|
|
|
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
Base = declarative_base()
|
|
|
|
|
|
def get_db():
|
|
"""获取数据库会话"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def _migrate_db():
|
|
"""简单的数据库迁移:为旧表添加缺失的列"""
|
|
migrations = [
|
|
("tasks", "branch", "VARCHAR DEFAULT 'main'"),
|
|
("tasks", "error_category", "VARCHAR"),
|
|
]
|
|
with engine.connect() as conn:
|
|
for table, column, col_type in migrations:
|
|
try:
|
|
conn.execute(text(f"ALTER TABLE {table} ADD COLUMN {column} {col_type}"))
|
|
conn.commit()
|
|
except Exception:
|
|
pass # 列已存在则忽略
|
|
|
|
|
|
def _seed_admin():
|
|
"""初始化管理员账号(从 .env 配置)"""
|
|
from .models import User
|
|
from .config import ADMIN_USERNAME, ADMIN_PASSWORD
|
|
import hashlib
|
|
|
|
db = SessionLocal()
|
|
try:
|
|
if not db.query(User).filter(User.username == ADMIN_USERNAME).first():
|
|
pw_hash = hashlib.sha256(ADMIN_PASSWORD.encode()).hexdigest()
|
|
db.add(User(id="admin-001", username=ADMIN_USERNAME, password_hash=pw_hash, is_admin=True))
|
|
db.commit()
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def init_db():
|
|
"""初始化数据库"""
|
|
Base.metadata.create_all(bind=engine)
|
|
_migrate_db()
|
|
_seed_admin()
|