Open Maopaoya M0-M2: 用户体系+权限开关+后台 / 渠道管理 / 单角色扮演(记忆可篡改+世界书+TTS) / 动态小说管线(实体抽取→建档→立绘→世界书注册) / AES-GCM数据加密+登录解密迁移 / 液态玻璃UI
This commit is contained in:
@@ -0,0 +1,111 @@
|
||||
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}
|
||||
Reference in New Issue
Block a user