from fastapi import APIRouter, Depends, HTTPException, Request from pydantic import BaseModel from sqlalchemy import select from ...db.session import get_db from ...db import repos from ...models.entities import User from ...core import security from ...core.config import settings router = APIRouter(prefix="/auth", tags=["auth"]) class AuthIn(BaseModel): username: str password: str async def current_user(request: Request, db=Depends(get_db)) -> User: token = request.headers.get("Authorization", "").removeprefix("Bearer ") payload = security.parse_token(token) if not payload: raise HTTPException(401, "未登录") user = await repos.UserRepo.by_id(db, int(payload["uid"])) if not user or not user.is_active: raise HTTPException(401, "账户无效") return user @router.post("/register") async def register(body: AuthIn, db=Depends(get_db)): if await repos.SettingRepo.get(db, "allow_register") != "true": raise HTTPException(403, "本站已关闭注册") if await repos.UserRepo.by_username(db, body.username): raise HTTPException(409, "用户名已存在") salt = security.os.urandom(16) u = User(username=body.username, password_hash=security.hash_password(body.password), kdf_salt=salt.hex()) # 首个注册用户 = 管理员 if not (await db.execute(select(User))).scalars().first(): u.is_admin = True db.add(u) await db.commit() return await token_response(u, body.password) @router.post("/login") async def login(body: AuthIn, db=Depends(get_db)): u = await repos.UserRepo.by_username(db, body.username) if not u or not security.verify_password(body.password, u.password_hash): raise HTTPException(401, "用户名或密码错误") if not u.is_active: raise HTTPException(403, "账户已被封禁") return await token_response(u, body.password) async def token_response(u: User, password: str): key = security.derive_key(password, bytes.fromhex(u.kdf_salt)) security.key_cache[u.id] = key # "数据可见" OFF→ON 迁移:登录时把存量密文解开转明文 await migrate_decrypt(u, key) return {"token": security.make_token(u.id, u.is_admin), "username": u.username, "is_admin": u.is_admin} async def migrate_decrypt(u: User, key: bytes): """admin_data_visible=true 时,解密该用户所有存量密文(静默)。""" from ...db.session import SessionLocal from ...models.entities import Memory, WorldbookEntry, Message, ChatSession async with SessionLocal() as db: visible = await repos.SettingRepo.get(db, "admin_data_visible") == "true" if not visible: return for field_rows, field in [(await db.execute(select(Memory).where(Memory.user_id == u.id))).scalars().all(), "content_enc"], \ [(await db.execute(select(WorldbookEntry).where(WorldbookEntry.user_id == u.id))).scalars().all(), "content_enc"], \ [(await db.execute(select(Message).where(Message.user_id == u.id))).scalars().all(), "content_enc"]: for row in field_rows: if security.is_encrypted(getattr(row, field)): setattr(row, field, security.decrypt_text(key, getattr(row, field))) # novel_setting for s in (await db.execute(select(ChatSession).where(ChatSession.user_id == u.id))).scalars().all(): if s.novel_setting_enc and security.is_encrypted(s.novel_setting_enc): s.novel_setting_enc = security.decrypt_text(key, s.novel_setting_enc) await db.commit() @router.post("/delete-account") async def delete_account(body: AuthIn, user: User = Depends(current_user), db=Depends(get_db)): if await repos.SettingRepo.get(db, "allow_delete_account") != "true": raise HTTPException(403, "本站已关闭注销") if not security.verify_password(body.password, user.password_hash): raise HTTPException(401, "密码错误") # 硬删除:数据随账户消失,不可恢复 from ...models.entities import (Memory, WorldbookEntry, Message, ChatSession, Character, Channel) for model, col in [(Memory, "user_id"), (WorldbookEntry, "user_id"), (Message, "user_id"), (ChatSession, "user_id"), (Character, "user_id"), (Channel, "owner_id")]: await db.execute(select(model)) # touch from sqlalchemy import delete as _del await db.execute(_del(model).where(getattr(model, col) == user.id)) await db.delete(user) await db.commit() security.key_cache.pop(user.id, None) return {"ok": True} @router.get("/me") async def me(user: User = Depends(current_user)): return {"id": user.id, "username": user.username, "is_admin": user.is_admin} class ChangePasswordIn(BaseModel): old_password: str new_password: str @router.post("/change_password") async def change_password(body: ChangePasswordIn, user: User = Depends(current_user), db=Depends(get_db)): """旧密码解密 → 新密码重加密 → 换盐换 hash。""" if not security.verify_password(body.old_password, user.password_hash): raise HTTPException(401, "旧密码错误") if len(body.new_password) < 6: raise HTTPException(400, "新密码至少6位") old_key = security.derive_key(body.old_password, bytes.fromhex(user.kdf_salt)) new_salt = security.os.urandom(16) new_key = security.derive_key(body.new_password, new_salt) # 当前是否要求加密落库 from ...db import repos as _repos need_encrypt = await _repos.SettingRepo.get(db, "admin_data_visible") != "true" from ...models.entities import (Memory, WorldbookEntry, Character, ChatSession, Message) tables = [(Memory, "content_enc"), (WorldbookEntry, "content_enc"), (Message, "content_enc"), (ChatSession, "novel_setting_enc"), (Character, "persona"), (Character, "greeting")] for model, col in tables: rows = (await db.execute( select(model).where(model.user_id == user.id))).scalars().all() for row in rows: v = getattr(row, col) if not v: continue plain = (security.decrypt_text(old_key, v) if security.is_encrypted(v) else v) setattr(row, col, security.encrypt_text(new_key, plain) if need_encrypt else plain) user.kdf_salt = new_salt.hex() user.password_hash = security.hash_password(body.new_password) await db.commit() security.key_cache[user.id] = new_key return {"ok": True}