timestamp_validator.py 2.1 KB

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