timestamp_validator.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """
  2. 时间戳验证工具
  3. """
  4. import time
  5. from typing import Optional
  6. from sqlalchemy.orm import Session
  7. from app.core.logger import logger
  8. # 时间戳容忍秒数(硬编码)
  9. TIMESTAMP_TOLERANCE_SECONDS = 300 # 默认5分钟
  10. class TimestampValidator:
  11. """时间戳验证器"""
  12. @staticmethod
  13. def get_timestamp_tolerance(db: Session) -> int:
  14. """获取时间戳容忍秒数"""
  15. # 硬编码时间戳容忍值
  16. return TIMESTAMP_TOLERANCE_SECONDS
  17. @staticmethod
  18. def validate_timestamp(request_timestamp: int, db: Session) -> tuple[bool, str]:
  19. """
  20. 验证请求时间戳是否有效
  21. Args:
  22. request_timestamp: 请求中的时间戳
  23. db: 数据库会话
  24. Returns:
  25. tuple: (是否有效, 错误信息)
  26. """
  27. try:
  28. # 获取当前时间戳
  29. current_timestamp = int(time.time())
  30. # 获取容忍时间范围
  31. tolerance = TimestampValidator.get_timestamp_tolerance(db)
  32. # 计算时间差
  33. time_diff = abs(current_timestamp - request_timestamp)
  34. # 检查是否在容忍范围内
  35. if time_diff > tolerance:
  36. logger.warning(f"时间戳验证失败: 请求时间戳={request_timestamp}, 当前时间戳={current_timestamp}, 差值={time_diff}秒, 容忍范围={tolerance}秒")
  37. return False, f"时间戳超出容忍范围({tolerance}秒)"
  38. logger.debug(f"时间戳验证通过: 请求时间戳={request_timestamp}, 当前时间戳={current_timestamp}, 差值={time_diff}秒")
  39. return True, ""
  40. except Exception as e:
  41. logger.exception("时间戳验证异常")
  42. return False, f"时间戳验证异常: {str(e)}"
  43. @staticmethod
  44. def generate_timestamp() -> int:
  45. """生成当前时间戳"""
  46. return int(time.time())