timestamp_validator.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. # 使用纵表设计,从配置表中获取时间戳容忍值
  16. config = db.query(SystemConfig).filter(
  17. SystemConfig.config_key == 'timestamp_tolerance_seconds',
  18. SystemConfig.is_deleted == 0
  19. ).first()
  20. if config:
  21. # 根据配置类型转换值
  22. if config.config_type == 'int':
  23. return int(config.config_value)
  24. else:
  25. return int(config.config_value)
  26. return 300 # 默认5分钟
  27. except Exception as e:
  28. logger.exception("获取时间戳容忍配置失败")
  29. return 300
  30. @staticmethod
  31. def validate_timestamp(request_timestamp: int, db: Session) -> tuple[bool, str]:
  32. """
  33. 验证请求时间戳是否有效
  34. Args:
  35. request_timestamp: 请求中的时间戳
  36. db: 数据库会话
  37. Returns:
  38. tuple: (是否有效, 错误信息)
  39. """
  40. try:
  41. # 获取当前时间戳
  42. current_timestamp = int(time.time())
  43. # 获取容忍时间范围
  44. tolerance = TimestampValidator.get_timestamp_tolerance(db)
  45. # 计算时间差
  46. time_diff = abs(current_timestamp - request_timestamp)
  47. # 检查是否在容忍范围内
  48. if time_diff > tolerance:
  49. logger.warning(f"时间戳验证失败: 请求时间戳={request_timestamp}, 当前时间戳={current_timestamp}, 差值={time_diff}秒, 容忍范围={tolerance}秒")
  50. return False, f"时间戳超出容忍范围({tolerance}秒)"
  51. logger.debug(f"时间戳验证通过: 请求时间戳={request_timestamp}, 当前时间戳={current_timestamp}, 差值={time_diff}秒")
  52. return True, ""
  53. except Exception as e:
  54. logger.exception("时间戳验证异常")
  55. return False, f"时间戳验证异常: {str(e)}"
  56. @staticmethod
  57. def generate_timestamp() -> int:
  58. """生成当前时间戳"""
  59. return int(time.time())