| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- """
- HMAC密钥模型
- 存储客户端的动态HMAC密钥
- """
- from sqlalchemy import Column, Integer, String, DateTime, Boolean, Text, Index
- from app.models.history_base import HistoryBase
- from datetime import datetime
- from app.utils.timezone import beijing_now_naive
- class HmacKey(HistoryBase):
- """HMAC密钥模型
-
- 用于存储客户端的动态HMAC密钥,支持:
- - 用户/机器码绑定
- - 密钥过期时间管理
- - 密钥轮换
- """
-
- __tablename__ = 'hmac_keys'
-
- # 基本信息
- user_id = Column(Integer, nullable=False, index=True, comment="用户ID")
- username = Column(String(64), nullable=False, comment="用户名")
- machine_code = Column(String(128), nullable=False, comment="机器码")
-
- # 密钥信息
- hmac_key = Column(Text, nullable=False, comment="HMAC密钥")
- key_version = Column(Integer, default=1, comment="密钥版本")
-
- # 过期时间
- expires_at = Column(DateTime, nullable=False, comment="过期时间")
-
- # 状态
- is_active = Column(Boolean, default=True, comment="是否活跃")
-
- # 索引
- __table_args__ = (
- Index('idx_hmac_key_lookup', 'user_id', 'machine_code', 'is_active'),
- Index('idx_hmac_key_expiry', 'expires_at', 'is_active'),
- )
-
- def __repr__(self):
- return f"<HmacKey(user_id={self.user_id}, username={self.username}, version={self.key_version})>"
-
- def is_expired(self) -> bool:
- """检查密钥是否过期"""
- return beijing_now_naive() > self.expires_at
-
- def is_valid(self) -> bool:
- """检查密钥是否有效"""
- return self.is_active and not self.is_expired()
-
- def to_dict(self) -> dict:
- """转换为字典"""
- return {
- "id": self.id,
- "user_id": self.user_id,
- "username": self.username,
- "machine_code": self.machine_code,
- "key_version": self.key_version,
- "expires_at": self.expires_at.isoformat() if self.expires_at else None,
- "is_active": self.is_active,
- "created_at": self.created_at.isoformat() if self.created_at else None,
- "updated_at": self.updated_at.isoformat() if self.updated_at else None,
- }
|