apps.py 49 KB

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