login_background.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. """登录界面自定义背景图接口。
  2. 用户将 background.jpg 或 background.png 放到服务端运行目录
  3. (打包模式为 exe 同级目录,开发模式为仓库根目录)即可让登录界面
  4. 自动展示自定义背景;两个文件同时存在时优先 jpg。
  5. 安全说明:
  6. - 接口公开(登录前无凭证可访问),不返回任何敏感信息;
  7. - 候选文件名为固定白名单,不接收路径参数,无目录穿越风险。
  8. """
  9. from __future__ import annotations
  10. import sys
  11. from pathlib import Path
  12. from flask import current_app, send_file
  13. from dms.api.v1.blueprint import api_v1
  14. from dms.common.errors import FileNotFoundError as DmsFileNotFoundError
  15. # 候选文件名(固定白名单):同时存在时按列表顺序优先
  16. _BACKGROUND_FILES: dict[str, str] = {
  17. "background.jpg": "image/jpeg",
  18. "background.png": "image/png",
  19. }
  20. def _runtime_root() -> Path:
  21. """服务端运行目录,与 launcher._app_root 同语义。
  22. - PyInstaller 打包模式:exe 同级目录(用户可见、可写)
  23. - 开发模式:本文件位于 backend/dms/api/v1/ 下,仓库根在上级第四层
  24. """
  25. if getattr(sys, "frozen", False):
  26. return Path(sys.executable).resolve().parent
  27. return Path(__file__).resolve().parents[4]
  28. def _candidate_paths() -> list[tuple[Path, str]]:
  29. # 测试与特殊部署可通过 DMS_LOGIN_BACKGROUND_DIR 覆盖运行目录
  30. root = Path(
  31. current_app.config.get("DMS_LOGIN_BACKGROUND_DIR") or _runtime_root()
  32. )
  33. return [
  34. (root / name, mime) for name, mime in _BACKGROUND_FILES.items()
  35. ]
  36. @api_v1.get("/config/login-background")
  37. def get_login_background():
  38. for path, mime in _candidate_paths():
  39. if path.is_file():
  40. response = send_file(path, mimetype=mime, conditional=True)
  41. response.headers["X-Content-Type-Options"] = "nosniff"
  42. # 背景图变更频率低,允许浏览器短缓存减少首屏请求
  43. response.headers["Cache-Control"] = "public, max-age=60"
  44. return response
  45. raise DmsFileNotFoundError("运行目录下不存在 background.jpg/png 背景图")