apps.py 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758
  1. import secrets
  2. import string
  3. import io
  4. import csv
  5. import pandas as pd
  6. import logging
  7. import json
  8. from typing import List, Optional
  9. from datetime import datetime
  10. from fastapi import APIRouter, Depends, HTTPException, Response, UploadFile, File, Form, Query, Request
  11. from fastapi.responses import StreamingResponse
  12. from sqlalchemy.orm import Session
  13. from sqlalchemy import desc, or_, func
  14. from app.api.v1 import deps
  15. from app.core import security
  16. from app.models.application import Application, ProtocolType
  17. from app.models.user import User, UserStatus
  18. from app.models.mapping import AppUserMapping
  19. from app.models.app_category import AppCategory
  20. from app.core.utils import generate_english_name, get_client_ip
  21. from app.schemas.application import (
  22. ApplicationCreate,
  23. ApplicationUpdate,
  24. ApplicationResponse,
  25. ApplicationList,
  26. ApplicationSecretDisplay,
  27. ViewSecretRequest,
  28. RegenerateSecretRequest,
  29. ApplicationTransferRequest,
  30. AppSyncRequest,
  31. CategoryStats,
  32. AppCategoryCreate,
  33. AppCategoryUpdate,
  34. AppCategoryResponse,
  35. BatchUpdateCategoryRequest
  36. )
  37. from app.schemas.mapping import (
  38. MappingList,
  39. MappingResponse,
  40. MappingCreate,
  41. MappingUpdate,
  42. MappingDelete,
  43. MappingPreviewResponse,
  44. MappingImportSummary,
  45. MappingStrategy,
  46. ImportLogResponse
  47. )
  48. from app.schemas.user import UserSyncRequest, UserSyncList
  49. from app.services.mapping_service import MappingService
  50. from app.services.sms_service import SmsService
  51. from app.services.log_service import LogService
  52. from app.services.hydra_service import hydra_service
  53. from app.schemas.operation_log import ActionType, OperationLogList, OperationLogResponse
  54. router = APIRouter()
  55. logger = logging.getLogger(__name__)
  56. def generate_access_token():
  57. return secrets.token_urlsafe(32)
  58. def generate_app_credentials():
  59. # Generate a random 16-char App ID (hex or alphanumeric)
  60. app_id = "app_" + secrets.token_hex(8)
  61. # Generate a strong 32-char App Secret
  62. alphabet = string.ascii_letters + string.digits
  63. app_secret = ''.join(secrets.choice(alphabet) for i in range(32))
  64. return app_id, app_secret
  65. @router.get("/", response_model=ApplicationList, summary="获取应用列表")
  66. def read_apps(
  67. skip: int = 0,
  68. limit: int = 10,
  69. search: str = None,
  70. category_id: int = None,
  71. db: Session = Depends(deps.get_db),
  72. current_user: User = Depends(deps.get_current_active_user),
  73. ):
  74. """
  75. 获取应用列表(分页)。
  76. 超级管理员可以查看所有,开发者只能查看自己的应用。
  77. category_id:
  78. - None: 获取所有应用
  79. - 0: 获取未分类的应用(category_id IS NULL)
  80. - >0: 获取指定分类的应用
  81. """
  82. query = db.query(Application).filter(Application.is_deleted == False)
  83. if current_user.role != "SUPER_ADMIN":
  84. query = query.filter(Application.owner_id == current_user.id)
  85. # 按分类筛选
  86. if category_id is not None:
  87. if category_id == 0:
  88. # 未分类的应用
  89. query = query.filter(Application.category_id.is_(None))
  90. else:
  91. # 指定分类的应用
  92. query = query.filter(Application.category_id == category_id)
  93. if search:
  94. # Search by name or app_id
  95. query = query.filter(
  96. or_(
  97. Application.app_name.ilike(f"%{search}%"),
  98. Application.app_id.ilike(f"%{search}%")
  99. )
  100. )
  101. total = query.count()
  102. apps = query.order_by(desc(Application.id)).offset(skip).limit(limit).all()
  103. # 为每个应用添加 category_name
  104. items = []
  105. for app in apps:
  106. app_dict = {
  107. **{c.name: getattr(app, c.name) for c in app.__table__.columns},
  108. "category_name": app.category.name if app.category else None
  109. }
  110. items.append(ApplicationResponse(**app_dict))
  111. return {"total": total, "items": items}
  112. @router.get("/categories", response_model=List[CategoryStats], summary="获取所有应用分类")
  113. def get_categories(
  114. db: Session = Depends(deps.get_db),
  115. current_user: User = Depends(deps.get_current_active_user),
  116. search: str = None,
  117. ):
  118. """
  119. 获取所有应用分类及其统计信息。
  120. 包括:预设分类 + 已使用的自定义分类
  121. 超级管理员查看所有,开发者只查看自己应用使用的分类。
  122. """
  123. try:
  124. logger.info(f"[分类管理] 请求开始 - 用户ID: {current_user.id}, 角色: {current_user.role}, 搜索参数: {repr(search)}")
  125. # 获取预设分类
  126. preset_query = db.query(AppCategory).order_by(AppCategory.name)
  127. if search and search.strip():
  128. preset_query = preset_query.filter(AppCategory.name.ilike(f"%{search.strip()}%"))
  129. preset_categories = preset_query.all()
  130. logger.info(f"[分类管理] 预设分类数量: {len(preset_categories)}")
  131. # 统计每个预设分类的应用数量
  132. category_list = []
  133. for cat in preset_categories:
  134. query = db.query(func.count(Application.id)).filter(
  135. Application.is_deleted == False,
  136. Application.category_id == cat.id
  137. )
  138. if current_user.role != "SUPER_ADMIN":
  139. query = query.filter(Application.owner_id == current_user.id)
  140. app_count = query.scalar() or 0
  141. category_list.append(CategoryStats(
  142. category_id=cat.id,
  143. category_name=cat.name,
  144. app_count=app_count
  145. ))
  146. logger.info(f"[分类管理] 最终返回数据数量: {len(category_list)}")
  147. return category_list
  148. except Exception as e:
  149. logger.error(f"[分类管理] 发生未捕获的异常: {e}", exc_info=True)
  150. raise
  151. @router.get("/categories/{category_id}/apps", response_model=ApplicationList, summary="获取分类下的应用列表")
  152. def get_category_apps(
  153. category_id: int,
  154. skip: int = 0,
  155. limit: int = 100,
  156. db: Session = Depends(deps.get_db),
  157. current_user: User = Depends(deps.get_current_active_user),
  158. ):
  159. """获取指定分类下的所有应用"""
  160. category = db.query(AppCategory).filter(AppCategory.id == category_id).first()
  161. if not category:
  162. raise HTTPException(status_code=404, detail="分类不存在")
  163. query = db.query(Application).filter(
  164. Application.is_deleted == False,
  165. Application.category_id == category_id
  166. )
  167. if current_user.role != "SUPER_ADMIN":
  168. query = query.filter(Application.owner_id == current_user.id)
  169. total = query.count()
  170. apps = query.order_by(desc(Application.id)).offset(skip).limit(limit).all()
  171. # 为每个应用添加 category_name
  172. items = []
  173. for app in apps:
  174. app_dict = {
  175. **{c.name: getattr(app, c.name) for c in app.__table__.columns},
  176. "category_name": app.category.name if app.category else None
  177. }
  178. items.append(ApplicationResponse(**app_dict))
  179. return {"total": total, "items": items}
  180. @router.post("/categories/batch-update", summary="批量更新应用分类")
  181. def batch_update_app_category(
  182. req: BatchUpdateCategoryRequest,
  183. db: Session = Depends(deps.get_db),
  184. current_user: User = Depends(deps.get_current_active_user),
  185. ):
  186. """批量更新应用的分类"""
  187. if not req.password:
  188. raise HTTPException(status_code=400, detail="需要提供管理员密码")
  189. if not security.verify_password(req.password, current_user.password_hash):
  190. raise HTTPException(status_code=400, detail="密码错误")
  191. if not req.app_ids:
  192. raise HTTPException(status_code=400, detail="请选择要更新的应用")
  193. # 验证分类是否存在(如果提供了 category_id)
  194. if req.category_id:
  195. category = db.query(AppCategory).filter(AppCategory.id == req.category_id).first()
  196. if not category:
  197. raise HTTPException(status_code=404, detail="分类不存在")
  198. # 查询要更新的应用
  199. query = db.query(Application).filter(
  200. Application.id.in_(req.app_ids),
  201. Application.is_deleted == False
  202. )
  203. if current_user.role != "SUPER_ADMIN":
  204. query = query.filter(Application.owner_id == current_user.id)
  205. apps = query.all()
  206. if len(apps) != len(req.app_ids):
  207. raise HTTPException(status_code=403, detail="部分应用不存在或无权限")
  208. # 批量更新分类
  209. updated_count = 0
  210. for app in apps:
  211. app.category_id = req.category_id
  212. db.add(app)
  213. updated_count += 1
  214. db.commit()
  215. action = f"设置为分类ID {req.category_id}" if req.category_id else "移除分类"
  216. logger.info(f"批量更新应用分类成功: {updated_count}个应用 {action} (Operator: {current_user.mobile})")
  217. return {"message": f"成功更新 {updated_count} 个应用的分类", "count": updated_count}
  218. @router.delete("/categories/{category_id}", summary="删除分类")
  219. def delete_category(
  220. category_id: int,
  221. verification_code: str = Query(..., description="手机验证码"),
  222. db: Session = Depends(deps.get_db),
  223. current_user: User = Depends(deps.get_current_active_user),
  224. ):
  225. """
  226. 删除分类。
  227. 注意:必须先移出该分类下的所有应用才能删除分类。
  228. 需要手机验证码验证。
  229. """
  230. if not SmsService.verify_code(current_user.mobile, verification_code):
  231. raise HTTPException(status_code=400, detail="验证码无效或已过期")
  232. category = db.query(AppCategory).filter(AppCategory.id == category_id).first()
  233. if not category:
  234. raise HTTPException(status_code=404, detail="分类不存在")
  235. # 检查是否有应用使用此分类
  236. apps_count = db.query(Application).filter(
  237. Application.is_deleted == False,
  238. Application.category_id == category_id
  239. ).count()
  240. if apps_count > 0:
  241. raise HTTPException(
  242. status_code=400,
  243. detail=f"无法删除:有 {apps_count} 个应用正在使用此分类。请先移出这些应用后再删除分类。"
  244. )
  245. db.delete(category)
  246. db.commit()
  247. logger.info(f"分类删除成功: {category.name} (Operator: {current_user.mobile})")
  248. return {"message": f"成功删除分类 '{category.name}'"}
  249. # ==========================================
  250. # Preset Category Management
  251. # ==========================================
  252. @router.get("/preset-categories", response_model=List[AppCategoryResponse], summary="获取预设分类列表")
  253. def get_preset_categories(
  254. db: Session = Depends(deps.get_db),
  255. current_user: User = Depends(deps.get_current_active_user),
  256. ):
  257. """获取所有预设分类"""
  258. categories = db.query(AppCategory).order_by(AppCategory.name).all()
  259. return categories
  260. @router.post("/preset-categories", response_model=AppCategoryResponse, summary="创建预设分类")
  261. def create_preset_category(
  262. category_in: AppCategoryCreate,
  263. db: Session = Depends(deps.get_db),
  264. current_user: User = Depends(deps.get_current_active_user),
  265. ):
  266. """创建预设分类(仅超级管理员)"""
  267. if current_user.role != "SUPER_ADMIN":
  268. raise HTTPException(status_code=403, detail="权限不足")
  269. # 检查分类名是否已存在
  270. existing = db.query(AppCategory).filter(AppCategory.name == category_in.name).first()
  271. if existing:
  272. raise HTTPException(status_code=400, detail=f"分类 '{category_in.name}' 已存在")
  273. category = AppCategory(**category_in.model_dump())
  274. db.add(category)
  275. db.commit()
  276. db.refresh(category)
  277. logger.info(f"预设分类创建成功: {category_in.name} (Operator: {current_user.mobile})")
  278. return category
  279. @router.put("/preset-categories/{category_id}", response_model=AppCategoryResponse, summary="更新预设分类")
  280. def update_preset_category(
  281. category_id: int,
  282. category_in: AppCategoryUpdate,
  283. db: Session = Depends(deps.get_db),
  284. current_user: User = Depends(deps.get_current_active_user),
  285. ):
  286. """更新预设分类(仅超级管理员,需要密码验证)"""
  287. if current_user.role != "SUPER_ADMIN":
  288. raise HTTPException(status_code=403, detail="权限不足")
  289. # 密码验证
  290. if not category_in.password:
  291. raise HTTPException(status_code=400, detail="需要提供密码")
  292. from app.core import security
  293. if not security.verify_password(category_in.password, current_user.password_hash):
  294. logger.warning(f"预设分类更新失败: 密码错误 (User: {current_user.mobile})")
  295. raise HTTPException(status_code=403, detail="密码错误")
  296. category = db.query(AppCategory).filter(AppCategory.id == category_id).first()
  297. if not category:
  298. raise HTTPException(status_code=404, detail="预设分类未找到")
  299. # 如果更新名称,检查是否重复
  300. if category_in.name and category_in.name != category.name:
  301. existing = db.query(AppCategory).filter(AppCategory.name == category_in.name).first()
  302. if existing:
  303. raise HTTPException(status_code=400, detail=f"分类 '{category_in.name}' 已存在")
  304. update_data = category_in.model_dump(exclude_unset=True)
  305. # 移除密码字段,不保存到数据库
  306. update_data.pop('password', None)
  307. for field, value in update_data.items():
  308. setattr(category, field, value)
  309. db.commit()
  310. db.refresh(category)
  311. logger.info(f"预设分类更新成功: {category.name} (Operator: {current_user.mobile})")
  312. return category
  313. @router.delete("/preset-categories/{category_id}", summary="删除预设分类")
  314. def delete_preset_category(
  315. category_id: int,
  316. db: Session = Depends(deps.get_db),
  317. current_user: User = Depends(deps.get_current_active_user),
  318. ):
  319. """删除预设分类(仅超级管理员)"""
  320. if current_user.role != "SUPER_ADMIN":
  321. raise HTTPException(status_code=403, detail="权限不足")
  322. category = db.query(AppCategory).filter(AppCategory.id == category_id).first()
  323. if not category:
  324. raise HTTPException(status_code=404, detail="预设分类未找到")
  325. # 检查是否有应用使用此分类
  326. apps_count = db.query(Application).filter(
  327. Application.category_id == category.id,
  328. Application.is_deleted == False
  329. ).count()
  330. if apps_count > 0:
  331. raise HTTPException(
  332. status_code=400,
  333. detail=f"无法删除:有 {apps_count} 个应用正在使用此分类"
  334. )
  335. db.delete(category)
  336. db.commit()
  337. logger.info(f"预设分类删除成功: {category.name} (Operator: {current_user.mobile})")
  338. return {"message": "删除成功"}
  339. @router.get("/{app_id}", response_model=ApplicationResponse, summary="获取单个应用详情")
  340. def read_app(
  341. *,
  342. db: Session = Depends(deps.get_db),
  343. app_id: int,
  344. current_user: User = Depends(deps.get_current_active_user),
  345. ):
  346. """
  347. 获取单个应用详情。
  348. """
  349. app = db.query(Application).filter(Application.id == app_id).first()
  350. if not app:
  351. raise HTTPException(status_code=404, detail="应用未找到")
  352. if current_user.role != "SUPER_ADMIN" and app.owner_id != current_user.id:
  353. raise HTTPException(status_code=403, detail="权限不足")
  354. # 设置 category_name
  355. app_dict = {
  356. **{c.name: getattr(app, c.name) for c in app.__table__.columns},
  357. "category_name": app.category.name if app.category else None
  358. }
  359. return ApplicationResponse(**app_dict)
  360. @router.post("/", response_model=ApplicationSecretDisplay, summary="创建应用")
  361. def create_app(
  362. *,
  363. db: Session = Depends(deps.get_db),
  364. app_in: ApplicationCreate,
  365. current_user: User = Depends(deps.get_current_active_user),
  366. ):
  367. """
  368. 创建新应用。只会返回一次明文密钥。
  369. """
  370. # 1. Generate ID and Secret
  371. app_id, app_secret = generate_app_credentials()
  372. # 2. Generate Access Token
  373. access_token = generate_access_token()
  374. # 3. Store Secret (Plain text needed for HMAC verification)
  375. db_app = Application(
  376. app_id=app_id,
  377. app_secret=app_secret,
  378. access_token=access_token,
  379. app_name=app_in.app_name,
  380. icon_url=app_in.icon_url,
  381. protocol_type=app_in.protocol_type,
  382. redirect_uris=app_in.redirect_uris,
  383. notification_url=app_in.notification_url,
  384. description=app_in.description,
  385. category_id=app_in.category_id,
  386. owner_id=current_user.id # Assign owner
  387. )
  388. # 验证 category_id 是否存在
  389. if app_in.category_id:
  390. category = db.query(AppCategory).filter(AppCategory.id == app_in.category_id).first()
  391. if not category:
  392. raise HTTPException(status_code=400, detail=f"分类ID {app_in.category_id} 不存在")
  393. db.add(db_app)
  394. db.commit()
  395. db.refresh(db_app)
  396. logger.info(f"应用创建成功: {app_in.app_name} (ID: {app_id}, Owner: {current_user.mobile})")
  397. # 如果是 OIDC 应用,自动在 Hydra 中创建 / 更新对应的 OAuth2 Client
  398. if db_app.protocol_type == ProtocolType.OIDC:
  399. try:
  400. raw = db_app.redirect_uris or ""
  401. redirect_uris: list[str] = []
  402. if raw:
  403. # 1. 优先按 JSON 解析(支持 ["url1","url2"] 或 "url1")
  404. try:
  405. parsed = json.loads(raw)
  406. if isinstance(parsed, list):
  407. redirect_uris = [str(u).strip() for u in parsed if str(u).strip()]
  408. elif isinstance(parsed, str):
  409. if parsed.strip():
  410. redirect_uris = [parsed.strip()]
  411. except Exception:
  412. # 2. 非 JSON 时,支持逗号分隔或单个 URL
  413. parts = [u.strip() for u in raw.split(",") if u.strip()]
  414. if parts:
  415. redirect_uris = parts
  416. hydra_service.create_or_update_client(
  417. client_id=db_app.app_id,
  418. client_secret=db_app.app_secret,
  419. redirect_uris=redirect_uris,
  420. client_name=db_app.app_name or db_app.app_id,
  421. )
  422. logger.info(f"Hydra OIDC Client 已创建/更新: {db_app.app_id}, redirect_uris={redirect_uris}")
  423. except Exception as e:
  424. logger.exception(
  425. "应用创建成功,但在 Hydra 创建 OIDC Client 失败 (app_id=%s): %s",
  426. db_app.app_id,
  427. e,
  428. )
  429. # 如需强一致,可以在这里 raise HTTPException 中断创建流程
  430. return ApplicationSecretDisplay(app_id=app_id, app_secret=app_secret, access_token=access_token)
  431. @router.put("/{app_id}", response_model=ApplicationResponse, summary="更新应用")
  432. def update_app(
  433. *,
  434. db: Session = Depends(deps.get_db),
  435. app_id: int,
  436. app_in: ApplicationUpdate,
  437. current_user: User = Depends(deps.get_current_active_user),
  438. ):
  439. """
  440. 更新应用信息。需要手机验证码和密码验证。
  441. """
  442. app = db.query(Application).filter(Application.id == app_id).first()
  443. if not app:
  444. raise HTTPException(status_code=404, detail="应用未找到")
  445. # Check ownership
  446. if current_user.role != "SUPER_ADMIN" and app.owner_id != current_user.id:
  447. raise HTTPException(status_code=403, detail="权限不足")
  448. # Security Verification
  449. if not app_in.verification_code:
  450. raise HTTPException(status_code=400, detail="需要提供手机验证码")
  451. if not SmsService.verify_code(current_user.mobile, app_in.verification_code):
  452. logger.warning(f"应用更新失败: 验证码错误 (User: {current_user.mobile})")
  453. raise HTTPException(status_code=400, detail="验证码无效或已过期")
  454. update_data = app_in.model_dump(exclude_unset=True)
  455. # Remove security fields from update data
  456. update_data.pop('password', None)
  457. update_data.pop('verification_code', None)
  458. # 验证 category_id 是否存在
  459. if 'category_id' in update_data and update_data['category_id']:
  460. category = db.query(AppCategory).filter(AppCategory.id == update_data['category_id']).first()
  461. if not category:
  462. raise HTTPException(status_code=400, detail=f"分类ID {update_data['category_id']} 不存在")
  463. for field, value in update_data.items():
  464. setattr(app, field, value)
  465. db.add(app)
  466. db.commit()
  467. db.refresh(app)
  468. # 如果是 OIDC 应用,编辑后同步 Hydra 中的 OAuth2 Client
  469. if app.protocol_type == ProtocolType.OIDC:
  470. try:
  471. raw = app.redirect_uris or ""
  472. redirect_uris: list[str] = []
  473. if raw:
  474. # 1. 优先按 JSON 解析(支持 ["url1","url2"] 或 "url1")
  475. try:
  476. parsed = json.loads(raw)
  477. if isinstance(parsed, list):
  478. redirect_uris = [str(u).strip() for u in parsed if str(u).strip()]
  479. elif isinstance(parsed, str):
  480. if parsed.strip():
  481. redirect_uris = [parsed.strip()]
  482. except Exception:
  483. # 2. 非 JSON 时,支持逗号分隔或单个 URL
  484. parts = [u.strip() for u in raw.split(",") if u.strip()]
  485. if parts:
  486. redirect_uris = parts
  487. hydra_service.create_or_update_client(
  488. client_id=app.app_id,
  489. client_secret=app.app_secret,
  490. redirect_uris=redirect_uris,
  491. client_name=app.app_name or app.app_id,
  492. )
  493. logger.info(f"Hydra OIDC Client 已在编辑后同步: {app.app_id}, redirect_uris={redirect_uris}")
  494. except Exception as e:
  495. logger.exception(
  496. "应用编辑成功,但在 Hydra 同步 OIDC Client 失败 (app_id=%s): %s",
  497. app.app_id,
  498. e,
  499. )
  500. # 5. Log
  501. LogService.create_log(
  502. db=db,
  503. app_id=app.id,
  504. operator_id=current_user.id,
  505. action_type=ActionType.UPDATE,
  506. details=update_data
  507. )
  508. logger.info(f"应用更新成功: {app.app_name} (ID: {app.app_id})")
  509. return app
  510. @router.delete("/{app_id}", response_model=ApplicationResponse, summary="删除应用")
  511. def delete_app(
  512. *,
  513. db: Session = Depends(deps.get_db),
  514. app_id: int,
  515. current_user: User = Depends(deps.get_current_active_user),
  516. ):
  517. """
  518. 软删除应用。
  519. """
  520. app = db.query(Application).filter(Application.id == app_id).first()
  521. if not app:
  522. raise HTTPException(status_code=404, detail="应用未找到")
  523. # Check ownership
  524. if current_user.role != "SUPER_ADMIN" and app.owner_id != current_user.id:
  525. raise HTTPException(status_code=403, detail="权限不足")
  526. app.is_deleted = True
  527. db.add(app)
  528. db.commit()
  529. logger.info(f"应用删除成功: {app.app_name} (ID: {app.app_id}, Operator: {current_user.mobile})")
  530. return app
  531. @router.post("/{app_id}/regenerate-secret", response_model=ApplicationSecretDisplay, summary="重新生成密钥")
  532. def regenerate_secret(
  533. *,
  534. db: Session = Depends(deps.get_db),
  535. app_id: int,
  536. req: RegenerateSecretRequest,
  537. current_user: User = Depends(deps.get_current_active_user),
  538. ):
  539. """
  540. 重新生成应用密钥。需要手机验证码和密码验证。
  541. """
  542. app = db.query(Application).filter(Application.id == app_id).first()
  543. if not app:
  544. raise HTTPException(status_code=404, detail="应用未找到")
  545. # Check ownership
  546. if current_user.role != "SUPER_ADMIN" and app.owner_id != current_user.id:
  547. raise HTTPException(status_code=403, detail="权限不足")
  548. # Security Verification
  549. if not security.verify_password(req.password, current_user.password_hash):
  550. logger.warning(f"重置密钥失败: 密码错误 (User: {current_user.mobile})")
  551. raise HTTPException(status_code=403, detail="密码错误")
  552. if not SmsService.verify_code(current_user.mobile, req.verification_code):
  553. logger.warning(f"重置密钥失败: 验证码错误 (User: {current_user.mobile})")
  554. raise HTTPException(status_code=400, detail="验证码无效或已过期")
  555. _, new_secret = generate_app_credentials()
  556. app.app_secret = new_secret
  557. db.add(app)
  558. db.commit()
  559. # Log
  560. LogService.create_log(
  561. db=db,
  562. app_id=app.id,
  563. operator_id=current_user.id,
  564. action_type=ActionType.REGENERATE_SECRET,
  565. details={"message": "Regenerated App Secret"}
  566. )
  567. logger.info(f"应用密钥已重置: {app.app_name} (ID: {app.app_id})")
  568. return ApplicationSecretDisplay(app_id=app.app_id, app_secret=new_secret, access_token=app.access_token)
  569. @router.post("/{app_id}/view-secret", response_model=ApplicationSecretDisplay, summary="查看密钥")
  570. def view_secret(
  571. *,
  572. db: Session = Depends(deps.get_db),
  573. app_id: int,
  574. req: ViewSecretRequest,
  575. current_user: User = Depends(deps.get_current_active_user),
  576. ):
  577. """
  578. 查看应用密钥。需要验证用户密码。
  579. """
  580. # 1. Verify Password
  581. if not security.verify_password(req.password, current_user.password_hash):
  582. logger.warning(f"查看密钥失败: 密码错误 (User: {current_user.mobile})")
  583. raise HTTPException(status_code=403, detail="密码错误")
  584. app = db.query(Application).filter(Application.id == app_id).first()
  585. if not app:
  586. raise HTTPException(status_code=404, detail="应用未找到")
  587. # Check ownership
  588. if current_user.role != "SUPER_ADMIN" and app.owner_id != current_user.id:
  589. raise HTTPException(status_code=403, detail="权限不足")
  590. # Log
  591. LogService.create_log(
  592. db=db,
  593. app_id=app.id,
  594. operator_id=current_user.id,
  595. action_type=ActionType.VIEW_SECRET,
  596. details={"message": "Viewed App Secret"}
  597. )
  598. logger.info(f"查看应用密钥: {app.app_name} (Operator: {current_user.mobile})")
  599. return ApplicationSecretDisplay(app_id=app.app_id, app_secret=app.app_secret, access_token=app.access_token)
  600. @router.post("/{app_id}/transfer", response_model=ApplicationResponse, summary="转让应用")
  601. def transfer_app(
  602. *,
  603. db: Session = Depends(deps.get_db),
  604. app_id: int,
  605. req: ApplicationTransferRequest,
  606. current_user: User = Depends(deps.get_current_active_user),
  607. ):
  608. """
  609. 将应用转让给其他开发者或超级管理员。
  610. 需要验证:目标用户手机号、当前用户密码、短信验证码。
  611. """
  612. app = db.query(Application).filter(Application.id == app_id).first()
  613. if not app:
  614. raise HTTPException(status_code=404, detail="应用未找到")
  615. # Check ownership
  616. if current_user.role != "SUPER_ADMIN" and app.owner_id != current_user.id:
  617. raise HTTPException(status_code=403, detail="权限不足")
  618. # 1. Verify Password
  619. if not security.verify_password(req.password, current_user.password_hash):
  620. logger.warning(f"转让应用失败: 密码错误 (User: {current_user.mobile})")
  621. raise HTTPException(status_code=403, detail="密码错误")
  622. # 2. Verify SMS Code
  623. if not SmsService.verify_code(current_user.mobile, req.verification_code):
  624. logger.warning(f"转让应用失败: 验证码错误 (User: {current_user.mobile})")
  625. raise HTTPException(status_code=400, detail="验证码无效或已过期")
  626. # 3. Verify Target User
  627. target_user = db.query(User).filter(User.mobile == req.target_mobile, User.is_deleted == 0).first()
  628. if not target_user:
  629. raise HTTPException(status_code=404, detail="目标用户不存在")
  630. if target_user.status != "ACTIVE":
  631. raise HTTPException(status_code=400, detail="目标用户状态不正常")
  632. if target_user.role not in ["DEVELOPER", "SUPER_ADMIN"]:
  633. raise HTTPException(status_code=400, detail="目标用户必须是开发者或超级管理员")
  634. if target_user.id == app.owner_id:
  635. raise HTTPException(status_code=400, detail="应用已归属于该用户")
  636. # 4. Transfer
  637. old_owner_id = app.owner_id
  638. app.owner_id = target_user.id
  639. db.add(app)
  640. db.commit()
  641. db.refresh(app)
  642. # 5. Log
  643. LogService.create_log(
  644. db=db,
  645. app_id=app.id,
  646. operator_id=current_user.id,
  647. action_type=ActionType.TRANSFER,
  648. target_user_id=target_user.id,
  649. target_mobile=target_user.mobile,
  650. details={
  651. "old_owner_id": old_owner_id,
  652. "new_owner_id": target_user.id
  653. }
  654. )
  655. logger.info(f"应用转让成功: {app.app_name} 从 {current_user.mobile} 转让给 {target_user.mobile}")
  656. return app
  657. # ==========================================
  658. # Mappings
  659. # ==========================================
  660. @router.get("/{app_id}/mappings", response_model=MappingList, summary="获取应用映射列表")
  661. def read_mappings(
  662. *,
  663. db: Session = Depends(deps.get_db),
  664. app_id: int,
  665. skip: int = 0,
  666. limit: int = 10,
  667. search: Optional[str] = Query(None, description="按手机号、映射账号、映射邮箱模糊匹配"),
  668. mapping_is_active: Optional[bool] = Query(None, description="映射是否启用,不传不筛选"),
  669. user_status: Optional[str] = Query(None, description="统一认证账号状态:ACTIVE|PENDING|DISABLED|DELETED"),
  670. current_user: User = Depends(deps.get_current_active_user),
  671. ):
  672. """
  673. 获取应用的账号映射列表。
  674. """
  675. app = db.query(Application).filter(Application.id == app_id).first()
  676. if not app:
  677. raise HTTPException(status_code=404, detail="应用未找到")
  678. if current_user.role != "SUPER_ADMIN" and app.owner_id != current_user.id:
  679. raise HTTPException(status_code=403, detail="权限不足")
  680. query = db.query(AppUserMapping).filter(AppUserMapping.app_id == app_id)
  681. if mapping_is_active is not None:
  682. query = query.filter(AppUserMapping.is_active == mapping_is_active)
  683. need_user_join = bool(search and search.strip()) or bool(user_status and user_status.strip())
  684. if need_user_join:
  685. query = query.outerjoin(User, AppUserMapping.user_id == User.id)
  686. if search and search.strip():
  687. term = f"%{search.strip()}%"
  688. query = query.filter(
  689. or_(
  690. AppUserMapping.mapped_key.ilike(term),
  691. AppUserMapping.mapped_email.ilike(term),
  692. User.mobile.ilike(term),
  693. )
  694. )
  695. if user_status and user_status.strip():
  696. st = user_status.strip().upper()
  697. if st == "DELETED":
  698. query = query.filter(User.id.is_(None))
  699. elif st in ("ACTIVE", "PENDING", "DISABLED"):
  700. query = query.filter(User.status == UserStatus[st])
  701. else:
  702. raise HTTPException(status_code=400, detail="无效的 user_status")
  703. total = query.count()
  704. mappings = query.order_by(desc(AppUserMapping.id)).offset(skip).limit(limit).all()
  705. # Enrich with user mobile (handled by ORM relation usually, but for Pydantic 'from_attributes')
  706. # We added `user_mobile` to MappingResponse, so we need to ensure it's populated.
  707. # The ORM `mapping.user` is lazy loaded, which is fine for sync code.
  708. result = []
  709. for m in mappings:
  710. result.append(MappingResponse(
  711. id=m.id,
  712. app_id=m.app_id,
  713. user_id=m.user_id,
  714. mapped_key=m.mapped_key,
  715. mapped_email=m.mapped_email,
  716. user_mobile=m.user.mobile if m.user else "Deleted User",
  717. user_status=m.user.status if m.user else "DELETED",
  718. is_active=m.is_active
  719. ))
  720. return {"total": total, "items": result}
  721. @router.post("/{app_id}/mappings", response_model=MappingResponse, summary="创建映射")
  722. def create_mapping(
  723. *,
  724. db: Session = Depends(deps.get_db),
  725. app_id: int,
  726. mapping_in: MappingCreate,
  727. current_user: User = Depends(deps.get_current_active_user),
  728. ):
  729. """
  730. 手动创建映射。
  731. """
  732. app = db.query(Application).filter(Application.id == app_id).first()
  733. if not app:
  734. raise HTTPException(status_code=404, detail="应用未找到")
  735. if current_user.role != "SUPER_ADMIN" and app.owner_id != current_user.id:
  736. raise HTTPException(status_code=403, detail="权限不足")
  737. # Verify Password
  738. if not security.verify_password(mapping_in.password, current_user.password_hash):
  739. logger.warning(f"创建映射失败: 密码错误 (User: {current_user.mobile})")
  740. raise HTTPException(status_code=403, detail="密码错误")
  741. # Normalize input: treat empty strings as None to avoid unique constraint violations
  742. mapped_key = mapping_in.mapped_key if mapping_in.mapped_key else None
  743. mapped_email = mapping_in.mapped_email if mapping_in.mapped_email else None
  744. # 1. Find User or Create
  745. user = db.query(User).filter(User.mobile == mapping_in.mobile, User.is_deleted == 0).first()
  746. new_user_created = False
  747. generated_password = None
  748. if not user:
  749. # Auto create user
  750. password_plain = security.generate_alphanumeric_password(8) # Random password letters+digits
  751. random_suffix = security.generate_alphanumeric_password(6)
  752. user = User(
  753. mobile=mapping_in.mobile,
  754. password_hash=security.get_password_hash(password_plain),
  755. status="ACTIVE",
  756. role="ORDINARY_USER",
  757. name=f"用户{random_suffix}",
  758. english_name=mapped_key
  759. )
  760. db.add(user)
  761. db.commit()
  762. db.refresh(user)
  763. new_user_created = True
  764. generated_password = password_plain
  765. logger.info(f"自动创建用户: {user.mobile}")
  766. # 2. Check if mapping exists
  767. existing = db.query(AppUserMapping).filter(
  768. AppUserMapping.app_id == app_id,
  769. AppUserMapping.user_id == user.id
  770. ).first()
  771. if existing:
  772. raise HTTPException(status_code=400, detail="该用户的映射已存在")
  773. # 3. Check Uniqueness for mapped_email (if provided)
  774. if mapped_email:
  775. email_exists = db.query(AppUserMapping).filter(
  776. AppUserMapping.app_id == app_id,
  777. AppUserMapping.mapped_email == mapped_email
  778. ).first()
  779. if email_exists:
  780. raise HTTPException(status_code=400, detail=f"该应用下邮箱 {mapped_email} 已被使用")
  781. # 4. Check Uniqueness for mapped_key
  782. if mapped_key:
  783. key_exists = db.query(AppUserMapping).filter(
  784. AppUserMapping.app_id == app_id,
  785. AppUserMapping.mapped_key == mapped_key
  786. ).first()
  787. if key_exists:
  788. raise HTTPException(status_code=400, detail=f"该应用下账号 {mapped_key} 已被使用")
  789. # 5. Create
  790. mapping = AppUserMapping(
  791. app_id=app_id,
  792. user_id=user.id,
  793. mapped_key=mapped_key,
  794. mapped_email=mapped_email
  795. )
  796. db.add(mapping)
  797. db.commit()
  798. db.refresh(mapping)
  799. # LOGGING
  800. LogService.create_log(
  801. db=db,
  802. app_id=app_id,
  803. operator_id=current_user.id,
  804. action_type=ActionType.MANUAL_ADD,
  805. target_user_id=user.id,
  806. target_mobile=user.mobile,
  807. details={
  808. "mapped_key": mapped_key,
  809. "mapped_email": mapped_email,
  810. "new_user_created": new_user_created
  811. }
  812. )
  813. logger.info(f"映射创建成功: App {app_id} -> User {user.mobile} ({mapped_key})")
  814. return MappingResponse(
  815. id=mapping.id,
  816. app_id=mapping.app_id,
  817. user_id=mapping.user_id,
  818. mapped_key=mapping.mapped_key,
  819. mapped_email=mapping.mapped_email,
  820. user_mobile=user.mobile,
  821. user_status=user.status,
  822. is_active=mapping.is_active,
  823. new_user_created=new_user_created,
  824. generated_password=generated_password
  825. )
  826. @router.put("/{app_id}/mappings/{mapping_id}", response_model=MappingResponse, summary="更新映射")
  827. def update_mapping(
  828. *,
  829. db: Session = Depends(deps.get_db),
  830. app_id: int,
  831. mapping_id: int,
  832. mapping_in: MappingUpdate,
  833. current_user: User = Depends(deps.get_current_active_user),
  834. ):
  835. """
  836. 更新映射信息。
  837. """
  838. app = db.query(Application).filter(Application.id == app_id).first()
  839. if not app:
  840. raise HTTPException(status_code=404, detail="应用未找到")
  841. if current_user.role != "SUPER_ADMIN" and app.owner_id != current_user.id:
  842. raise HTTPException(status_code=403, detail="权限不足")
  843. # Verify Password
  844. if not security.verify_password(mapping_in.password, current_user.password_hash):
  845. logger.warning(f"更新映射失败: 密码错误 (User: {current_user.mobile})")
  846. raise HTTPException(status_code=403, detail="密码错误")
  847. mapping = db.query(AppUserMapping).filter(
  848. AppUserMapping.id == mapping_id,
  849. AppUserMapping.app_id == app_id
  850. ).first()
  851. if not mapping:
  852. raise HTTPException(status_code=404, detail="映射未找到")
  853. # Check Uniqueness for mapped_key
  854. if mapping_in.mapped_key is not None and mapping_in.mapped_key != mapping.mapped_key:
  855. if mapping_in.mapped_key:
  856. key_exists = db.query(AppUserMapping).filter(
  857. AppUserMapping.app_id == app_id,
  858. AppUserMapping.mapped_key == mapping_in.mapped_key
  859. ).first()
  860. if key_exists:
  861. raise HTTPException(status_code=400, detail=f"该应用下账号 {mapping_in.mapped_key} 已被使用")
  862. # Check Uniqueness for mapped_email
  863. if mapping_in.mapped_email is not None and mapping_in.mapped_email != mapping.mapped_email:
  864. if mapping_in.mapped_email:
  865. email_exists = db.query(AppUserMapping).filter(
  866. AppUserMapping.app_id == app_id,
  867. AppUserMapping.mapped_email == mapping_in.mapped_email
  868. ).first()
  869. if email_exists:
  870. raise HTTPException(status_code=400, detail=f"该应用下邮箱 {mapping_in.mapped_email} 已被使用")
  871. # Capture old values for logging
  872. old_key = mapping.mapped_key
  873. old_email = mapping.mapped_email
  874. old_is_active = mapping.is_active
  875. if mapping_in.mapped_key is not None:
  876. mapping.mapped_key = mapping_in.mapped_key
  877. if mapping_in.mapped_email is not None:
  878. mapping.mapped_email = mapping_in.mapped_email
  879. if mapping_in.is_active is not None:
  880. mapping.is_active = mapping_in.is_active
  881. db.add(mapping)
  882. db.commit()
  883. db.refresh(mapping)
  884. # LOGGING
  885. LogService.create_log(
  886. db=db,
  887. app_id=app_id,
  888. operator_id=current_user.id,
  889. action_type=ActionType.UPDATE,
  890. target_user_id=mapping.user_id,
  891. target_mobile=mapping.user.mobile if mapping.user else None,
  892. details={
  893. "old": {
  894. "mapped_key": old_key,
  895. "mapped_email": old_email,
  896. "is_active": old_is_active,
  897. },
  898. "new": {
  899. "mapped_key": mapping.mapped_key,
  900. "mapped_email": mapping.mapped_email,
  901. "is_active": mapping.is_active,
  902. },
  903. }
  904. )
  905. logger.info(f"映射更新成功: App {app_id} User {mapping.user.mobile if mapping.user else 'unknown'}")
  906. return MappingResponse(
  907. id=mapping.id,
  908. app_id=mapping.app_id,
  909. user_id=mapping.user_id,
  910. mapped_key=mapping.mapped_key,
  911. mapped_email=mapping.mapped_email,
  912. user_mobile=mapping.user.mobile if mapping.user else "Deleted User",
  913. user_status=mapping.user.status if mapping.user else "DELETED",
  914. is_active=mapping.is_active
  915. )
  916. @router.delete("/{app_id}/mappings/{mapping_id}", summary="删除映射")
  917. def delete_mapping(
  918. *,
  919. db: Session = Depends(deps.get_db),
  920. app_id: int,
  921. mapping_id: int,
  922. req: MappingDelete,
  923. current_user: User = Depends(deps.get_current_active_user),
  924. ):
  925. """
  926. 删除映射关系。需验证密码。
  927. """
  928. # Verify Password
  929. if not security.verify_password(req.password, current_user.password_hash):
  930. logger.warning(f"删除映射失败: 密码错误 (User: {current_user.mobile})")
  931. raise HTTPException(status_code=403, detail="密码错误")
  932. mapping = db.query(AppUserMapping).filter(
  933. AppUserMapping.id == mapping_id,
  934. AppUserMapping.app_id == app_id
  935. ).first()
  936. if not mapping:
  937. raise HTTPException(status_code=404, detail="映射未找到")
  938. app = db.query(Application).filter(Application.id == app_id).first()
  939. if current_user.role != "SUPER_ADMIN" and app.owner_id != current_user.id:
  940. raise HTTPException(status_code=403, detail="权限不足")
  941. # Capture for logging
  942. target_user_id = mapping.user_id
  943. target_mobile = mapping.user.mobile if mapping.user else None
  944. db.delete(mapping)
  945. db.commit()
  946. # LOGGING
  947. LogService.create_log(
  948. db=db,
  949. app_id=app_id,
  950. operator_id=current_user.id,
  951. action_type=ActionType.DELETE,
  952. target_user_id=target_user_id,
  953. target_mobile=target_mobile,
  954. details={"mapping_id": mapping_id}
  955. )
  956. logger.info(f"映射删除成功: App {app_id}, Mapping {mapping_id}")
  957. return {"message": "删除成功"}
  958. @router.post("/{app_id}/sync-users", summary="同步所有用户")
  959. def sync_users_to_app(
  960. *,
  961. db: Session = Depends(deps.get_db),
  962. app_id: int,
  963. current_user: User = Depends(deps.get_current_active_user),
  964. ):
  965. """
  966. 一键导入用户管理中的用户数据到应用映射中。
  967. """
  968. app = db.query(Application).filter(Application.id == app_id).first()
  969. if not app:
  970. raise HTTPException(status_code=404, detail="应用未找到")
  971. if current_user.role != "SUPER_ADMIN" and app.owner_id != current_user.id:
  972. raise HTTPException(status_code=403, detail="权限不足")
  973. # Get all active users
  974. users = db.query(User).filter(User.is_deleted == 0).all()
  975. # Get existing mappings (user_ids)
  976. existing_mappings = db.query(AppUserMapping).filter(AppUserMapping.app_id == app_id).all()
  977. mapped_user_ids = {m.user_id for m in existing_mappings}
  978. new_mappings = []
  979. logger.info(f"开始同步用户到应用 {app.app_name} (ID: {app_id})")
  980. for user in users:
  981. if user.id in mapped_user_ids:
  982. continue
  983. # Create mapping
  984. mapped_key = user.english_name if user.english_name else user.mobile
  985. mapping = AppUserMapping(
  986. app_id=app.id,
  987. user_id=user.id,
  988. mapped_key=mapped_key,
  989. mapped_email=None,
  990. is_active=True
  991. )
  992. new_mappings.append(mapping)
  993. if new_mappings:
  994. try:
  995. db.bulk_save_objects(new_mappings)
  996. db.commit()
  997. logger.info(f"用户同步完成: 新增 {len(new_mappings)} 条映射")
  998. except Exception as e:
  999. db.rollback()
  1000. logger.error(f"批量同步用户失败: {e}。尝试逐条插入。")
  1001. # Fallback: try one by one
  1002. success_count = 0
  1003. for m in new_mappings:
  1004. try:
  1005. db.add(m)
  1006. db.commit()
  1007. success_count += 1
  1008. except Exception as ex:
  1009. db.rollback()
  1010. logger.warning(f"单个用户映射失败 (User: {m.user_id}): {ex}")
  1011. LogService.create_log(
  1012. db=db,
  1013. app_id=app.id,
  1014. operator_id=current_user.id,
  1015. action_type=ActionType.IMPORT,
  1016. details={"message": "Sync all users (partial)", "attempted": len(new_mappings), "success": success_count}
  1017. )
  1018. return {"message": f"同步完成,成功 {success_count} 个,失败 {len(new_mappings) - success_count} 个 (可能是账号冲突)"}
  1019. # Log success
  1020. LogService.create_log(
  1021. db=db,
  1022. app_id=app.id,
  1023. operator_id=current_user.id,
  1024. action_type=ActionType.IMPORT,
  1025. details={"message": "Sync all users", "count": len(new_mappings)}
  1026. )
  1027. return {"message": f"同步成功,新增 {len(new_mappings)} 个用户映射"}
  1028. logger.info("用户同步: 没有需要同步的新用户")
  1029. return {"message": "没有需要同步的用户"}
  1030. @router.post("/{app_id}/sync-users-v2", summary="同步用户 (新版)")
  1031. def sync_users_to_app_v2(
  1032. *,
  1033. db: Session = Depends(deps.get_db),
  1034. app_id: int,
  1035. sync_req: AppSyncRequest,
  1036. current_user: User = Depends(deps.get_current_active_user),
  1037. ):
  1038. """
  1039. 高级用户同步功能。
  1040. 支持全量/部分同步,以及可选的默认邮箱初始化。
  1041. 需要手机验证码。
  1042. """
  1043. app = db.query(Application).filter(Application.id == app_id).first()
  1044. if not app:
  1045. raise HTTPException(status_code=404, detail="应用未找到")
  1046. if current_user.role != "SUPER_ADMIN" and app.owner_id != current_user.id:
  1047. raise HTTPException(status_code=403, detail="权限不足")
  1048. # 1. Verify SMS Code
  1049. if not SmsService.verify_code(current_user.mobile, sync_req.verification_code):
  1050. logger.warning(f"同步用户失败: 验证码错误 (User: {current_user.mobile})")
  1051. raise HTTPException(status_code=400, detail="验证码无效或已过期")
  1052. # 2. Determine Target Users
  1053. query = db.query(User).filter(User.is_deleted == 0)
  1054. if sync_req.mode == "SELECTED":
  1055. if not sync_req.user_ids:
  1056. raise HTTPException(status_code=400, detail="请选择要同步的用户")
  1057. query = query.filter(User.id.in_(sync_req.user_ids))
  1058. users = query.all()
  1059. if not users:
  1060. return {"message": "没有找到可同步的用户"}
  1061. # 3. Get existing mappings (user_ids) to skip
  1062. existing_mappings = db.query(AppUserMapping).filter(AppUserMapping.app_id == app_id).all()
  1063. mapped_user_ids = {m.user_id for m in existing_mappings}
  1064. # Check if email domain is valid format if provided (simple check)
  1065. if sync_req.init_email and not sync_req.email_domain:
  1066. raise HTTPException(status_code=400, detail="开启邮箱初始化时必须填写域名")
  1067. new_mappings = []
  1068. for user in users:
  1069. if user.id in mapped_user_ids:
  1070. continue
  1071. mapped_key = user.english_name if user.english_name else user.mobile
  1072. mapped_email = None
  1073. if sync_req.init_email and user.english_name:
  1074. # Construct email
  1075. domain = sync_req.email_domain.strip()
  1076. if not domain.startswith("@"):
  1077. domain = "@" + domain
  1078. mapped_email = f"{user.english_name}{domain}"
  1079. mapping = AppUserMapping(
  1080. app_id=app.id,
  1081. user_id=user.id,
  1082. mapped_key=mapped_key,
  1083. mapped_email=mapped_email,
  1084. is_active=True
  1085. )
  1086. new_mappings.append(mapping)
  1087. if not new_mappings:
  1088. return {"message": "所有选中的用户均已存在映射,无需同步"}
  1089. # 4. Insert
  1090. logger.info(f"开始同步(v2)用户到应用 {app.app_name},计划新增 {len(new_mappings)} 条")
  1091. success_count = 0
  1092. fail_count = 0
  1093. for m in new_mappings:
  1094. try:
  1095. # Additional check: uniqueness of mapped_key in this app
  1096. db.add(m)
  1097. db.commit()
  1098. success_count += 1
  1099. except Exception as e:
  1100. db.rollback()
  1101. fail_count += 1
  1102. logger.warning(f"同步单个映射失败 (User: {m.user_id}): {e}")
  1103. # 5. Log
  1104. LogService.create_log(
  1105. db=db,
  1106. app_id=app.id,
  1107. operator_id=current_user.id,
  1108. action_type=ActionType.SYNC,
  1109. details={
  1110. "mode": sync_req.mode,
  1111. "init_email": sync_req.init_email,
  1112. "total_attempted": len(new_mappings),
  1113. "success": success_count,
  1114. "failed": fail_count
  1115. }
  1116. )
  1117. logger.info(f"同步(v2)完成。成功: {success_count}, 失败: {fail_count}")
  1118. msg = f"同步完成。成功: {success_count},失败: {fail_count}"
  1119. if fail_count > 0:
  1120. msg += " (失败原因可能是账号或邮箱冲突)"
  1121. return {"message": msg}
  1122. @router.get("/{app_id}/mappings/export", summary="导出映射")
  1123. def export_mappings(
  1124. *,
  1125. db: Session = Depends(deps.get_db),
  1126. app_id: int,
  1127. current_user: User = Depends(deps.get_current_active_user),
  1128. ):
  1129. """
  1130. 导出所有映射到 Excel (.xlsx)。
  1131. """
  1132. app = db.query(Application).filter(Application.id == app_id).first()
  1133. if not app:
  1134. raise HTTPException(status_code=404, detail="应用未找到")
  1135. if current_user.role != "SUPER_ADMIN" and app.owner_id != current_user.id:
  1136. raise HTTPException(status_code=403, detail="权限不足")
  1137. mappings = db.query(AppUserMapping).filter(AppUserMapping.app_id == app_id).all()
  1138. # Prepare data for DataFrame
  1139. data = []
  1140. for m in mappings:
  1141. mobile = m.user.mobile if m.user else "Deleted User"
  1142. data.append({
  1143. '手机号': mobile,
  1144. '映射账号': m.mapped_key,
  1145. '映射邮箱': m.mapped_email or ''
  1146. })
  1147. # Create DataFrame
  1148. df = pd.DataFrame(data)
  1149. # If no data, create an empty DataFrame with columns
  1150. if not data:
  1151. df = pd.DataFrame(columns=['手机号', '映射账号', '映射邮箱'])
  1152. # Write to Excel BytesIO
  1153. output = io.BytesIO()
  1154. with pd.ExcelWriter(output, engine='openpyxl') as writer:
  1155. df.to_excel(writer, index=False)
  1156. output.seek(0)
  1157. filename = f"mappings_app_{app_id}.xlsx"
  1158. logger.info(f"导出映射成功: App {app_id}, Count {len(mappings)}")
  1159. return StreamingResponse(
  1160. output,
  1161. media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  1162. headers={"Content-Disposition": f"attachment; filename={filename}"}
  1163. )
  1164. @router.post("/{app_id}/mapping/preview", response_model=MappingPreviewResponse, summary="预览映射导入")
  1165. async def preview_mapping(
  1166. app_id: int,
  1167. file: UploadFile = File(...),
  1168. db: Session = Depends(deps.get_db),
  1169. current_user: User = Depends(deps.get_current_active_user),
  1170. ):
  1171. """
  1172. 预览 Excel/CSV 映射导入。
  1173. """
  1174. app = db.query(Application).filter(Application.id == app_id).first()
  1175. if not app:
  1176. raise HTTPException(status_code=404, detail="应用未找到")
  1177. if current_user.role != "SUPER_ADMIN" and app.owner_id != current_user.id:
  1178. raise HTTPException(status_code=403, detail="权限不足")
  1179. contents = await file.read()
  1180. filename = file.filename
  1181. try:
  1182. return MappingService.preview_import(db, app_id, contents, filename)
  1183. except Exception as e:
  1184. logger.error(f"导入预览失败: {e}", exc_info=True)
  1185. raise HTTPException(status_code=400, detail=f"解析文件失败: {str(e)}")
  1186. @router.post("/send-import-verification-code", summary="发送导入验证码")
  1187. def send_import_verification_code(
  1188. current_user: User = Depends(deps.get_current_active_user),
  1189. ):
  1190. """
  1191. 发送验证码给当前登录用户(用于敏感操作验证,如导入)。
  1192. """
  1193. SmsService.send_code(current_user.mobile)
  1194. logger.info(f"发送导入验证码: {current_user.mobile}")
  1195. return {"message": "验证码已发送"}
  1196. @router.post("/{app_id}/mapping/import", response_model=ImportLogResponse, summary="执行映射导入")
  1197. async def import_mapping(
  1198. app_id: int,
  1199. file: UploadFile = File(...),
  1200. strategy: MappingStrategy = Form(MappingStrategy.SKIP),
  1201. verification_code: str = Form(...),
  1202. db: Session = Depends(deps.get_db),
  1203. current_user: User = Depends(deps.get_current_active_user),
  1204. ):
  1205. """
  1206. 执行映射导入操作。需要验证短信验证码。
  1207. """
  1208. app = db.query(Application).filter(Application.id == app_id).first()
  1209. if not app:
  1210. raise HTTPException(status_code=404, detail="应用未找到")
  1211. if current_user.role != "SUPER_ADMIN" and app.owner_id != current_user.id:
  1212. raise HTTPException(status_code=403, detail="权限不足")
  1213. contents = await file.read()
  1214. filename = file.filename
  1215. logger.info(f"开始执行映射导入: App {app_id}, File {filename}, Strategy {strategy}")
  1216. try:
  1217. result = MappingService.execute_import(db, app_id, contents, filename, strategy, current_user.mobile, verification_code)
  1218. except Exception as e:
  1219. logger.error(f"执行映射导入异常: {e}", exc_info=True)
  1220. raise e
  1221. # LOGGING
  1222. # For import, we log the summary and the logs structure
  1223. LogService.create_log(
  1224. db=db,
  1225. app_id=app_id,
  1226. operator_id=current_user.id,
  1227. action_type=ActionType.IMPORT,
  1228. details=result.model_dump(mode='json') # Store full result including logs
  1229. )
  1230. logger.info(f"映射导入完成: 成功 {result.summary.inserted + result.summary.updated}, 失败 {result.summary.failed}")
  1231. return result
  1232. @router.get("/mapping/users", response_model=UserSyncList, summary="获取全量用户(M2M)")
  1233. def get_all_users_m2m(
  1234. *,
  1235. db: Session = Depends(deps.get_db),
  1236. skip: int = 0,
  1237. limit: int = 100,
  1238. current_app: Application = Depends(deps.get_current_app),
  1239. ):
  1240. """
  1241. 开发者拉取全量用户接口。
  1242. 仅返回:手机号、姓名、英文名。
  1243. 需要应用访问令牌 (Authorization Bearer JWT 或 X-App-Access-Token)。
  1244. """
  1245. query = db.query(User).filter(User.is_deleted == 0)
  1246. total = query.count()
  1247. users = query.order_by(User.id).offset(skip).limit(limit).all()
  1248. return {"total": total, "items": users}
  1249. @router.post("/mapping/sync", response_model=MappingResponse, summary="同步映射 (M2M)")
  1250. def sync_mapping(
  1251. request: Request,
  1252. *,
  1253. db: Session = Depends(deps.get_db),
  1254. sync_in: UserSyncRequest,
  1255. current_app: Application = Depends(deps.get_current_app),
  1256. ):
  1257. """
  1258. 从外部平台同步用户映射关系(机器对机器)。
  1259. 支持增删改查:
  1260. - UPSERT (默认): 创建或更新映射及用户;必须提供姓名;新建用户时英文名由姓名自动生成并去重。
  1261. - DELETE: 仅删除应用与用户的映射关系,不删除用户。
  1262. 需要应用访问令牌 (Authorization Bearer JWT 或 X-App-Access-Token)。
  1263. """
  1264. # Normalize input: treat empty strings as None (mobile / mapped_key 已在 Schema 中强制校验)
  1265. mapped_key = sync_in.mapped_key
  1266. mapped_email = sync_in.mapped_email if sync_in.mapped_email else None
  1267. logger.info(f"收到 M2M 同步请求: App {current_app.app_id}, Mobile {sync_in.mobile}, Action {sync_in.sync_action}")
  1268. # ==========================================
  1269. # 1. Handle DELETE Action
  1270. # ==========================================
  1271. if sync_in.sync_action == "DELETE":
  1272. # 查找用户
  1273. user = db.query(User).filter(User.mobile == sync_in.mobile).first()
  1274. if not user:
  1275. # 用户不存在,无法删除映射,直接抛出404或视作成功
  1276. logger.warning(f"M2M 删除失败: 用户 {sync_in.mobile} 不存在")
  1277. raise HTTPException(status_code=404, detail="用户不存在")
  1278. # 查找映射
  1279. mapping = db.query(AppUserMapping).filter(
  1280. AppUserMapping.app_id == current_app.id,
  1281. AppUserMapping.user_id == user.id
  1282. ).first()
  1283. if not mapping:
  1284. logger.warning(f"M2M 删除失败: 映射不存在 (User {sync_in.mobile})")
  1285. raise HTTPException(status_code=404, detail="映射关系不存在")
  1286. if mapping.mapped_key is None:
  1287. raise HTTPException(
  1288. status_code=400,
  1289. detail="映射记录缺少外部账号,请在平台侧补全后再删除",
  1290. )
  1291. if mapping.mapped_key != mapped_key:
  1292. raise HTTPException(status_code=400, detail="映射账号与平台记录不一致")
  1293. # 构造返回数据(删除前快照,将状态置为 False)
  1294. resp_data = MappingResponse(
  1295. id=mapping.id,
  1296. app_id=mapping.app_id,
  1297. user_id=mapping.user_id,
  1298. mapped_key=mapping.mapped_key,
  1299. mapped_email=mapping.mapped_email,
  1300. user_mobile=user.mobile,
  1301. user_status=user.status,
  1302. is_active=False # 标记为非活跃/已删除
  1303. )
  1304. # 执行物理删除 (只删映射,不删用户)
  1305. db.delete(mapping)
  1306. db.commit()
  1307. # 记录日志
  1308. LogService.create_log(
  1309. db=db,
  1310. app_id=current_app.id,
  1311. operator_id=current_app.owner_id,
  1312. action_type=ActionType.DELETE,
  1313. target_user_id=user.id,
  1314. target_mobile=user.mobile,
  1315. ip_address=get_client_ip(request),
  1316. details={
  1317. "mapped_key": mapping.mapped_key,
  1318. "action": "M2M_DELETE",
  1319. "source": "M2M",
  1320. "sync_action": "DELETE",
  1321. },
  1322. )
  1323. logger.info(f"M2M 删除成功: {sync_in.mobile}")
  1324. return resp_data
  1325. # ==========================================
  1326. # 2. Handle UPSERT Action (Existing Logic)
  1327. # ==========================================
  1328. in_name = (sync_in.name or "").strip()
  1329. if not in_name:
  1330. raise HTTPException(status_code=400, detail="同步操作必须提供姓名")
  1331. # 0. Check Uniqueness for Name (Global Check)
  1332. # We exclude the current user (by mobile) to allow updates to self without conflict
  1333. name_conflict = db.query(User).filter(
  1334. User.name == in_name,
  1335. User.mobile != sync_in.mobile,
  1336. ).first()
  1337. if name_conflict:
  1338. raise HTTPException(status_code=400, detail=f"姓名 '{in_name}' 已存在")
  1339. # 1. Find User or Create
  1340. user = db.query(User).filter(User.mobile == sync_in.mobile).first()
  1341. new_user_created = False
  1342. if not user:
  1343. # Create New User — english_name 始终由姓名生成并去重(忽略请求中的 english_name)
  1344. in_english_name = generate_english_name(in_name).strip()
  1345. if not in_english_name:
  1346. in_english_name = f"u{sync_in.mobile[-4:]}"
  1347. original_base = in_english_name
  1348. counter = 1
  1349. while db.query(User).filter(
  1350. User.english_name == in_english_name,
  1351. User.is_deleted == 0,
  1352. ).first():
  1353. in_english_name = f"{original_base}{counter}"
  1354. counter += 1
  1355. # Auto create user
  1356. password = security.generate_alphanumeric_password(8) # Random password letters+digits
  1357. user = User(
  1358. mobile=sync_in.mobile,
  1359. password_hash=security.get_password_hash(password),
  1360. status="ACTIVE",
  1361. role="ORDINARY_USER",
  1362. name=in_name,
  1363. english_name=in_english_name
  1364. )
  1365. db.add(user)
  1366. db.commit()
  1367. db.refresh(user)
  1368. new_user_created = True
  1369. logger.info(f"M2M 自动创建用户: {sync_in.mobile}")
  1370. else:
  1371. # Update Existing User - 已有用户不允许修改 name、mobile、english_name
  1372. # Check if trying to modify restricted fields
  1373. if sync_in.mobile != user.mobile:
  1374. raise HTTPException(status_code=400, detail="已有用户不允许修改手机号")
  1375. if (user.name or "").strip() != in_name:
  1376. raise HTTPException(status_code=400, detail="已有用户不允许修改姓名")
  1377. # 已有用户的其他字段(如status等)可以更新,但当前M2M接口不涉及
  1378. # 这里只处理映射关系的更新
  1379. # 2. Handle Mapping
  1380. mapping = db.query(AppUserMapping).filter(
  1381. AppUserMapping.app_id == current_app.id,
  1382. AppUserMapping.user_id == user.id
  1383. ).first()
  1384. # Check Uniqueness for mapped_key (if changing or new, and provided)
  1385. if mapped_key and (not mapping or mapping.mapped_key != mapped_key):
  1386. key_exists = db.query(AppUserMapping).filter(
  1387. AppUserMapping.app_id == current_app.id,
  1388. AppUserMapping.mapped_key == mapped_key
  1389. ).first()
  1390. if key_exists:
  1391. raise HTTPException(status_code=400, detail=f"该应用下账号 {mapped_key} 已被使用")
  1392. # Check Uniqueness for mapped_email (if changing or new, and provided)
  1393. if mapped_email and (not mapping or mapping.mapped_email != mapped_email):
  1394. email_exists = db.query(AppUserMapping).filter(
  1395. AppUserMapping.app_id == current_app.id,
  1396. AppUserMapping.mapped_email == mapped_email
  1397. ).first()
  1398. if email_exists:
  1399. raise HTTPException(status_code=400, detail=f"该应用下邮箱 {mapped_email} 已被使用")
  1400. new_mapping_created = False
  1401. if mapping:
  1402. # Update existing mapping
  1403. mapping.mapped_key = mapped_key
  1404. if sync_in.is_active is not None:
  1405. mapping.is_active = sync_in.is_active
  1406. if sync_in.mapped_email is not None:
  1407. mapping.mapped_email = mapped_email
  1408. else:
  1409. # Create new mapping
  1410. new_mapping_created = True
  1411. mapping = AppUserMapping(
  1412. app_id=current_app.id,
  1413. user_id=user.id,
  1414. mapped_key=mapped_key,
  1415. mapped_email=mapped_email,
  1416. is_active=sync_in.is_active if sync_in.is_active is not None else True
  1417. )
  1418. db.add(mapping)
  1419. db.commit()
  1420. db.refresh(mapping)
  1421. # LOGGING
  1422. LogService.create_log(
  1423. db=db,
  1424. app_id=current_app.id,
  1425. operator_id=current_app.owner_id,
  1426. action_type=ActionType.SYNC_M2M,
  1427. target_user_id=user.id,
  1428. target_mobile=user.mobile,
  1429. ip_address=get_client_ip(request),
  1430. details={
  1431. "mapped_key": mapped_key,
  1432. "mapped_email": mapped_email,
  1433. "new_user_created": new_user_created,
  1434. "new_mapping_created": new_mapping_created,
  1435. "sync_action": "UPSERT",
  1436. "source": "M2M",
  1437. "is_active": mapping.is_active,
  1438. },
  1439. )
  1440. logger.info(f"M2M 同步成功: {sync_in.mobile} (Mapping: {mapping.id})")
  1441. return MappingResponse(
  1442. id=mapping.id,
  1443. app_id=mapping.app_id,
  1444. user_id=mapping.user_id,
  1445. mapped_key=mapping.mapped_key,
  1446. mapped_email=mapping.mapped_email,
  1447. user_mobile=user.mobile,
  1448. user_status=user.status,
  1449. is_active=mapping.is_active
  1450. )
  1451. # ==========================================
  1452. # Operation Logs
  1453. # ==========================================
  1454. @router.get("/{app_id}/logs", response_model=OperationLogList, summary="获取操作日志")
  1455. def read_logs(
  1456. *,
  1457. db: Session = Depends(deps.get_db),
  1458. app_id: int,
  1459. skip: int = 0,
  1460. limit: int = 20,
  1461. action_type: ActionType = Query(None),
  1462. keyword: str = Query(None, description="搜索手机号"),
  1463. start_date: datetime = Query(None),
  1464. end_date: datetime = Query(None),
  1465. current_user: User = Depends(deps.get_current_active_user),
  1466. ):
  1467. """
  1468. 获取应用操作日志。
  1469. """
  1470. app = db.query(Application).filter(Application.id == app_id).first()
  1471. if not app:
  1472. raise HTTPException(status_code=404, detail="应用未找到")
  1473. if current_user.role != "SUPER_ADMIN" and app.owner_id != current_user.id:
  1474. raise HTTPException(status_code=403, detail="权限不足")
  1475. total, logs = LogService.get_logs(
  1476. db=db,
  1477. app_id=app_id,
  1478. skip=skip,
  1479. limit=limit,
  1480. action_type=action_type,
  1481. keyword=keyword,
  1482. start_date=start_date,
  1483. end_date=end_date
  1484. )
  1485. result = []
  1486. for log in logs:
  1487. # Enrich operator mobile
  1488. operator_mobile = log.operator.mobile if log.operator else "Unknown"
  1489. result.append(OperationLogResponse(
  1490. id=log.id,
  1491. app_id=log.app_id,
  1492. action_type=log.action_type,
  1493. target_mobile=log.target_mobile,
  1494. details=log.details,
  1495. operator_id=log.operator_id,
  1496. operator_mobile=operator_mobile,
  1497. target_user_id=log.target_user_id,
  1498. created_at=log.created_at
  1499. ))
  1500. return {"total": total, "items": result}