apps.py 40 KB

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