Files
tyapi-server/internal/domains/finance/entities/user_secrets.go
2025-07-11 21:05:58 +08:00

68 lines
2.2 KiB
Go
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.

package entities
import (
"time"
"gorm.io/gorm"
)
// UserSecrets 用户密钥实体
// 存储用户的API访问密钥信息用于第三方服务集成和API调用
// 支持密钥的生命周期管理,包括激活状态、过期时间、使用统计等
type UserSecrets struct {
// 基础标识
ID string `gorm:"primaryKey;type:varchar(36)" comment:"密钥记录唯一标识"`
UserID string `gorm:"type:varchar(36);not null;uniqueIndex" comment:"关联用户ID"`
AccessID string `gorm:"type:varchar(100);not null;uniqueIndex" comment:"访问ID(用于API认证)"`
AccessKey string `gorm:"type:varchar(255);not null" comment:"访问密钥(加密存储)"`
// 密钥状态 - 密钥的生命周期管理
IsActive bool `gorm:"default:true" comment:"密钥是否激活"`
LastUsedAt *time.Time `comment:"最后使用时间"`
ExpiresAt *time.Time `comment:"密钥过期时间"`
// 时间戳字段
CreatedAt time.Time `gorm:"autoCreateTime" comment:"创建时间"`
UpdatedAt time.Time `gorm:"autoUpdateTime" comment:"更新时间"`
DeletedAt gorm.DeletedAt `gorm:"index" comment:"软删除时间"`
}
// TableName 指定数据库表名
func (UserSecrets) TableName() string {
return "user_secrets"
}
// IsExpired 检查密钥是否已过期
// 判断密钥是否超过有效期,过期后需要重新生成或续期
func (u *UserSecrets) IsExpired() bool {
if u.ExpiresAt == nil {
return false // 没有过期时间表示永不过期
}
return time.Now().After(*u.ExpiresAt)
}
// IsValid 检查密钥是否有效
// 综合判断密钥是否可用,包括激活状态和过期状态检查
func (u *UserSecrets) IsValid() bool {
return u.IsActive && !u.IsExpired()
}
// UpdateLastUsedAt 更新最后使用时间
// 在密钥被使用时调用,记录最新的使用时间,用于使用统计和监控
func (u *UserSecrets) UpdateLastUsedAt() {
now := time.Now()
u.LastUsedAt = &now
}
// Deactivate 停用密钥
// 将密钥设置为非激活状态禁止使用该密钥进行API调用
func (u *UserSecrets) Deactivate() {
u.IsActive = false
}
// Activate 激活密钥
// 重新启用密钥允许使用该密钥进行API调用
func (u *UserSecrets) Activate() {
u.IsActive = true
}