Files
xbcr/routes/map_api.py
T
zzy f34ed304bc fix: 缺陷审计批次(231 例)+ 复核补钉(①–⑦)
一、审计修复(另一侧完成,我复核通过)
- 认证/限流:_client_ip 归一、限流统一走 rate_limit._SlidingTable(超限只淘汰最旧 key,
  不再整表 clear 自毁)、每用户会话上限 10 + 过期清理
- 邮件验证码:锁内原子占位 → 锁外发信 → 成功落码,失败回滚冷却(并发不再双发)
- 租赁:rentals 部分唯一索引(同 order_id 只允许一行 expired=0,迁移前先查重)、
  开锁幂等落库、Timer 代号机制(取消/重排同临界区)、minutes=null 兜底、
  自动还车 30s×6 → 1m/2m/5m/10m 退避
- 安全:ring 四接口登录 + 任务归属校验(Bearer 或 ?token=,校验 sessions 表)、
  共享还车坐标不再伪造、代开锁 IntegrityError 兜底、token 配置原子写(fsync + 0600)
- 入口鉴权:8 个历史/分析接口未登录 401(HTTP 与 rtn_code 同时给)、
  analysis.html 带 Bearer + 未登录门 + 截断提示、历史查询 LIMIT 60000 并回传 truncated
- UX 四个 P0:计时条出现、真实单走 /api/order/return 而 reminder 走 /api/rental/return、
  定位失败不伪造坐标(三选一弹窗)、地图/配置/脚本失败统一落到可自救失败卡片
- 测试:新增 6 个文件 62 例;既有 test_history_30d 只补登录前置

二、我复核时发现并修掉的 7 处
① email_verify.record_cooldown 的 expires 写成 now,会被 send_code 开头的
   _cleanup_locked 整条删掉 —— 任何人发一次验证码就废掉「未注册邮箱」的冷却,
   找回密码又能枚举邮箱是否注册。改为活过冷却窗口,并补 3 例测试
② timer.py 两处落库(自动续租 INSERT、sync 复活 UPDATE)没防新唯一索引:
   撞索引抛 IntegrityError 会让巡检线程退出,该单从此没有计时器/自动还车(上游还在计费)。
   新增 _active_rental_id_for_order(),捕获后复用存活行
③ (0,0) 当合法坐标会先发给上游:/record/return 不校验范围,宽松后端会把车"还"在海里。
   新增 _coords_usable(),不可用就跳过原始点;候选列表永远丢掉第 0 项
④ boot_smoke.py 按旧契约要求 200,加鉴权后永远失败 → HTTPError 401 视为「未登录,预期」
⑤ 自动还车「不放弃」缺绝对上限:加 AUTO_RETURN_GIVE_UP_SECONDS=6h,到点只告警一次并停手
⑥ 索引谓词 aligned 到查重口径:COALESCE(expired,0)=0,旧定义自动重建
⑦ 访问日志脱敏:?token= / ?ticket= / ?access_token= 的值替换为 ***(werkzeug + root logger)
   否则容器日志里就是明文会话令牌
配套改写 tests/test_rental_dedup.py::test_return_accepts_zero_coordinates →
test_return_treats_zero_coordinates_as_missing(原断言把 (0,0) 当合法值发上游)

三、验证
- python -m pytest -q → 234 passed(基线 231,净增 3)
- node 5 套 → 44 pass / 0 fail
- 14 个 .py ast.parse、node --check dist/app.js → 全部通过
- boot_smoke.py → exit=0;未登录 /api/history/stats、/api/analysis/overview、
  /api/ring_progress/* 实测 401,/api/config 200
- 行为级:传 (0,0) 时上游只收到候选点;合法坐标仍先发上报值;唯一索引拦住重复插入
2026-11-17 09:58:16 +08:00

664 lines
26 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""地图数据、寻车、分析等路由"""
import json
import time
import uuid
import hashlib
import threading
import asyncio
import aiohttp
from pathlib import Path
from flask import Blueprint, current_app, jsonify, request, render_template
from db import get_db, get_user_display_name, get_user_auth
from routes.auth import get_current_user
from wechat import request_api, get_signature_headers, SEARCH_BIKE_URL, SEARCH_HEADERS
bp = Blueprint("map_api", __name__)
# 批量寻铃(响铃所有车)消耗大且影响他人,仅对指定用户开放
BATCH_RING_ALLOWED_EMAILS = {"3146527494@qq.com"}
# 并行寻车任务
ring_tasks: dict = {}
_ring_lock = threading.Lock()
# 首页静态资源版本号的进程内缓存(BUG-21):只有签名变化才重算 sha256
_map_asset_version_lock = threading.Lock()
_map_asset_version_cache = {"signature": None, "version": None}
# 寻车任务生命周期:已完成/失败的任务保留 30 分钟后删除,字典另有硬上限。
# 之前只有显式 /api/ring_status_clear 才 pop,前端不调就永久驻留(每条含
# 车辆列表与统计),随使用次数线性增长(BUG-20)。
RING_TASK_TTL_SECONDS = 30 * 60 # 已结束任务的保留时间
RING_TASK_CLEANUP_INTERVAL = 60 # 清理最小间隔:不是每个请求都扫全表
RING_TASK_MAX_TASKS = 2000 # 容量硬上限
_RING_FINISHED_STATUS = ("completed", "cancelled", "failed")
_ring_last_cleanup = 0.0
def _ring_cleanup_locked(now=None, force=False):
"""清理过期/超额任务(调用方必须持有 _ring_lock)。
- 已完成/失败任务超过 RING_TASK_TTL_SECONDS 删除;运行中的任务不动,
否则正在看进度页的 SSE 会莫名收到「任务不存在」。
- 清理按 RING_TASK_CLEANUP_INTERVAL 节流,避免每个请求都全表扫。
- 达到容量上限时按创建时间淘汰最老的已结束任务。
"""
global _ring_last_cleanup
now = time.time() if now is None else now
over_capacity = len(ring_tasks) >= RING_TASK_MAX_TASKS
if not force and not over_capacity and \
now - _ring_last_cleanup < RING_TASK_CLEANUP_INTERVAL:
return
_ring_last_cleanup = now
for tid, task in list(ring_tasks.items()):
if task.get("status") not in _RING_FINISHED_STATUS:
continue
ended = float(task.get("last_update") or task.get("created_at") or now)
if now - ended >= RING_TASK_TTL_SECONDS:
ring_tasks.pop(tid, None)
if len(ring_tasks) < RING_TASK_MAX_TASKS:
return
for tid, task in sorted(ring_tasks.items(),
key=lambda kv: float(kv[1].get("created_at") or 0)):
if len(ring_tasks) < RING_TASK_MAX_TASKS:
break
if task.get("status") in _RING_FINISHED_STATUS:
ring_tasks.pop(tid, None)
def _ring_task_get(task_id):
"""取任务快照,并顺手做一次节流清理(顺带保证过期任务读不到)。"""
with _ring_lock:
_ring_cleanup_locked()
task = ring_tasks.get(task_id)
return dict(task) if task else None
def _query_token():
"""URL 里的会话 token:`?token=<token>`(EventSource / 新窗口带不了 header)。"""
return (request.args.get("token") or "").strip()
def _user_from_request():
"""寻车任务鉴权:同时接受 `Authorization: Bearer <token>` 与 `?token=<token>`。
/ring_progress.html 用 EventSource(浏览器不给带 header)、取消按钮在新窗口
打开(同样拿不到前端内存里的 header),所以两个入口都走查询参数。
token 出现在 URL 里,因此相关页面/接口统一加 no-store + no-referrer。
"""
user = get_current_user()
if user:
return user
token = _query_token()
if not token:
return None
conn = get_db()
try:
row = conn.execute("""
SELECT users.id, users.email FROM sessions
JOIN users ON sessions.user_id = users.id
WHERE sessions.token = ? AND sessions.expires_at > datetime('now', '+8 hours')
""", (token,)).fetchone()
except Exception as exc:
print(f"[寻车] 校验 token 失败: {exc}")
row = None
finally:
conn.close()
return dict(row) if row else None
def _ring_owner_guard(task_id, user):
"""校验任务归属;返回 (task, error_response)。
任务里记 owner_user_id,只能操作自己创建的任务,否则任何人都能拿 8 位
task_id 读进度、取消别人的任务(BUG-20)。
"""
task = _ring_task_get(task_id)
if not task:
return None, (jsonify({"rtn_code": 404, "message": "任务不存在或已过期"}), 404)
if task.get("owner_user_id") != user["id"]:
return None, (jsonify({"rtn_code": 403, "message": "无权操作他人的寻车任务"}), 403)
return task, None
async def ring_single_bike_async(session, bike_code, school_id=10):
try:
headers = {**SEARCH_HEADERS, **get_signature_headers()}
async with session.post(
SEARCH_BIKE_URL,
json={"code": bike_code, "school_id": school_id},
headers=headers,
timeout=aiohttp.ClientTimeout(total=5)
) as resp:
data = await resp.json()
return data.get("rtn_code") == 0 or data.get("success") is True
except Exception:
return False
def run_ring_task(task_id: str):
global ring_tasks
task = ring_tasks.get(task_id)
if not task:
return
bikes = task["bikes"]
total = len(bikes)
task["total"] = total
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
connector = aiohttp.TCPConnector(limit=20, limit_per_host=20, loop=loop)
try:
async def run_session():
semaphore = asyncio.Semaphore(20)
async with aiohttp.ClientSession(connector=connector) as session:
async def ring_one(idx, code):
async with semaphore:
if task["cancelled"]:
return False
result = await ring_single_bike_async(session, code, 10)
with _ring_lock:
task["done"] += 1
if result:
task["success"] += 1
else:
task["failed"] += 1
task["last_update"] = time.time()
return result
batch_size = 20
for i in range(0, len(bikes), batch_size):
if task["cancelled"]:
break
batch = bikes[i:i + batch_size]
await asyncio.gather(
*[ring_one(i + j, b["code"]) for j, b in enumerate(batch)],
return_exceptions=True
)
await asyncio.sleep(0.1)
loop.run_until_complete(run_session())
finally:
with _ring_lock:
task["status"] = "completed" if not task["cancelled"] else "cancelled"
task["done"] = total
loop.close()
@bp.route("/api/ring_all", methods=["POST"])
def api_ring_all():
global ring_tasks
user = get_current_user()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录"})
if user["email"] not in BATCH_RING_ALLOWED_EMAILS:
return jsonify({"rtn_code": 403, "message": "批量寻铃仅对指定用户开放"})
data = request.get_json() or {}
codes = data.get("codes", [])
if isinstance(codes, str):
codes = [codes]
if not codes:
return jsonify({"rtn_code": 400, "message": "缺少 codes 参数"})
user_name = get_user_display_name(user["id"])
print(f"[操作日志] 寻车铃: codes={codes}, count={len(codes)}, user={user_name}")
task_id = str(uuid.uuid4())[:8]
task = {
"status": "running", "total": len(codes), "done": 0,
"success": 0, "failed": 0, "bikes": [{"code": c} for c in codes],
"cancelled": False, "created_at": time.time(), "last_update": time.time(),
"owner_user_id": user["id"],
}
with _ring_lock:
_ring_cleanup_locked()
if len(ring_tasks) >= RING_TASK_MAX_TASKS:
# 清理后仍然满:拒绝新建,而不是让字典无限涨
return jsonify({"rtn_code": 429,
"message": "寻车任务过多,请稍后再试"}), 429
ring_tasks[task_id] = task
t = threading.Thread(target=run_ring_task, args=(task_id,), daemon=True)
t.start()
return jsonify({"rtn_code": 0, "task_id": task_id, "total": len(codes),
"message": f"任务已启动,共 {len(codes)} 辆车"})
@bp.route("/api/ring_status/<task_id>")
def api_ring_status(task_id):
user = _user_from_request()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录"}), 401
task, error = _ring_owner_guard(task_id, user)
if error:
return error
return jsonify({"rtn_code": 0, "status": task["status"], "total": task["total"],
"done": task["done"], "success": task["success"], "failed": task["failed"]})
@bp.route("/api/ring_cancel/<task_id>", methods=["POST"])
def api_ring_cancel(task_id):
user = _user_from_request()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录"}), 401
with _ring_lock:
_ring_cleanup_locked()
task = ring_tasks.get(task_id)
if not task:
return jsonify({"rtn_code": 404, "message": "任务不存在或已过期"}), 404
if task.get("owner_user_id") != user["id"]:
return jsonify({"rtn_code": 403, "message": "无权操作他人的寻车任务"}), 403
if task["status"] != "running":
return jsonify({"rtn_code": 400, "message": f"任务已是 {task['status']} 状态"})
task["cancelled"] = True
task["status"] = "cancelling"
return jsonify({"rtn_code": 0, "message": "取消请求已发送"})
@bp.route("/api/ring_progress/<task_id>")
def api_ring_progress(task_id):
from flask import Response as FlaskResponse
global ring_tasks
RING_SSE_MAX_SECONDS = 180 # 单个进度 SSE 最长占用时间
user = _user_from_request()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录"}), 401
task, error = _ring_owner_guard(task_id, user)
if error:
return error
def _sse(obj):
return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n"
def generate():
last_done = -1
last_status = None
tick = 0
# 硬超时:SSE 是同步长连接,一个连接占死一个 worker。任务卡住时
# 不设上限的话(-w 4 只要 4 个进度页)整站会被打满。
deadline = time.time() + RING_SSE_MAX_SECONDS
while True:
if time.time() > deadline:
yield _sse({"type": "error", "message": "进度推送超时,请刷新页面查看结果"})
return
with _ring_lock:
task = ring_tasks.get(task_id)
snapshot = dict(task) if task else None
if not snapshot:
# 任务不存在(如服务重启/多进程不共享)——向前端发明确错误而非静默断开
yield _sse({"type": "error", "message": "任务不存在或已结束"})
return
done = snapshot["done"]
status = snapshot["status"]
if done != last_done or status != last_status:
last_done = done
last_status = status
yield _sse({
"type": "progress",
"status": status,
"done": done,
"total": snapshot["total"],
"success": snapshot["success"],
"failed": snapshot["failed"],
})
if status in ("completed", "cancelled"):
# 已结束,补发一条 done 事件后关闭
yield _sse({"type": "done", "status": status})
return
tick += 1
if tick >= 20: # 约 10s 一次心跳,避免代理/连接超时被判定为断开
tick = 0
yield ": ping\n\n"
time.sleep(0.5)
return FlaskResponse(
generate(),
mimetype="text/event-stream",
headers={
"Cache-Control": "no-store",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
"Referrer-Policy": "no-referrer",
},
)
@bp.route("/api/ring_status_clear/<task_id>", methods=["POST"])
def api_ring_status_clear(task_id):
user = _user_from_request()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录"}), 401
with _ring_lock:
task = ring_tasks.get(task_id)
if not task:
return jsonify({"rtn_code": 0, "message": "已清除"})
if task.get("owner_user_id") != user["id"]:
return jsonify({"rtn_code": 403, "message": "无权操作他人的寻车任务"}), 403
ring_tasks.pop(task_id, None)
return jsonify({"rtn_code": 0, "message": "已清除"})
@bp.route("/api/map")
def api_map():
# 非登录人员不能使用:地图数据需登录后查看
user = get_current_user()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
bike_type = request.args.get("type", "1").strip()
from map_cache import MAP_TYPES
if bike_type not in MAP_TYPES:
return jsonify({"rtn_code": 400, "message": "不支持的车辆类型"}), 400
result = request_api("GET", "/project/map", params={"type": bike_type})
# 上游错误文案统一翻译(成功响应原样透传)
if result.get("rtn_code") not in (None, 0):
from wechat import friendly_upstream_message
result = {**result,
"message": friendly_upstream_message(result.get("message", ""))}
response = jsonify(result)
# Only the server snapshot is cached; browsers must ask the server on refresh.
response.headers["Cache-Control"] = "private, no-store"
response.headers["Vary"] = "Authorization"
response.headers["X-Map-Server-Time"] = str(time.time())
return response
@bp.route("/api/bicycle", methods=["GET", "POST"])
def api_bicycle():
user = get_current_user()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
data = request.get_json() or {}
code = data.get("code", "")
if not code:
return jsonify({"rtn_code": 400, "message": "缺少 code 参数"})
user_name = get_user_display_name(user["id"])
print(f"[操作日志] 扫车牌号查询: code={code}, user={user_name}")
result = request_api("POST", "/project/bicycle", data={"code": code})
if result.get("rtn_code") not in (None, 0):
from wechat import friendly_upstream_message
result = {**result,
"message": friendly_upstream_message(result.get("message", ""))}
return jsonify(result)
@bp.route("/api/find_bike", methods=["POST"])
def api_find_bike():
user = get_current_user()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
data = request.get_json() or {}
keyword = (data.get("keyword") or data.get("code") or "").strip()
if not keyword:
return jsonify({"rtn_code": 400, "message": "缺少关键字"})
school_id = data.get("school_id", 10)
result = request_api("POST", "/project/search_bicycle", data={"code": keyword, "school_id": school_id})
if result.get("rtn_code") not in (None, 0):
from wechat import friendly_upstream_message
result = {**result,
"message": friendly_upstream_message(result.get("message", ""))}
return jsonify(result)
@bp.route("/api/config")
def api_config():
from campus import CAMPUS_CENTER_LAT, CAMPUS_CENTER_LNG
return jsonify({
"center_lat": CAMPUS_CENTER_LAT, "center_lng": CAMPUS_CENTER_LNG,
"scale": 17, "school_name": "山东管理学院",
"type_names": {"1": "单车", "3": "电动车", "6": "助力车"},
})
@bp.route("/api/nav_route")
def api_nav_route():
"""导航路线:距离/耗时/分段指引/整条折线(前端直接画到地图上)。
参数:origin_lat/origin_lng/dest_lat/dest_lng(GCJ02),mode=walking|riding
返回:{rtn_code:0, data:{distance, duration, points:[[lng,lat],...], steps:[...]}}
"""
user = get_current_user()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
from routes.auth import _client_ip
from rate_limit import hit as rl_hit
# 导航比查卡片更重,按 IP 每分钟 20 次
if not rl_hit(("nav_route", _client_ip()), 20, 60):
return jsonify({"rtn_code": 429, "message": "导航请求过于频繁,请稍后再试"}), 429
try:
o_lat = float(request.args.get("origin_lat"))
o_lng = float(request.args.get("origin_lng"))
d_lat = float(request.args.get("dest_lat"))
d_lng = float(request.args.get("dest_lng"))
except (TypeError, ValueError):
return jsonify({"rtn_code": 400, "message": "缺少或非法的坐标参数"})
mode = (request.args.get("mode") or "walking").strip().lower()
if mode not in ("walking", "riding"):
mode = "walking"
import walk_route
data = walk_route.get_nav_route(o_lat, o_lng, d_lat, d_lng, api=mode)
if data.get("error"):
return jsonify({"rtn_code": 500, "message": data["error"]}), 200
response = jsonify({"rtn_code": 0, "data": data})
response.headers["Cache-Control"] = "private, max-age=30"
return response
@bp.route("/api/walk_route")
def api_walk_route():
"""步行路线:真实道路距离 + 步行耗时(百度轻量级路线规划)。
参数:origin_lat/origin_lng/dest_lat/dest_lng,**全部 GCJ02**
(前端要把 BD09 的我方位置先转 GCJ02 再传)。
返回:{rtn_code:0, data:{distance, duration, source}}
source = baidu(实时)/ cache(命中缓存)/ estimate(百度不可用时的本地估算)
"""
user = get_current_user()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
from routes.auth import _client_ip
from rate_limit import hit as rl_hit
# 保护百度配额:同一 IP 每分钟 60 次(正常点卡片远低于此)
if not rl_hit(("walk_route", _client_ip()), 60, 60):
return jsonify({"rtn_code": 429, "message": "请求过于频繁,请稍后再试"}), 429
try:
o_lat = float(request.args.get("origin_lat"))
o_lng = float(request.args.get("origin_lng"))
d_lat = float(request.args.get("dest_lat"))
d_lng = float(request.args.get("dest_lng"))
except (TypeError, ValueError):
return jsonify({"rtn_code": 400, "message": "缺少或非法的坐标参数"})
import walk_route
data = walk_route.get_walk_route(o_lat, o_lng, d_lat, d_lng)
response = jsonify({"rtn_code": 0, "data": data})
response.headers["Cache-Control"] = "private, max-age=60"
return response
# ========== 校园地点(订阅下拉 / 地点解析标签) ==========
@bp.route("/api/map/freshness")
def api_map_freshness():
"""优先返回共享地图快照的真实时间,未加载地图时兼容历史采集时间。
只读取缓存元数据,不会为了查询时间额外请求上游。
"""
from map_cache import shared_map_cache
snapshot = shared_map_cache.freshness(request.args.get("type", "3"))
if snapshot is not None:
response = jsonify({"rtn_code": 0, "data": snapshot})
response.headers["Cache-Control"] = "no-store"
return response
conn = get_db()
row = conn.execute(
"SELECT MAX(recorded_at) AS latest FROM bike_history").fetchone()
conn.close()
latest = row["latest"] if row else None
if not latest:
return jsonify({"rtn_code": 0, "data": {
"latest": None, "stale_seconds": None, "interval_hint": "暂无采集数据"}})
import datetime as dt
import sqlite3
# recorded_at 存的是北京时间字符串;SQLite datetime('now','+8 hours') 与之同源
try:
naive = dt.datetime.strptime(str(latest), "%Y-%m-%d %H:%M:%S")
latest_dt = naive.replace(tzinfo=dt.timezone(dt.timedelta(hours=8)))
now = dt.datetime.now(latest_dt.tzinfo)
stale = max(0, int((now - latest_dt).total_seconds()))
except (ValueError, TypeError):
return jsonify({"rtn_code": 0, "data": {
"latest": str(latest), "stale_seconds": None,
"interval_hint": "时间格式异常"}})
hint = "白天 5-10 分钟 / 夜间 30-60 分钟"
return jsonify({"rtn_code": 0, "data": {
"latest": str(latest), "stale_seconds": stale, "interval_hint": hint}})
@bp.route("/api/campus/locations")
def campus_locations():
"""校园地点(单点模型)。
- kind='poi'(楼/兴趣点):用于骑行起终点「最近归属」;
- kind='parking'(停车点):用于订阅提醒「附近有没有车」,带统计半径。
返回坐标为 GCJ02;bd09 字段是换算后的百度坐标,前端直接用它画在百度地图上。
"""
from campus import DEFAULT_PARKING_RADIUS_M, gcj02_to_bd09, load_locations
result = []
for loc in load_locations():
item = {
"id": loc["id"],
"name": loc["name"],
"kind": loc.get("kind") or "poi",
"latitude": loc.get("latitude"),
"longitude": loc.get("longitude"),
"radius": loc.get("radius") or (
DEFAULT_PARKING_RADIUS_M if (loc.get("kind") == "parking") else None),
"bd09": None,
}
if loc.get("latitude") is not None and loc.get("longitude") is not None:
bd = gcj02_to_bd09(loc["longitude"], loc["latitude"])
item["bd09"] = {"lat": bd[1], "lng": bd[0]}
result.append(item)
return jsonify({"rtn_code": 0, "data": result})
# ========== 用户信息 API ==========
@bp.route("/api/user/info")
def api_user_info():
user = get_current_user()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录"})
from wechat import request_with_user_auth
token_id, access_token = get_user_auth(user["id"])
if not token_id:
return jsonify({"rtn_code": 0, "has_auth": False, "message": "未配置微信凭据"})
result = request_with_user_auth(user["id"], "GET", "/user/info")
if result.get("rtn_code") != 0:
return jsonify({"rtn_code": result.get("rtn_code", 500), "has_auth": True, "message": result.get("message", "获取失败")})
data = result.get("data", {})
non_deal = data.get("nonDealOrder")
true_name = ""
account = data.get("account", {})
if isinstance(account, str):
try:
account = json.loads(account)
except Exception:
account = {}
true_name = account.get("trueName", "") if isinstance(account, dict) else ""
out_money = data.get("bus_account", {}).get("outMoneyBus", 0)
save_money = data.get("bus_account", {}).get("saveMoneyBus", 0)
return jsonify({
"rtn_code": 0, "has_auth": True,
"data": {
"true_name": true_name, "out_money": out_money,
"save_money": save_money, "has_auth": True,
"nonDealOrder": non_deal,
}
})
# ========== 首页路由 ==========
MAP_ASSETS = (
"css/map.css", "css/bike-clusters.css", "css/map-settings.css", "css/ui-system.css",
"js/ui-motion.js", "js/qrcode.min.js", "js/coordtransform.js", "js/bike-clusters.js",
"js/settings-pages.js", "dist/app.js",
)
def _map_asset_signature():
"""静态资源的 (绝对路径, mtime_ns, size) 签名:任一文件被改就变。
只做 stat,不读内容 —— 用它判断进程内缓存是否还能用。
"""
root = Path(current_app.static_folder)
signature = []
for filename in MAP_ASSETS:
path = root / filename
try:
info = path.stat()
signature.append((str(path), info.st_mtime_ns, info.st_size))
except OSError:
signature.append((str(path), None, None))
return tuple(signature)
def _map_asset_version():
"""Version the complete map bundle so deployments cannot reuse old dependencies.
首页每次请求都要这个版本号,而它要读完约 420KB 静态资源再 sha256(BUG-21)。
这里按 (路径, mtime, size) 做进程内缓存:文件没动就直接返回上次的结果,
文件一改(含部署覆盖、`touch`)签名就变,立刻重算,不会长期缓存旧 hash。
参与版本号的资源必须是页面真正引用的那一套(MAP_ASSETS),不要再抽掉什么
—— 少算一个文件就等于那个文件改了但浏览器仍用旧缓存。
"""
signature = _map_asset_signature()
with _map_asset_version_lock:
if _map_asset_version_cache["signature"] == signature \
and _map_asset_version_cache["version"]:
return _map_asset_version_cache["version"]
digest = hashlib.sha256()
for filename in MAP_ASSETS:
digest.update(filename.encode())
try:
digest.update((Path(current_app.static_folder) / filename).read_bytes())
except FileNotFoundError:
digest.update(b"missing")
version = digest.hexdigest()[:16]
with _map_asset_version_lock:
_map_asset_version_cache["signature"] = signature
_map_asset_version_cache["version"] = version
return version
@bp.route("/")
def index():
response = current_app.make_response(render_template("map.html", map_asset_version=_map_asset_version()))
response.headers["Cache-Control"] = "no-cache"
return response
@bp.route("/analysis.html")
def analysis_page():
return render_template("analysis.html")
@bp.route("/ring_progress.html")
def ring_progress():
# 进度页把会话 token 放在 URL 查询参数里,别让浏览器缓存页面或把带 token
# 的地址通过 Referer 带给第三方(页面内的地图/CDN 请求)。
response = current_app.make_response(render_template("ring_progress.html"))
response.headers["Cache-Control"] = "no-store"
response.headers["Referrer-Policy"] = "no-referrer"
return response