simple_auth.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. from typing import Optional, List
  2. import json
  3. from fastapi import APIRouter, Depends, HTTPException, Body
  4. from sqlalchemy.orm import Session
  5. from pydantic import BaseModel
  6. from app.api.v1 import deps
  7. from app.core import security
  8. from app.models.user import User, UserRole, UserStatus
  9. from app.models.application import Application
  10. from app.models.mapping import AppUserMapping
  11. from app.schemas.simple_auth import (
  12. TicketExchangeRequest, TicketExchangeResponse,
  13. TicketValidateRequest, TicketValidateResponse,
  14. PasswordLoginRequest, PasswordLoginResponse,
  15. UserRegisterRequest, AdminPasswordResetRequest, AdminPasswordResetResponse,
  16. ChangePasswordRequest, MyMappingsResponse, UserMappingResponse,
  17. UserPromoteRequest, SsoLoginRequest, SsoLoginResponse
  18. )
  19. from app.services.signature_service import SignatureService
  20. from app.services.ticket_service import TicketService
  21. router = APIRouter()
  22. @router.post("/login", response_model=PasswordLoginResponse, summary="密码登录")
  23. def login_with_password(
  24. req: PasswordLoginRequest,
  25. db: Session = Depends(deps.get_db),
  26. ):
  27. """
  28. 1. 如果提供 app_id:应用 SSO 登录,返回 ticket。
  29. 2. 如果未提供 app_id:统一认证平台登录,返回 access_token。
  30. """
  31. # --- Platform Login ---
  32. if not req.app_id:
  33. # Find user by mobile only
  34. user = db.query(User).filter(User.mobile == req.identifier, User.is_deleted == 0).first()
  35. if not user:
  36. raise HTTPException(status_code=404, detail="用户未找到")
  37. if not security.verify_password(req.password, user.password_hash):
  38. raise HTTPException(status_code=401, detail="密码错误")
  39. if user.status != UserStatus.ACTIVE:
  40. raise HTTPException(status_code=400, detail="用户已禁用")
  41. # Generate JWT Access Token
  42. access_token = security.create_access_token(user.id)
  43. return {
  44. "access_token": access_token,
  45. "token_type": "bearer",
  46. "role": user.role
  47. }
  48. # --- App SSO Login ---
  49. # 1. Verify App
  50. app = db.query(Application).filter(Application.app_id == req.app_id).first()
  51. if not app:
  52. raise HTTPException(status_code=404, detail="应用未找到")
  53. # 2. Verify Signature (Optional but recommended for server-side calls)
  54. if req.sign and req.timestamp:
  55. params = {
  56. "app_id": req.app_id,
  57. "identifier": req.identifier,
  58. "password": req.password,
  59. "timestamp": req.timestamp,
  60. "sign": req.sign
  61. }
  62. if not SignatureService.verify_signature(app.app_secret, params, req.sign):
  63. raise HTTPException(status_code=400, detail="签名无效")
  64. # 3. Find User
  65. user = None
  66. # Try by mobile
  67. user = db.query(User).filter(User.mobile == req.identifier, User.is_deleted == 0).first()
  68. if not user:
  69. # Try by mapping
  70. mapping = db.query(AppUserMapping).filter(
  71. AppUserMapping.app_id == app.id,
  72. (AppUserMapping.mapped_key == req.identifier) | (AppUserMapping.mapped_email == req.identifier)
  73. ).first()
  74. if mapping:
  75. user = db.query(User).filter(User.id == mapping.user_id, User.is_deleted == 0).first()
  76. if not user:
  77. raise HTTPException(status_code=404, detail="用户未找到")
  78. if user.status != UserStatus.ACTIVE:
  79. raise HTTPException(status_code=400, detail="用户已禁用")
  80. # 4. Verify Password
  81. if not security.verify_password(req.password, user.password_hash):
  82. raise HTTPException(status_code=401, detail="密码错误")
  83. # 5. Generate Ticket (Self-Targeting)
  84. ticket = TicketService.generate_ticket(user.id, req.app_id)
  85. return {"ticket": ticket}
  86. @router.post("/register", response_model=PasswordLoginResponse, summary="用户注册")
  87. def register_user(
  88. req: UserRegisterRequest,
  89. db: Session = Depends(deps.get_db),
  90. ):
  91. """
  92. 注册新用户 (默认为普通用户)。
  93. """
  94. # Force role to ORDINARY_USER
  95. role = UserRole.ORDINARY_USER
  96. existing_user = db.query(User).filter(User.mobile == req.mobile, User.is_deleted == 0).first()
  97. if existing_user:
  98. raise HTTPException(status_code=400, detail="手机号已注册")
  99. new_user = User(
  100. mobile=req.mobile,
  101. password_hash=security.get_password_hash(req.password),
  102. status=UserStatus.ACTIVE,
  103. role=role
  104. )
  105. db.add(new_user)
  106. db.commit()
  107. db.refresh(new_user)
  108. # Auto-login after registration (return token)
  109. access_token = security.create_access_token(new_user.id)
  110. return {
  111. "access_token": access_token,
  112. "token_type": "bearer",
  113. "role": new_user.role
  114. }
  115. @router.post("/admin/reset-password", response_model=AdminPasswordResetResponse, summary="管理员重置密码")
  116. def admin_reset_password(
  117. req: AdminPasswordResetRequest,
  118. db: Session = Depends(deps.get_db),
  119. current_user: User = Depends(deps.get_current_active_user),
  120. ):
  121. """
  122. 超级管理员重置用户密码。
  123. 随机生成8位密码,只显示一次。
  124. """
  125. if current_user.role != UserRole.SUPER_ADMIN:
  126. raise HTTPException(status_code=403, detail="权限不足")
  127. target_user = db.query(User).filter(User.id == req.user_id).first()
  128. if not target_user:
  129. raise HTTPException(status_code=404, detail="用户未找到")
  130. # Generate random password (alphanumeric only)
  131. new_pwd = security.generate_alphanumeric_password(8)
  132. target_user.password_hash = security.get_password_hash(new_pwd)
  133. db.add(target_user)
  134. db.commit()
  135. return {"new_password": new_pwd}
  136. @router.post("/admin/promote", summary="提升用户角色")
  137. def promote_user(
  138. req: UserPromoteRequest,
  139. db: Session = Depends(deps.get_db),
  140. current_user: User = Depends(deps.get_current_active_user),
  141. ):
  142. if current_user.role != UserRole.SUPER_ADMIN:
  143. raise HTTPException(status_code=403, detail="权限不足")
  144. if req.new_role not in [UserRole.SUPER_ADMIN, UserRole.DEVELOPER]:
  145. raise HTTPException(status_code=400, detail="只能提升为管理员 or 开发者")
  146. target_user = db.query(User).filter(User.id == req.user_id).first()
  147. if not target_user:
  148. raise HTTPException(status_code=404, detail="用户未找到")
  149. target_user.role = req.new_role
  150. db.add(target_user)
  151. db.commit()
  152. return {"message": "success"}
  153. @router.get("/me/mappings", response_model=MyMappingsResponse, summary="我的映射")
  154. def get_my_mappings(
  155. skip: int = 0,
  156. limit: int = 10,
  157. app_name: str = None,
  158. db: Session = Depends(deps.get_db),
  159. current_user: User = Depends(deps.get_current_active_user),
  160. ):
  161. query = db.query(AppUserMapping).join(Application).filter(AppUserMapping.user_id == current_user.id)
  162. if app_name:
  163. query = query.filter(Application.app_name.ilike(f"%{app_name}%"))
  164. total = query.count()
  165. mappings = query.order_by(AppUserMapping.id.desc()).offset(skip).limit(limit).all()
  166. result = []
  167. for m in mappings:
  168. result.append(UserMappingResponse(
  169. app_name=m.application.app_name if m.application else "Unknown",
  170. mapped_key=m.mapped_key,
  171. mapped_email=m.mapped_email,
  172. is_active=m.is_active
  173. ))
  174. return {"total": total, "items": result}
  175. @router.post("/me/change-password", summary="修改密码")
  176. def change_my_password(
  177. req: ChangePasswordRequest,
  178. db: Session = Depends(deps.get_db),
  179. current_user: User = Depends(deps.get_current_active_user),
  180. ):
  181. if not security.verify_password(req.old_password, current_user.password_hash):
  182. raise HTTPException(status_code=400, detail="旧密码错误")
  183. current_user.password_hash = security.get_password_hash(req.new_password)
  184. db.add(current_user)
  185. db.commit()
  186. return {"message": "密码修改成功"}
  187. @router.post("/exchange", response_model=TicketExchangeResponse, summary="票据交换")
  188. def exchange_ticket(
  189. req: TicketExchangeRequest,
  190. db: Session = Depends(deps.get_db),
  191. ):
  192. """
  193. 源应用调用以获取目标应用的票据。
  194. """
  195. # 1. Verify Source App
  196. source_app = db.query(Application).filter(Application.app_id == req.app_id).first()
  197. if not source_app:
  198. raise HTTPException(status_code=404, detail="源应用未找到")
  199. # 2. Verify Signature
  200. params = {
  201. "app_id": req.app_id,
  202. "target_app_id": req.target_app_id,
  203. "user_mobile": req.user_mobile,
  204. "timestamp": req.timestamp,
  205. "sign": req.sign
  206. }
  207. # Use the stored secret to verify
  208. if not SignatureService.verify_signature(source_app.app_secret, params, req.sign):
  209. raise HTTPException(status_code=400, detail="签名无效")
  210. # 3. Verify User Existence (Optional: Do we trust source app completely? Usually yes if signed.)
  211. # But we need user_id to generate ticket.
  212. # We query by mobile.
  213. user = db.query(User).filter(User.mobile == req.user_mobile, User.is_deleted == 0).first()
  214. if not user:
  215. # If user doesn't exist, we might auto-create OR fail.
  216. # Requirement: "Returns redirect_url".
  217. # For simplicity, if user not found, we cannot map.
  218. raise HTTPException(status_code=404, detail="用户在 UAP 中未找到")
  219. # 4. Generate Ticket for Target App
  220. # Logic: The ticket allows the user to log in to Target App.
  221. ticket = TicketService.generate_ticket(user.id, req.target_app_id)
  222. # 5. Get Target App URL
  223. target_app = db.query(Application).filter(Application.app_id == req.target_app_id).first()
  224. if not target_app:
  225. raise HTTPException(status_code=404, detail="目标应用未找到")
  226. # Construct redirect URL
  227. # Assuming target app handles /callback?ticket=...
  228. # We use the first redirect_uri or notification_url or custom logic.
  229. # Simplicity: We return the ticket and let the Source App handle the redirect,
  230. # OR we return a full redirect URL if target_app has a base URL configured.
  231. # Let's assume redirect_uris is a JSON list.
  232. redirect_base = ""
  233. if target_app.redirect_uris:
  234. try:
  235. uris = json.loads(target_app.redirect_uris)
  236. if uris and len(uris) > 0:
  237. redirect_base = uris[0]
  238. except:
  239. pass
  240. if not redirect_base:
  241. # Fallback or error
  242. redirect_base = "http://unknown-target-url"
  243. full_redirect_url = f"{redirect_base}?ticket={ticket}"
  244. return {
  245. "ticket": ticket,
  246. "redirect_url": full_redirect_url
  247. }
  248. @router.post("/ticket/exchange", response_model=TicketExchangeResponse, summary="票据交换 (API)")
  249. def ticket_exchange_api(
  250. req: TicketExchangeRequest,
  251. db: Session = Depends(deps.get_db),
  252. ):
  253. """
  254. 服务器对服务器 API:源应用请求目标应用的票据。
  255. """
  256. return exchange_ticket(req, db)
  257. @router.post("/sso-login", response_model=SsoLoginResponse, summary="SSO 登录 (简易模式)")
  258. def sso_login(
  259. req: SsoLoginRequest,
  260. db: Session = Depends(deps.get_db),
  261. current_user: Optional[User] = Depends(deps.get_current_active_user_optional),
  262. ):
  263. """
  264. 简易 API 应用的 SSO 登录。
  265. 返回带有票据的重定向 URL。
  266. 支持:
  267. 1. 用户名 + 密码登录
  268. 2. 基于会话的自动登录(如果已登录)
  269. """
  270. # 1. Verify App
  271. app = db.query(Application).filter(Application.app_id == req.app_id).first()
  272. if not app:
  273. raise HTTPException(status_code=404, detail="应用未找到")
  274. if app.protocol_type != "SIMPLE_API":
  275. raise HTTPException(status_code=400, detail="SSO 登录仅支持简易 API 应用。OIDC 请使用标准流程。")
  276. user = None
  277. # 2. Try Session Login first
  278. if current_user:
  279. user = current_user
  280. # 3. If no session, try Credentials Login
  281. if not user and req.username and req.password:
  282. # Verify User Credentials
  283. user_query = db.query(User).filter(User.mobile == req.username, User.is_deleted == 0).first()
  284. if not user_query:
  285. # Check mapping
  286. mapping = db.query(AppUserMapping).filter(
  287. AppUserMapping.app_id == app.id,
  288. (AppUserMapping.mapped_key == req.username) | (AppUserMapping.mapped_email == req.username)
  289. ).first()
  290. if mapping:
  291. user_query = db.query(User).filter(User.id == mapping.user_id, User.is_deleted == 0).first()
  292. if user_query and security.verify_password(req.password, user_query.password_hash):
  293. user = user_query
  294. if not user:
  295. raise HTTPException(status_code=401, detail="认证失败")
  296. if user.status != "ACTIVE":
  297. raise HTTPException(status_code=400, detail="用户已禁用")
  298. # 4. Generate Ticket
  299. ticket = TicketService.generate_ticket(user.id, req.app_id)
  300. # 5. Get Redirect URL
  301. redirect_base = ""
  302. if app.redirect_uris:
  303. try:
  304. uris = json.loads(app.redirect_uris)
  305. if uris and len(uris) > 0:
  306. redirect_base = uris[0]
  307. except:
  308. pass
  309. if not redirect_base:
  310. raise HTTPException(status_code=400, detail="应用未配置重定向 URI")
  311. full_redirect_url = f"{redirect_base}?ticket={ticket}"
  312. return {"redirect_url": full_redirect_url}
  313. @router.post("/validate", response_model=TicketValidateResponse, summary="验证票据")
  314. def validate_ticket(
  315. req: TicketValidateRequest,
  316. db: Session = Depends(deps.get_db),
  317. ):
  318. """
  319. 目标应用调用以消费票据。
  320. """
  321. # 1. Verify App
  322. app = db.query(Application).filter(Application.app_id == req.app_id).first()
  323. if not app:
  324. raise HTTPException(status_code=404, detail="应用未找到")
  325. # 2. Verify Signature
  326. params = {
  327. "ticket": req.ticket,
  328. "app_id": req.app_id,
  329. "timestamp": req.timestamp,
  330. "sign": req.sign
  331. }
  332. if not SignatureService.verify_signature(app.app_secret, params, req.sign):
  333. raise HTTPException(status_code=400, detail="签名无效")
  334. # 3. Consume Ticket
  335. ticket_data = TicketService.consume_ticket(req.ticket, req.app_id)
  336. if not ticket_data:
  337. return {"valid": False}
  338. user_id = ticket_data["user_id"]
  339. # 4. Get User Info & Mapping
  340. user = db.query(User).filter(User.id == user_id).first()
  341. mapping = db.query(AppUserMapping).filter(
  342. AppUserMapping.app_id == app.id,
  343. AppUserMapping.user_id == user_id
  344. ).first()
  345. mapped_key = mapping.mapped_key if mapping else None
  346. mapped_email = mapping.mapped_email if mapping else None
  347. return {
  348. "valid": True,
  349. "user_id": user.id,
  350. "mobile": user.mobile,
  351. "mapped_key": mapped_key,
  352. "mapped_email": mapped_email
  353. }