Documentation
¶
Index ¶
- Constants
- Variables
- func AccountDeletionEligibilityReasons(db *gorm.DB, user *User, accountLocked bool, remoteLoginRisk bool, ...) []string
- func AccountDeletionPending(user *User) bool
- func AdminRequired(c *gin.Context)
- func AuthRequired(c *gin.Context)
- func CalculateProfileComplete(user *User) int
- func CancelAccountDeletion(db *gorm.DB, userID uint, operator string) error
- func ChangePassword(db *gorm.DB, user *User, oldPassword, newPassword string) error
- func CheckDeviceTrust(db *gorm.DB, userID uint, deviceID string) (bool, error)
- func CheckPassword(user *User, password string) bool
- func CheckUserAllowLogin(db *gorm.DB, user *User) error
- func CreateBackupCodes(db *gorm.DB, userId int, codes []string) error
- func DefaultAccountDeletionCooldown() time.Duration
- func DeletePasskeyByUserID(db *gorm.DB, userID int) error
- func DeleteUserDevice(db *gorm.DB, userID uint, deviceID string) error
- func DisableTwoFA(db *gorm.DB, userId int) error
- func FinalizeAccountDeletion(db *gorm.DB, userID uint, operator string) error
- func GenerateEmailVerifyToken(db *gorm.DB, user *User) (string, error)
- func GeneratePasswordResetToken(db *gorm.DB, user *User) (string, error)
- func GeneratePhoneVerifyToken(db *gorm.DB, user *User) (string, error)
- func GenerateTwoFATOTPSetupMaterial(issuer string, user *User) (*utils.TOTPSetup, error)
- func GetTwoFAStats(db *gorm.DB) (map[string]interface{}, error)
- func GetUnusedBackupCodeCount(db *gorm.DB, userId int) (int, error)
- func HasRecentSuspiciousLogins(db *gorm.DB, userID uint, lookback time.Duration) (bool, error)
- func HashPassword(password string) string
- func InTimezone(c *gin.Context, timezone string)
- func IncrementLoginCount(db *gorm.DB, user *User) error
- func IsExistsByEmail(db *gorm.DB, email string) bool
- func IsLLMChannelProtocolKnown(p string) bool
- func IsNotificationChannelTypeKnown(t string) bool
- func IsTwoFAEnabled(db *gorm.DB, userId int) bool
- func Login(c *gin.Context, user *User)
- func Logout(c *gin.Context, user *User)
- func MaskTokenKey(key string) string
- func NormalizeUserSource(raw string) string
- func NormalizeUserStatus(raw string) string
- func RecordLoginHistory(db *gorm.DB, userID uint, ...) error
- func ResetPassword(db *gorm.DB, user *User, newPassword string) error
- func ScheduleAccountDeletion(db *gorm.DB, userID uint, operator string) error
- func SetLastLogin(db *gorm.DB, user *User, lastIp string) error
- func SetPassword(db *gorm.DB, user *User, password string) (err error)
- func SplitLLMModelNamesCSV(s string) []string
- func SyncLLMAbilitiesFromChannel(db *gorm.DB, ch *LLMChannel) error
- func ThirdPartyBindings(user *User) (github bool, wechat bool)
- func TrustUserDevice(db *gorm.DB, userID uint, deviceID string) error
- func UnlockAccount(db *gorm.DB, email string, userID uint) error
- func UntrustUserDevice(db *gorm.DB, userID uint, deviceID string) error
- func UpdateNotificationSettings(db *gorm.DB, user *User, settings map[string]bool) error
- func UpdatePreferences(db *gorm.DB, user *User, preferences map[string]string) error
- func UpdateProfileComplete(db *gorm.DB, user *User) error
- func UpdateUser(db *gorm.DB, user *User, vals map[string]any) error
- func UpdateUserFields(db *gorm.DB, user *User, vals map[string]any) error
- func UpsertPasskeyCredential(db *gorm.DB, credential *PasskeyCredential) error
- func UserStatusAllowsLogin(status string) bool
- func ValidateBackupCode(db *gorm.DB, userId int, code string) (bool, error)
- func ValidateUserRole(user *User) error
- func VerifyEncryptedPassword(encryptedPassword, storedPasswordHash string) bool
- func VerifyPhone(db *gorm.DB, user *User, token string) error
- type ASRChannel
- type AccountLock
- type AgentRun
- type AgentStep
- type BaseModel
- func (m *BaseModel) GetCreatedAtString() string
- func (m *BaseModel) GetCreatedAtUnix() int64
- func (m *BaseModel) GetUpdatedAtString() string
- func (m *BaseModel) GetUpdatedAtUnix() int64
- func (m *BaseModel) IsSoftDeleted() bool
- func (m *BaseModel) SetCreateInfo(operator string)
- func (m *BaseModel) SetUpdateInfo(operator string)
- type ChangePasswordForm
- type ChatMessage
- type ChatSession
- type Credential
- type EmailOperatorForm
- type InternalNotification
- type LLMAbility
- type LLMChannel
- type LLMChannelInfo
- type LLMModelMeta
- type LLMUsage
- type LLMUsageChannelAttempt
- type LLMUsageChannelAttempts
- type LLMUsageUserDaily
- type LLMUsageUserModelDaily
- type LoginForm
- type LoginHistory
- type MailTemplate
- type MultiKeyMode
- type NotificationChannel
- type PasskeyCredential
- func (p *PasskeyCredential) ApplyValidatedCredential(credential *webauthn.Credential)
- func (p *PasskeyCredential) SetTransports(list []protocol.AuthenticatorTransport)
- func (p *PasskeyCredential) ToWebAuthnCredential() webauthn.Credential
- func (p *PasskeyCredential) TransportList() []protocol.AuthenticatorTransport
- type RegisterUserForm
- type ResetPasswordDoneForm
- type ResetPasswordForm
- type SendEmailVerifyEmail
- type SiteAnnouncement
- type SpeechUsage
- type TTSChannel
- type TwoFA
- func (t *TwoFA) Create(db *gorm.DB) error
- func (t *TwoFA) Delete(db *gorm.DB) error
- func (t *TwoFA) Enable(db *gorm.DB) error
- func (t *TwoFA) IncrementFailedAttempts(db *gorm.DB) error
- func (t *TwoFA) IsLocked() bool
- func (t *TwoFA) ResetFailedAttempts(db *gorm.DB) error
- func (t *TwoFA) Update(db *gorm.DB) error
- func (t *TwoFA) ValidateBackupCodeAndUpdateUsage(db *gorm.DB, code string) (bool, error)
- func (t *TwoFA) ValidateTOTPAndUpdateUsage(db *gorm.DB, code string) (bool, error)
- type TwoFABackupCode
- type UpdateUserRequest
- type User
- func CreateUser(db *gorm.DB, email, password string) (*User, error)
- func CreateUserByEmail(db *gorm.DB, username, display, email, password string) (*User, error)
- func CreateUserByEmailWithMeta(db *gorm.DB, username, display, email, password, source, status string) (*User, error)
- func CreateUserWithMeta(db *gorm.DB, email, password, source, status string) (*User, error)
- func CurrentUser(c *gin.Context) *User
- func GetUserByEmail(db *gorm.DB, email string) (user *User, err error)
- func GetUserByUID(db *gorm.DB, userID uint) (*User, error)
- func ListUsersDueForAccountDeletion(db *gorm.DB, before time.Time) ([]User, error)
- func VerifyEmailLoginCode(db *gorm.DB, email, code string) (*User, error)
- func VerifyPasswordResetToken(db *gorm.DB, token string) (*User, error)
- type UserBasicInfoUpdate
- type UserDevice
Constants ¶
const ( SoftDeleteStatusActive int8 = 0 // Not deleted SoftDeleteStatusDeleted int8 = 1 // Deleted )
const ( CredentialKindLLM = "llm" // 大模型 API Key;ModelLimits* 字段主要对此类生效 CredentialKindASR = "asr" // 语音识别 CredentialKindTTS = "tts" // 语音合成 CredentialKindEmail = "email" // 邮件类第三方 API Key 等 )
凭证服务类型:同一套「密钥 + 配额 + IP 限制」承载多种上游能力。
const ( LLMChannelProtocolOpenAI = "openai" LLMChannelProtocolAnthropic = "anthropic" LLMChannelProtocolCoze = "coze" LLMChannelProtocolOllama = "ollama" LLMChannelProtocolLMStudio = "lmstudio" )
上游 LLM 渠道商 / 协议(与路由、鉴权头、Base URL 约定对齐)。
const ( NotificationChannelTypeEmail = "email" NotificationChannelTypeSMS = "sms" )
通知渠道类型(可随业务扩展,发送侧按 Type 解析 ConfigJSON)。
const ( SpeechUsageKindASR = "asr" SpeechUsageKindTTS = "tts" )
OpenAPI 语音用量种类(与 speech_usage.kind 一致)。
const ( RoleSuperAdmin = "superadmin" // 超级管理员 RoleAdmin = "admin" // 管理员 RoleUser = "user" // 普通用户 )
const ( UserSourceSystem = "SYSTEM" UserSourceAdmin = "ADMIN" UserSourceWechat = "WECHAT" UserSourceGithub = "GITHUB" )
const ( UserStatusActive = "active" UserStatusPendingVerification = "pending_verification" UserStatusSuspended = "suspended" UserStatusBanned = "banned" )
Variables ¶
var ( ErrPasskeyNotFound = errors.New("passkey credential not found") ErrFriendlyPasskeyNotFound = errors.New("Passkey 验证失败,请重试或联系管理员") )
var ErrTwoFANotEnabled = errors.New("2fa not enabled")
var LLMChannelProtocols = []string{ LLMChannelProtocolOpenAI, LLMChannelProtocolAnthropic, LLMChannelProtocolCoze, LLMChannelProtocolOllama, LLMChannelProtocolLMStudio, }
LLMChannelProtocols 管理端可选协议列表。
Functions ¶
func AccountDeletionEligibilityReasons ¶
func AccountDeletionEligibilityReasons(db *gorm.DB, user *User, accountLocked bool, remoteLoginRisk bool, recentSuspicious bool) []string
AccountDeletionEligibilityReasons 返回不满足注销申请条件的原因(空切片表示通过基础校验)。
func AccountDeletionPending ¶
AccountDeletionPending 是否在冷静期内(已申请、尚未到期、账号仍为正常态)。
func AdminRequired ¶
AdminRequired 须在 AuthRequired 之后注册;仅管理员(admin / superadmin)可继续。
func AuthRequired ¶
AuthRequired 依赖 CurrentUser:其中已包含 session cookie 与 Authorization Bearer access JWT 的解析与装库(见 CurrentUser 末尾 jwtauth.ParseAccessToken)。
func CalculateProfileComplete ¶
CalculateProfileComplete 计算资料完整度
func CancelAccountDeletion ¶
CancelAccountDeletion 用户主动撤回注销申请。
func ChangePassword ¶
ChangePassword 修改密码
func CheckDeviceTrust ¶
CheckDeviceTrust 检查设备是否被信任
func CheckPassword ¶
func CreateBackupCodes ¶
CreateBackupCodes 创建备用码
func DefaultAccountDeletionCooldown ¶
DefaultAccountDeletionCooldown 默认冷静期 72 小时(3 天),可通过环境变量 ACCOUNT_DELETION_COOLDOWN_HOURS 覆盖。
func DeleteUserDevice ¶
DeleteUserDevice 删除用户设备
func FinalizeAccountDeletion ¶
FinalizeAccountDeletion 永久注销:删除绑定类数据,将用户行匿名化并软删除;不删除助手、知识库等业务资源。
func GenerateEmailVerifyToken ¶
GenerateEmailVerifyToken 生成邮箱登录用 6 位数字验证码(写入 email_verify_token,短期有效)。
func GeneratePasswordResetToken ¶
GeneratePasswordResetToken 生成密码重置令牌
func GeneratePhoneVerifyToken ¶
GeneratePhoneVerifyToken 生成手机验证令牌
func GenerateTwoFATOTPSetupMaterial ¶
GenerateTwoFATOTPSetupMaterial 生成绑定 TOTP 所需的密钥、otpauth URL 与二维码(依赖 pkg/utils/totp)。 将 Secret 写入 TwoFA 前应由用户用验证器校验首码。
func GetTwoFAStats ¶
GetTwoFAStats 获取2FA统计信息(管理员使用)
func GetUnusedBackupCodeCount ¶
GetUnusedBackupCodeCount 获取未使用的备用码数量
func HasRecentSuspiciousLogins ¶
HasRecentSuspiciousLogins 近期是否存在标记为可疑的成功登录(用于注销前风控)。
func HashPassword ¶
func InTimezone ¶
func IncrementLoginCount ¶
IncrementLoginCount 增加登录次数
func IsLLMChannelProtocolKnown ¶
IsLLMChannelProtocolKnown 校验 API 入参。
func IsNotificationChannelTypeKnown ¶
IsNotificationChannelTypeKnown 用于校验 API 入参
func MaskTokenKey ¶
func NormalizeUserSource ¶
NormalizeUserSource 统一为大写合法值,未知则回落为 SYSTEM。
func NormalizeUserStatus ¶
NormalizeUserStatus 校验并规范化状态字符串。
func RecordLoginHistory ¶
func RecordLoginHistory(db *gorm.DB, userID uint, email, ipAddress, location, country, city, userAgent, deviceID, loginType string, success bool, failureReason string, isSuspicious bool) error
RecordLoginHistory 记录登录历史
func ResetPassword ¶
ResetPassword 重置密码
func ScheduleAccountDeletion ¶
ScheduleAccountDeletion 进入冷静期。
func SplitLLMModelNamesCSV ¶
SplitLLMModelNamesCSV 解析渠道「模型」配置字段(逗号/分号/换行分隔)。
func SyncLLMAbilitiesFromChannel ¶
func SyncLLMAbilitiesFromChannel(db *gorm.DB, ch *LLMChannel) error
SyncLLMAbilitiesFromChannel 按渠道 models、group 重建该 channel_id 下全部能力行。
func ThirdPartyBindings ¶
ThirdPartyBindings 是否仍绑定 GitHub / 微信。
func TrustUserDevice ¶
TrustUserDevice 信任设备
func UnlockAccount ¶
UnlockAccount 解锁账号
func UntrustUserDevice ¶
UntrustUserDevice 取消信任设备
func UpdateNotificationSettings ¶
UpdateNotificationSettings 更新通知设置
func UpdatePreferences ¶
UpdatePreferences 更新用户偏好设置 只处理实际使用的字段:timezone 和 locale
func UpdateProfileComplete ¶
UpdateProfileComplete 更新资料完整度
func UpsertPasskeyCredential ¶
func UpsertPasskeyCredential(db *gorm.DB, credential *PasskeyCredential) error
func UserStatusAllowsLogin ¶
UserStatusAllowsLogin 是否允许登录(仅正常态)。
func ValidateBackupCode ¶
ValidateBackupCode 验证并使用备用码
func ValidateUserRole ¶
ValidateUserRole validates that the user has a valid role
func VerifyEncryptedPassword ¶
VerifyEncryptedPassword 验证加密密码 前端发送格式:passwordHash:encryptedHash:salt:timestamp passwordHash = SHA256(原始密码) - 用于验证密码正确性 encryptedHash = SHA256(原始密码 + salt + timestamp) - 用于防重放 后端验证: 1. passwordHash 与存储的密码哈希匹配(去掉 sha256$ 前缀) 2. 时间戳在有效期内(5分钟) 3. 验证 salt 是否在缓存中(防重放)
Types ¶
type ASRChannel ¶
type ASRChannel struct {
BaseModel
Provider string `json:"provider" gorm:"size:64;not null;index;comment:厂商如 aliyun_funasr、azure、whisper"`
Name string `json:"name" gorm:"size:128;not null;comment:展示名称"`
Enabled bool `json:"enabled" gorm:"not null;default:true;index;comment:是否启用"`
Group string `json:"group" gorm:"size:64;default:'';index;comment:路由分组"`
SortOrder int `json:"sortOrder" gorm:"not null;default:0;index;comment:同组内优先级"`
ConfigJSON string `json:"configJson,omitempty" gorm:"type:text;comment:厂商相关 JSON 配置"`
}
ASRChannel 语音识别上游渠道;厂商、鉴权、endpoint 等差异放在 ConfigJSON(与 Provider 联合解析)。
type AccountLock ¶
type AccountLock struct {
BaseModel
UserID uint `gorm:"index;not null" json:"userId"`
Email string `gorm:"size:128;index;not null" json:"email"` // 邮箱(用于未登录时的锁定)
IPAddress string `gorm:"size:128;index" json:"ipAddress"` // 锁定IP
LockedAt time.Time `gorm:"index" json:"lockedAt"` // 锁定时间
UnlockAt time.Time `gorm:"index" json:"unlockAt"` // 解锁时间
Reason string `gorm:"size:256" json:"reason"` // 锁定原因
FailedAttempts int `gorm:"default:0" json:"failedAttempts"` // 失败次数
IsActive bool `gorm:"default:true;index" json:"isActive"` // 是否激活
}
AccountLock 账号锁定记录
func CreateOrUpdateAccountLock ¶
func CreateOrUpdateAccountLock(db *gorm.DB, email string, userID uint, ipAddress string, failedAttempts int) (*AccountLock, error)
CreateOrUpdateAccountLock 创建或更新账号锁定记录
func GetAccountLock ¶
GetAccountLock 获取账号锁定记录
func (AccountLock) TableName ¶
func (AccountLock) TableName() string
type AgentRun ¶
type AgentRun struct {
ID string `json:"id" gorm:"primaryKey;type:varchar(64)"`
SessionID string `json:"session_id" gorm:"type:varchar(64);index;not null"`
UserID string `json:"user_id" gorm:"type:varchar(64);index;not null"`
Goal string `json:"goal" gorm:"type:text;not null"`
Status string `json:"status" gorm:"type:varchar(20);index;not null"` // queued/running/succeeded/failed/cancelled
Phase string `json:"phase" gorm:"type:varchar(32);index"` // planning/executing/reflecting
PlanJSON string `json:"plan_json" gorm:"type:longtext"`
ResultText string `json:"result_text" gorm:"type:longtext"`
ErrorMessage string `json:"error_message" gorm:"type:text"`
TotalSteps int `json:"total_steps" gorm:"default:0"`
TotalTokens int `json:"total_tokens" gorm:"default:0"`
MaxSteps int `json:"max_steps" gorm:"default:0"`
MaxCostTokens int `json:"max_cost_tokens" gorm:"default:0"`
MaxDurationMs int64 `json:"max_duration_ms" gorm:"default:0"`
StartedAt time.Time `json:"started_at" gorm:"index"`
CompletedAt time.Time `json:"completed_at"`
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
}
type AgentStep ¶
type AgentStep struct {
ID string `json:"id" gorm:"primaryKey;type:varchar(64)"`
RunID string `json:"run_id" gorm:"type:varchar(64);index;not null"`
StepID string `json:"step_id" gorm:"type:varchar(64);index;not null"`
TaskID string `json:"task_id" gorm:"type:varchar(64);index"`
Title string `json:"title" gorm:"type:varchar(255)"`
Instruction string `json:"instruction" gorm:"type:text"`
Status string `json:"status" gorm:"type:varchar(20);index;not null"` // queued/running/waiting_tool/succeeded/failed/cancelled
Model string `json:"model" gorm:"type:varchar(100)"`
InputJSON string `json:"input_json" gorm:"type:longtext"`
OutputText string `json:"output_text" gorm:"type:longtext"`
ErrorMessage string `json:"error_message" gorm:"type:text"`
Feedback string `json:"feedback" gorm:"type:text"`
Attempts int `json:"attempts" gorm:"default:0"`
InputTokens int `json:"input_tokens" gorm:"default:0"`
OutputTokens int `json:"output_tokens" gorm:"default:0"`
TotalTokens int `json:"total_tokens" gorm:"default:0"`
LatencyMs int64 `json:"latency_ms" gorm:"default:0"`
StartedAt time.Time `json:"started_at" gorm:"index"`
CompletedAt time.Time `json:"completed_at"`
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
}
type BaseModel ¶
type BaseModel struct {
ID uint `json:"id" gorm:"primaryKey"`
CreatedAt time.Time `json:"createdAt" gorm:"autoCreateTime;comment:Creation time"`
UpdatedAt time.Time `json:"updatedAt,omitempty" gorm:"autoUpdateTime;comment:Update time"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
CreateBy string `json:"createBy,omitempty" gorm:"size:128;comment:Creator"`
UpdateBy string `json:"updateBy,omitempty" gorm:"size:128;comment:Updater"`
Remark string `json:"remark,omitempty" gorm:"size:128;comment:Remark"`
}
func (*BaseModel) GetCreatedAtString ¶
GetCreatedAtString 获取格式化创建时间
func (*BaseModel) GetCreatedAtUnix ¶
GetCreatedAtUnix 获取创建时间戳
func (*BaseModel) GetUpdatedAtString ¶
GetUpdatedAtString 获取格式化更新时间
func (*BaseModel) GetUpdatedAtUnix ¶
GetUpdatedAtUnix 获取更新时间戳
func (*BaseModel) SetCreateInfo ¶
SetCreateInfo 设置创建人信息
func (*BaseModel) SetUpdateInfo ¶
SetUpdateInfo 设置更新人信息
type ChangePasswordForm ¶
type ChangePasswordForm struct {
Password string `json:"password" binding:"required"`
}
type ChatMessage ¶
type ChatMessage struct {
ID string `json:"id" gorm:"primaryKey;type:varchar(64)"` // 雪花算法生成的ID
SessionID string `json:"session_id" gorm:"type:varchar(64);not null;index"`
Role string `json:"role" gorm:"type:varchar(20);not null"` // user, assistant, system
Content string `json:"content" gorm:"type:text;not null"`
TokenCount int `json:"token_count" gorm:"default:0"`
Model string `json:"model" gorm:"type:varchar(100);not null"`
Provider string `json:"provider" gorm:"type:varchar(50);not null"`
RequestID string `json:"request_id" gorm:"type:varchar(64);index"` // 关联到LLMUsage
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
DeletedAt *time.Time `json:"deleted_at,omitempty" gorm:"index"`
}
ChatMessage 聊天消息表
func (ChatMessage) TableName ¶
func (ChatMessage) TableName() string
type ChatSession ¶
type ChatSession struct {
ID string `json:"id" gorm:"primaryKey;type:varchar(64)"` // 雪花算法生成的ID
UserID string `json:"user_id" gorm:"type:varchar(64);not null;index"`
Title string `json:"title" gorm:"type:varchar(255)"`
Provider string `json:"provider" gorm:"type:varchar(50);not null"` // LLM提供商
Model string `json:"model" gorm:"type:varchar(100);not null"`
SystemPrompt string `json:"system_prompt" gorm:"type:text"`
Status string `json:"status" gorm:"type:varchar(20);default:'active'"` // active, archived, deleted
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
DeletedAt *time.Time `json:"deleted_at,omitempty" gorm:"index"`
}
ChatSession 聊天会话表
type Credential ¶
type Credential struct {
Id int `json:"id"`
UserId int `json:"user_id" gorm:"index:idx_credential_user_kind"`
Kind string `json:"kind" gorm:"size:16;index:idx_credential_user_kind;default:llm"`
Key string `json:"key" gorm:"type:char(48);uniqueIndex"`
Status int `json:"status" gorm:"default:1"` // 1 启用 0 禁用
Name string `json:"name" gorm:"index"`
ExtraJSON string `json:"extra,omitempty" gorm:"column:extra_json;type:text"`
CreatedTime int64 `json:"created_time" gorm:"bigint"`
AccessedTime int64 `json:"accessed_time" gorm:"bigint"`
ExpiredTime int64 `json:"expired_time" gorm:"bigint;default:-1"` // -1 永不过期
RemainQuota int `json:"remain_quota" gorm:"default:0"`
UnlimitedQuota bool `json:"unlimited_quota"`
UsedQuota int `json:"used_quota" gorm:"default:0"`
ModelLimitsEnabled bool `json:"model_limits_enabled"`
ModelLimits string `json:"model_limits" gorm:"type:text"`
AllowIps *string `json:"allow_ips" gorm:"default:''"`
Group string `json:"group" gorm:"default:''"`
CrossGroupRetry bool `json:"cross_group_retry"`
// OpenAPIModelCatalogJSON /v1/models 与前端展示用;JSON 数组,元素为 {"id":"..."} 或字符串。
// 为空时从本凭证 group 下 OpenAI 协议渠道的 models 字段汇总。
OpenAPIModelCatalogJSON string `json:"openapi_model_catalog,omitempty" gorm:"column:openapi_model_catalog_json;type:text"`
DeletedAt gorm.DeletedAt `gorm:"index"`
}
Credential 用户侧可调用的访问凭证。 各 kind 专有字段优先放在 ExtraJSON(JSON 文本)。
type EmailOperatorForm ¶
type EmailOperatorForm struct {
UserName string `json:"userName"`
DisplayName string `json:"displayName"`
Email string `json:"email" comment:"Email address"`
Code string `json:"code"`
Password string `json:"password"`
AuthToken bool `json:"AuthToken,omitempty"`
Timezone string `json:"timezone,omitempty"`
CaptchaID string `json:"captchaId,omitempty"`
CaptchaCode string `json:"captchaCode,omitempty"`
CaptchaType string `json:"captchaType,omitempty"`
CaptchaData string `json:"captchaData,omitempty"`
}
type InternalNotification ¶
type InternalNotification struct {
ID uint `json:"id" gorm:"primaryKey"`
CreatedAt time.Time `json:"createdAt" gorm:"autoCreateTime;comment:Creation time"`
UpdatedAt time.Time `json:"updatedAt,omitempty" gorm:"autoUpdateTime;comment:Update time"`
DeletedAt gorm.DeletedAt `json:"deletedAt,omitempty" gorm:"index"`
CreateBy string `json:"createBy,omitempty" gorm:"size:128;comment:Creator"`
UpdateBy string `json:"updateBy,omitempty" gorm:"size:128;comment:Updater"`
Remark string `json:"remark,omitempty" gorm:"size:128;comment:Remark"`
UserID uint `json:"userId" gorm:"index;not null;comment:接收用户 ID"`
Title string `json:"title" gorm:"size:255;not null;comment:标题"`
Content string `json:"content" gorm:"type:text;not null;comment:正文"`
Read bool `json:"read" gorm:"default:false;index;comment:是否已读"`
}
InternalNotification 站内通知(非邮件);邮件通道仍使用 pkg/notification 与 MailTemplate。 前台与站点公告(SiteAnnouncement)同置于「系统消息」弹窗的「通知」页签,需登录后拉取 /api/internal-notifications。 字段与 BaseModel 对齐,并对 DeletedAt 使用 json:"deletedAt" 便于前端展示/同步。
func (*InternalNotification) IsSoftDeleted ¶
func (m *InternalNotification) IsSoftDeleted() bool
IsSoftDeleted 是否已软删除(与 BaseModel 判定方式一致)
func (*InternalNotification) SetCreateInfo ¶
func (m *InternalNotification) SetCreateInfo(operator string)
SetCreateInfo 设置创建人(与 BaseModel 行为一致)
func (*InternalNotification) SetUpdateInfo ¶
func (m *InternalNotification) SetUpdateInfo(operator string)
SetUpdateInfo 设置更新人
func (InternalNotification) TableName ¶
func (InternalNotification) TableName() string
TableName GORM 表名
type LLMAbility ¶
type LLMAbility struct {
Group string `json:"group" gorm:"primaryKey;size:64;index:idx_llm_ability_group_model,priority:1"`
Model string `json:"model" gorm:"primaryKey;size:255;index:idx_llm_ability_group_model,priority:2"`
ChannelId int `json:"channel_id" gorm:"primaryKey;index"`
ModelMetaID *uint `json:"model_meta_id,omitempty" gorm:"index"` // 可选:与 llm_model_metas 关联(展示/校验)
Enabled bool `json:"enabled" gorm:"default:true;index"`
Priority int64 `json:"priority" gorm:"default:0;index"`
Weight uint `json:"weight" gorm:"default:1"`
Tag *string `json:"tag,omitempty" gorm:"size:64"`
}
LLMAbility 分组 + 模型名 → 可承载的 LLM 渠道(对齐 new-api abilities 思路)。
func (LLMAbility) TableName ¶
func (LLMAbility) TableName() string
type LLMChannel ¶
type LLMChannel struct {
Id int `json:"id"`
Protocol string `json:"protocol" gorm:"size:32;not null;default:'openai';index;comment:渠道协议 openai|anthropic|coze|ollama|lmstudio"`
Type int `json:"type" gorm:"default:0"`
Key string `json:"key" gorm:"not null"`
OpenAIOrganization *string `json:"openai_organization"`
TestModel *string `json:"test_model"`
Status int `json:"status" gorm:"default:1"`
Name string `json:"name" gorm:"index"`
Weight *uint `json:"weight" gorm:"default:0"`
CreatedTime int64 `json:"created_time" gorm:"bigint"`
TestTime int64 `json:"test_time" gorm:"bigint"`
ResponseTime int `json:"response_time"` // in milliseconds
BaseURL *string `json:"base_url" gorm:"column:base_url;default:''"`
Balance float64 `json:"balance"` // in USD
BalanceUpdatedTime int64 `json:"balance_updated_time" gorm:"bigint"`
Models string `json:"models"`
Group string `json:"group" gorm:"type:varchar(64);default:'default'"`
UsedQuota int64 `json:"used_quota" gorm:"bigint;default:0"`
ModelMapping *string `json:"model_mapping" gorm:"type:text"`
StatusCodeMapping *string `json:"status_code_mapping" gorm:"type:varchar(1024);default:''"`
Priority *int64 `json:"priority" gorm:"bigint;default:0"`
AutoBan *int `json:"auto_ban" gorm:"default:1"`
Tag *string `json:"tag" gorm:"index"`
ChannelInfo LLMChannelInfo `json:"channel_info" gorm:"column:channel_info;type:json"`
Keys []string `json:"-" gorm:"-"`
}
LLMChannel 大模型上游渠道(OpenAI 兼容、自建网关等),与 ASR/TTS 分表。
type LLMChannelInfo ¶
type LLMChannelInfo struct {
IsMultiKey bool `json:"is_multi_key"`
MultiKeySize int `json:"multi_key_size"`
MultiKeyStatusList map[int]int `json:"multi_key_status_list"`
MultiKeyDisabledReason map[int]string `json:"multi_key_disabled_reason,omitempty"`
MultiKeyDisabledTime map[int]int64 `json:"multi_key_disabled_time,omitempty"`
MultiKeyPollingIndex int `json:"multi_key_polling_index"`
MultiKeyMode MultiKeyMode `json:"multi_key_mode"`
}
LLMChannelInfo 多 Key 与轮询状态(仅 LLM)。
func (*LLMChannelInfo) Scan ¶
func (i *LLMChannelInfo) Scan(value interface{}) error
Scan 实现 sql.Scanner,供 GORM 从 JSON 列扫描到结构体。
type LLMModelMeta ¶
type LLMModelMeta struct {
Id uint `json:"id" gorm:"primaryKey"`
ModelName string `json:"model_name" gorm:"size:255;uniqueIndex;not null"`
Description string `json:"description,omitempty" gorm:"type:text"`
Tags string `json:"tags,omitempty" gorm:"size:255"`
Status int `json:"status" gorm:"default:1"` // 1 启用展示 0 停用
IconURL string `json:"icon_url,omitempty" gorm:"size:512"` // 可选覆盖;空则前端按 vendor / 模型名推断
Vendor string `json:"vendor,omitempty" gorm:"size:64;index"` // 如 openai、anthropic、deepseek,便于图标与筛选
SortOrder int `json:"sort_order" gorm:"default:0;index"`
ContextLength *int `json:"context_length,omitempty"`
MaxOutputTokens *int `json:"max_output_tokens,omitempty"`
// QuotaBillingMode:显式 times=按次;其它含空值=按 token 折算(与 new-api 默认按量一致)。
QuotaBillingMode string `json:"quota_billing_mode,omitempty" gorm:"size:16;default:''"`
QuotaModelRatio float64 `json:"quota_model_ratio" gorm:"default:1"` // 全局倍率
QuotaPromptRatio float64 `json:"quota_prompt_ratio" gorm:"default:1"` // 非缓存输入 token 权重
QuotaCompletionRatio float64 `json:"quota_completion_ratio" gorm:"default:1"` // 输出 token 权重
QuotaCacheReadRatio float64 `json:"quota_cache_read_ratio" gorm:"default:0.25"` // 缓存命中 prompt 相对非缓存的折算(对齐常见「缓存计费」思路)
CreatedTime int64 `json:"created_time" gorm:"bigint"`
UpdatedTime int64 `json:"updated_time" gorm:"bigint"`
}
LLMModelMeta 模型目录元数据(展示/说明;路由仍以 llm_channels + llm_abilities 为准)。
func (LLMModelMeta) TableName ¶
func (LLMModelMeta) TableName() string
type LLMUsage ¶
type LLMUsage struct {
ID string `json:"id" gorm:"primaryKey;type:varchar(64)"` // 雪花算法生成的ID
RequestID string `json:"request_id" gorm:"type:varchar(64);uniqueIndex;not null"` // 唯一请求ID(可与上游 id 对齐)
UserID string `json:"user_id" gorm:"type:varchar(64);index"`
Provider string `json:"provider" gorm:"type:varchar(50);not null;index"`
Model string `json:"model" gorm:"type:varchar(100);not null;index"`
BaseURL string `json:"base_url" gorm:"type:varchar(255)"` // API基础URL
RequestType string `json:"request_type" gorm:"type:varchar(20);not null"` // query, query_stream, rewrite, expand
InputTokens int `json:"input_tokens" gorm:"default:0"`
OutputTokens int `json:"output_tokens" gorm:"default:0"`
TotalTokens int `json:"total_tokens" gorm:"default:0"`
QuotaDelta int `json:"quota_delta" gorm:"default:0"` // 本次从凭证扣除的额度单位(倍率/按次/按 token 汇总)
LatencyMs int64 `json:"latency_ms" gorm:"default:0"` // 总延迟(毫秒)
TTFTMs int64 `json:"ttft_ms" gorm:"default:0"` // Time To First Token(毫秒)
TPS float64 `json:"tps" gorm:"default:0"` // Tokens Per Second
QueueTimeMs int64 `json:"queue_time_ms" gorm:"default:0"` // 排队时间(毫秒)
RequestContent string `json:"request_content" gorm:"type:text"` // 请求内容(JSON格式)
ResponseContent string `json:"response_content" gorm:"type:text"` // 响应内容(JSON格式)
UserAgent string `json:"user_agent" gorm:"type:varchar(500)"` // 用户代理
IPAddress string `json:"ip_address" gorm:"type:varchar(45)"` // 客户端IP地址
StatusCode int `json:"status_code" gorm:"default:200"` // HTTP响应码
Success bool `json:"success" gorm:"default:true"`
ErrorCode string `json:"error_code" gorm:"type:varchar(50)"`
ErrorMessage string `json:"error_message" gorm:"type:text"`
// ChannelID 实际完成请求的上游 llm_channels.id(轮询/重试后命中的渠道)。
ChannelID int `json:"channel_id" gorm:"index;default:0"`
ChannelAttempts LLMUsageChannelAttempts `json:"channel_attempts" gorm:"column:channel_attempts;type:json"`
RequestedAt time.Time `json:"requested_at" gorm:"not null;index"` // 请求开始时间
StartedAt time.Time `json:"started_at" gorm:"index"` // 实际处理开始时间
FirstTokenAt time.Time `json:"first_token_at" gorm:"index"` // 首个token时间
CompletedAt time.Time `json:"completed_at"` // 请求完成时间
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
}
LLMUsage LLM用量统计表
type LLMUsageChannelAttempt ¶
type LLMUsageChannelAttempt struct {
Order int `json:"order"` // 从 1 递增
ChannelID int `json:"channel_id"`
BaseURL string `json:"base_url,omitempty"`
Success bool `json:"success"`
StatusCode int `json:"status_code,omitempty"`
LatencyMs int64 `json:"latency_ms,omitempty"` // 该次上游往返耗时
TTFTMs int64 `json:"ttft_ms,omitempty"` // 非流式时常与 LatencyMs 同量级;流式场景可填首包
ErrorCode string `json:"error_code,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
}
LLMUsageChannelAttempt 多渠道路由/重试时单次走向(失败后再换渠道成功时形成数组)。
type LLMUsageChannelAttempts ¶
type LLMUsageChannelAttempts []LLMUsageChannelAttempt
LLMUsageChannelAttempts JSON 列类型。
func (*LLMUsageChannelAttempts) Scan ¶
func (a *LLMUsageChannelAttempts) Scan(value interface{}) error
type LLMUsageUserDaily ¶
type LLMUsageUserDaily struct {
ID uint `json:"id" gorm:"primaryKey"`
UserID string `json:"user_id" gorm:"size:64;uniqueIndex:ux_llm_usage_user_daily;not null;index"`
StatDate string `json:"stat_date" gorm:"size:10;uniqueIndex:ux_llm_usage_user_daily;not null"` // YYYY-MM-DD UTC
RequestCount int64 `json:"request_count" gorm:"default:0"`
SuccessCount int64 `json:"success_count" gorm:"default:0"`
TokenSum int64 `json:"token_sum" gorm:"default:0"`
QuotaSum int64 `json:"quota_sum" gorm:"default:0"`
}
LLMUsageUserDaily 用户 + UTC 日期维度的用量汇总(listener 增量 upsert;面板按区间 SUM,避免每次扫 llm_usage 全表)。
func (LLMUsageUserDaily) TableName ¶
func (LLMUsageUserDaily) TableName() string
type LLMUsageUserModelDaily ¶
type LLMUsageUserModelDaily struct {
ID uint `json:"id" gorm:"primaryKey"`
UserID string `json:"user_id" gorm:"size:64;uniqueIndex:ux_llm_usage_um_daily;not null;index"`
StatDate string `json:"stat_date" gorm:"size:10;uniqueIndex:ux_llm_usage_um_daily;not null"`
Model string `json:"model" gorm:"size:255;uniqueIndex:ux_llm_usage_um_daily;not null"`
RequestCount int64 `json:"request_count" gorm:"default:0"`
SuccessCount int64 `json:"success_count" gorm:"default:0"`
TokenSum int64 `json:"token_sum" gorm:"default:0"`
QuotaSum int64 `json:"quota_sum" gorm:"default:0"`
}
LLMUsageUserModelDaily 用户 + 日期 + 模型维度的汇总(用于面板模型榜等)。
func (LLMUsageUserModelDaily) TableName ¶
func (LLMUsageUserModelDaily) TableName() string
type LoginForm ¶
type LoginForm struct {
Email string `json:"email" comment:"Email address"`
Password string `json:"password,omitempty"`
Timezone string `json:"timezone,omitempty"`
Remember bool `json:"remember,omitempty"`
AuthToken string `json:"token,omitempty"`
TwoFactorCode string `json:"twoFactorCode,omitempty"` // 两步验证码
CaptchaID string `json:"captchaId,omitempty"` // 图形验证码ID
CaptchaCode string `json:"captchaCode,omitempty"` // 图形验证码
CaptchaType string `json:"captchaType,omitempty"` // 验证码类型: image/click
CaptchaData string `json:"captchaData,omitempty"` // 点击验证码坐标数据(JSON)
}
type LoginHistory ¶
type LoginHistory struct {
BaseModel
UserID uint `gorm:"index;not null" json:"userId"`
Email string `gorm:"size:128;index" json:"email"`
IPAddress string `gorm:"size:128;index" json:"ipAddress"`
Location string `gorm:"size:256" json:"location"`
Country string `gorm:"size:64" json:"country"`
City string `gorm:"size:128" json:"city"`
UserAgent string `gorm:"type:text" json:"userAgent"`
DeviceID string `gorm:"size:128;index" json:"deviceId"`
LoginType string `gorm:"size:32" json:"loginType"`
Success bool `gorm:"index" json:"success"`
FailureReason string `gorm:"size:256" json:"failureReason"`
IsSuspicious bool `gorm:"default:false;index" json:"isSuspicious"`
}
LoginHistory 登录历史记录表(用于异地登录检测)
func GetRecentLoginLocations ¶
GetRecentLoginLocations 获取最近的登录位置(用于异地登录检测)
func (LoginHistory) TableName ¶
func (LoginHistory) TableName() string
type MailTemplate ¶
type MailTemplate struct {
BaseModel
// Code 业务唯一键,用于代码里加载模版,如 welcome、verify_code、password_reset
Code string `json:"code" gorm:"uniqueIndex:idx_mail_tpl_code_locale;size:64;not null;comment:模版编码"`
// Name 后台展示用名称
Name string `json:"name" gorm:"size:128;not null;comment:模版名称"`
// HTMLBody HTML 正文模版
HTMLBody string `json:"htmlBody" gorm:"type:longtext;comment:HTML 正文"`
// TextBody 纯文本正文模版(由服务端根据 HTMLBody 去标签生成,可与 HTML 共用占位符)
TextBody string `json:"textBody,omitempty" gorm:"type:longtext;comment:纯文本正文"`
// Description 用途说明,供运营/开发查看
Description string `json:"description,omitempty" gorm:"size:512;comment:说明"`
// Variables JSON 数组字符串,描述可用占位符,如 ["Username","VerifyURL"]
Variables string `json:"variables,omitempty" gorm:"type:text;comment:占位符说明 JSON"`
// Locale 语言区域;空字符串表示默认模版,与 Code 组成联合唯一
Locale string `json:"locale,omitempty" gorm:"uniqueIndex:idx_mail_tpl_code_locale;size:32;default:'';comment:语言如 zh-CN"`
// Enabled 是否启用;禁用后发送逻辑应拒绝或回退到内置默认
Enabled bool `json:"enabled" gorm:"default:true;index;comment:是否启用"`
}
MailTemplate 是可持久化的邮件模版,供渲染主题/正文(占位符由业务层注入)。 通知渠道当前以邮件为主;预留 Locale 便于多语言模版行。
type MultiKeyMode ¶
type MultiKeyMode string
MultiKeyMode 多 Key 调度方式(仅 LLM 渠道使用)。
const ( MultiKeyModeRandom MultiKeyMode = "random" // 随机 MultiKeyModePolling MultiKeyMode = "polling" // 轮询 )
type NotificationChannel ¶
type NotificationChannel struct {
BaseModel
// Type 渠道大类:email、sms(预留 push、webhook 等可继续加常量)
Type string `json:"type" gorm:"size:32;not null;index:idx_notify_ch_type_sort,priority:1;comment:渠道类型"`
// Code 服务端生成的唯一业务键(列表展示,勿手填)
Code string `json:"code,omitempty" gorm:"size:64;index;comment:渠道编码"`
// Name 展示名称
Name string `json:"name" gorm:"size:128;not null;comment:显示名称"`
// SortOrder 同 Type 下越小越优先(故障转移/轮询顺序)
SortOrder int `json:"sortOrder" gorm:"not null;default:0;index:idx_notify_ch_type_sort,priority:2;comment:排序权重"`
// Enabled 是否参与发送
Enabled bool `json:"enabled" gorm:"not null;default:true;index;comment:是否启用"`
// ConfigJSON 渠道参数 JSON(email 时可为 MailConfig 字段子集 + provider 等)
ConfigJSON string `json:"configJson,omitempty" gorm:"type:text;comment:渠道配置 JSON"`
}
NotificationChannel 统一描述一种可配置通知出口(当前多为邮件 JSON 配置,后续 SMS 等同表扩展)。 ConfigJSON 建议与 pkg/notification.MailConfig / 未来 SmsConfig 结构对齐的 JSON 文本,便于反序列化。
func (NotificationChannel) TableName ¶
func (NotificationChannel) TableName() string
TableName GORM 表名
type PasskeyCredential ¶
type PasskeyCredential struct {
ID int `json:"id" gorm:"primaryKey"`
UserID int `json:"user_id" gorm:"uniqueIndex;not null"`
CredentialID string `json:"credential_id" gorm:"type:varchar(512);uniqueIndex;not null"` // base64 encoded
PublicKey string `json:"public_key" gorm:"type:text;not null"` // base64 encoded
AttestationType string `json:"attestation_type" gorm:"type:varchar(255)"`
AAGUID string `json:"aaguid" gorm:"type:varchar(512)"` // base64 encoded
SignCount uint32 `json:"sign_count" gorm:"default:0"`
CloneWarning bool `json:"clone_warning"`
UserPresent bool `json:"user_present"`
UserVerified bool `json:"user_verified"`
BackupEligible bool `json:"backup_eligible"`
BackupState bool `json:"backup_state"`
Transports string `json:"transports" gorm:"type:text"`
Attachment string `json:"attachment" gorm:"type:varchar(32)"`
LastUsedAt *time.Time `json:"last_used_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}
func GetPasskeyByCredentialID ¶
func GetPasskeyByCredentialID(db *gorm.DB, credentialID []byte) (*PasskeyCredential, error)
func GetPasskeyByUserID ¶
func GetPasskeyByUserID(db *gorm.DB, userID int) (*PasskeyCredential, error)
func NewPasskeyCredentialFromWebAuthn ¶
func NewPasskeyCredentialFromWebAuthn(userID int, credential *webauthn.Credential) *PasskeyCredential
func (*PasskeyCredential) ApplyValidatedCredential ¶
func (p *PasskeyCredential) ApplyValidatedCredential(credential *webauthn.Credential)
func (*PasskeyCredential) SetTransports ¶
func (p *PasskeyCredential) SetTransports(list []protocol.AuthenticatorTransport)
func (*PasskeyCredential) ToWebAuthnCredential ¶
func (p *PasskeyCredential) ToWebAuthnCredential() webauthn.Credential
func (*PasskeyCredential) TransportList ¶
func (p *PasskeyCredential) TransportList() []protocol.AuthenticatorTransport
type RegisterUserForm ¶
type RegisterUserForm struct {
Email string `json:"email" binding:"required"`
Password string `json:"password" binding:"required"`
DisplayName string `json:"displayName"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Locale string `json:"locale"`
Timezone string `json:"timezone"`
Source string `json:"source"`
CaptchaID string `json:"captchaId"`
CaptchaCode string `json:"captchaCode"`
CaptchaType string `json:"captchaType"`
CaptchaData string `json:"captchaData"`
MouseTrack string `json:"mouseTrack"`
FormFillTime int64 `json:"formFillTime"`
KeystrokePattern string `json:"keystrokePattern"`
}
type ResetPasswordDoneForm ¶
type ResetPasswordForm ¶
type ResetPasswordForm struct {
Email string `json:"email" binding:"required"`
}
type SendEmailVerifyEmail ¶
type SiteAnnouncement ¶
type SiteAnnouncement struct {
ID uint `json:"id" gorm:"primaryKey"`
Title string `json:"title" gorm:"size:255;not null"`
Body string `json:"body" gorm:"type:text"`
Pinned bool `json:"pinned" gorm:"default:false;index"`
Enabled bool `json:"enabled" gorm:"default:true;index"`
SortOrder int `json:"sort_order" gorm:"default:0;index"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
SiteAnnouncement 站点公告(前台展示 + 管理端维护)。
func (SiteAnnouncement) TableName ¶
func (SiteAnnouncement) TableName() string
type SpeechUsage ¶
type SpeechUsage struct {
ID string `json:"id" gorm:"primaryKey;type:varchar(64)"`
RequestID string `json:"request_id" gorm:"type:varchar(64);uniqueIndex;not null"`
CredentialID int `json:"credential_id" gorm:"index"`
UserID string `json:"user_id" gorm:"type:varchar(64);index"`
Kind string `json:"kind" gorm:"type:varchar(16);not null;index"`
Provider string `json:"provider" gorm:"type:varchar(64);index"`
ChannelID int `json:"channel_id" gorm:"index"`
Group string `json:"group" gorm:"type:varchar(128)"`
RequestType string `json:"request_type" gorm:"type:varchar(64);not null;index"`
RequestContent string `json:"request_content" gorm:"type:text"`
ResponseContent string `json:"response_content" gorm:"type:text"`
LatencyMs int64 `json:"latency_ms"`
StatusCode int `json:"status_code"`
Success bool `json:"success"`
ErrorMessage string `json:"error_message" gorm:"type:text"`
AudioInputBytes int64 `json:"audio_input_bytes"`
AudioOutputBytes int64 `json:"audio_output_bytes"`
TextInputChars int `json:"text_input_chars"`
QuotaDelta int `json:"quota_delta" gorm:"default:0"` // 本次从凭证扣除的额度单位(OpenAPI 语音计费)
UserAgent string `json:"user_agent" gorm:"type:varchar(500)"`
IPAddress string `json:"ip_address" gorm:"type:varchar(45)"`
RequestedAt time.Time `json:"requested_at" gorm:"not null;index"`
CompletedAt time.Time `json:"completed_at" gorm:"index"`
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
}
SpeechUsage 记录 OpenAPI 语音(ASR/TTS)单次调用,便于审计与统计;不落原始音频 base64。
func (SpeechUsage) TableName ¶
func (SpeechUsage) TableName() string
type TTSChannel ¶
type TTSChannel struct {
BaseModel
Provider string `json:"provider" gorm:"size:64;not null;index;comment:厂商如 aliyun_cosyvoice、azure、edge"`
Name string `json:"name" gorm:"size:128;not null;comment:展示名称"`
Enabled bool `json:"enabled" gorm:"not null;default:true;index;comment:是否启用"`
Group string `json:"group" gorm:"size:64;default:'';index;comment:路由分组"`
SortOrder int `json:"sortOrder" gorm:"not null;default:0;index;comment:同组内优先级"`
ConfigJSON string `json:"configJson,omitempty" gorm:"type:text;comment:厂商相关 JSON 配置"`
}
TTSChannel 语音合成上游渠道;厂商、音色、鉴权等差异放在 ConfigJSON(与 Provider 联合解析)。
type TwoFA ¶
type TwoFA struct {
Id int `json:"id" gorm:"primaryKey"`
UserId int `json:"user_id" gorm:"unique;not null;index"`
Secret string `json:"-" gorm:"type:varchar(255);not null"` // TOTP密钥,不返回给前端
IsEnabled bool `json:"is_enabled"`
FailedAttempts int `json:"failed_attempts" gorm:"default:0"`
LockedUntil *time.Time `json:"locked_until,omitempty"`
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}
TwoFA 用户2FA设置表
func GetTwoFAByUserId ¶
GetTwoFAByUserId 根据用户ID获取2FA设置
func (*TwoFA) IncrementFailedAttempts ¶
IncrementFailedAttempts 增加失败尝试次数
func (*TwoFA) ResetFailedAttempts ¶
ResetFailedAttempts 重置失败尝试次数
func (*TwoFA) ValidateBackupCodeAndUpdateUsage ¶
ValidateBackupCodeAndUpdateUsage 验证备用码并更新使用记录
type TwoFABackupCode ¶
type TwoFABackupCode struct {
Id int `json:"id" gorm:"primaryKey"`
UserId int `json:"user_id" gorm:"not null;index"`
CodeHash string `json:"-" gorm:"type:varchar(255);not null"` // 备用码哈希
IsUsed bool `json:"is_used"`
UsedAt *time.Time `json:"used_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}
TwoFABackupCode 备用码使用记录表
type UpdateUserRequest ¶
type UpdateUserRequest struct {
Email string `form:"email" json:"email"`
Phone string `form:"phone" json:"phone"`
FirstName string `form:"firstName" json:"firstName"`
LastName string `form:"lastName" json:"lastName"`
DisplayName string `form:"displayName" json:"displayName"`
Locale string `form:"locale" json:"locale"`
Timezone string `form:"timezone" json:"timezone"`
Gender string `form:"gender" json:"gender"`
City string `form:"city" json:"city"`
Region string `form:"region" json:"region"`
Extra string `form:"extra" json:"extra"`
Avatar string `form:"avatar" json:"avatar"`
}
type User ¶
type User struct {
BaseModel
Email string `json:"email" gorm:"size:128;uniqueIndex"`
WechatOpenID string `json:"wechatOpenId,omitempty" gorm:"size:128;index"`
WechatUnionID string `json:"wechatUnionId,omitempty" gorm:"size:128;index"`
GithubID string `json:"githubId,omitempty" gorm:"size:64;index"`
GithubLogin string `json:"githubLogin,omitempty" gorm:"size:128;index"`
Password string `json:"-" gorm:"size:128"`
Phone string `json:"phone,omitempty" gorm:"size:64;index"`
FirstName string `json:"firstName,omitempty" gorm:"size:128"`
LastName string `json:"lastName,omitempty" gorm:"size:128"`
DisplayName string `json:"displayName,omitempty" gorm:"size:128"`
Status string `json:"status" gorm:"size:32;index;default:'active';comment:Account status"`
LastLogin *time.Time `json:"lastLogin,omitempty"`
LastLoginIP string `json:"-" gorm:"size:128"`
Source string `json:"source" gorm:"size:64;index"`
Locale string `json:"locale,omitempty" gorm:"size:20"`
Timezone string `json:"timezone,omitempty" gorm:"size:200"`
AuthToken string `json:"token,omitempty" gorm:"-"`
Avatar string `json:"avatar,omitempty"`
Gender string `json:"gender,omitempty"`
City string `json:"city,omitempty"`
Region string `json:"region,omitempty"`
EmailNotifications bool `json:"emailNotifications"` // 邮件通知
EmailVerified bool `json:"emailVerified" gorm:"default:false"` // 邮箱已验证
PhoneVerified bool `json:"phoneVerified" gorm:"default:false"` // 手机已验证
TwoFactorEnabled bool `json:"twoFactorEnabled" gorm:"default:false"` // 双因素认证
TwoFactorSecret string `json:"-" gorm:"size:128"` // 双因素认证密钥
EmailVerifyToken string `json:"-" gorm:"size:128"` // 邮箱验证令牌
PhoneVerifyToken string `json:"-" gorm:"size:128"` // 手机验证令牌
PasswordResetToken string `json:"-" gorm:"size:128"` // 密码重置令牌
PasswordResetExpires *time.Time `json:"-"` // 密码重置过期时间
EmailVerifyExpires *time.Time `json:"-"` // 邮箱验证过期时间
LoginCount int `json:"loginCount" gorm:"default:0"` // 登录次数
RemainQuota int `json:"remainQuota" gorm:"default:0"` // 用户级剩余额度(与 new-api 用户配额概念对齐;实际扣减仍以凭证为主时可作展示/预留)
UsedQuota int `json:"usedQuota" gorm:"default:0"` // 用户级已用额度
UnlimitedQuota bool `json:"unlimitedQuota" gorm:"default:false"` // 用户级无限额度标记
LastPasswordChange *time.Time `json:"lastPasswordChange,omitempty"` // 最后密码修改时间
ProfileComplete int `json:"profileComplete" gorm:"default:0"` // 资料完整度百分比
Role string `json:"role,omitempty" gorm:"size:50;default:'user'"` // 用户角色
AccountDeletionRequestedAt *time.Time `json:"accountDeletionRequestedAt,omitempty"`
AccountDeletionEffectiveAt *time.Time `json:"accountDeletionEffectiveAt,omitempty" gorm:"index"`
}
func CreateUserByEmail ¶
func CreateUserByEmailWithMeta ¶
func CreateUserByEmailWithMeta(db *gorm.DB, username, display, email, password, source, status string) (*User, error)
CreateUserByEmailWithMeta 创建用户并写入来源与账号状态。
func CreateUserWithMeta ¶
CreateUserWithMeta 使用邮箱+密码创建用户(如网页注册),可指定来源与状态。
func CurrentUser ¶
CurrentUser 解析顺序:① Gin 已缓存的 User ② session 中的 user id ③ Header(默认 Authorization)或 ?token= 中的 access JWT → jwtauth.ParseAccessToken → DB 加载并写入缓存。
func ListUsersDueForAccountDeletion ¶
ListUsersDueForAccountDeletion 冷静期已结束、待执行永久注销的用户。
func VerifyEmailLoginCode ¶
VerifyEmailLoginCode 校验邮箱与邮件中的数字验证码,成功后标记邮箱已验证并清除令牌。
func VerifyPasswordResetToken ¶
VerifyPasswordResetToken 验证密码重置令牌
type UserBasicInfoUpdate ¶
type UserDevice ¶
type UserDevice struct {
BaseModel
UserID uint `gorm:"index;not null" json:"userId"`
DeviceID string `gorm:"size:128;index;not null" json:"deviceId"`
DeviceName string `gorm:"size:128" json:"deviceName"`
DeviceType string `gorm:"size:64" json:"deviceType"`
OS string `gorm:"size:64" json:"os"`
Browser string `gorm:"size:64" json:"browser"`
UserAgent string `gorm:"type:text" json:"userAgent"`
IPAddress string `gorm:"size:128;index" json:"ipAddress"`
Location string `gorm:"size:256" json:"location"`
IsTrusted bool `gorm:"default:false" json:"isTrusted"`
IsActive bool `gorm:"default:true" json:"isActive"`
LastUsedAt time.Time `gorm:"index" json:"lastUsedAt"`
}
UserDevice 用户设备表
func CreateOrUpdateUserDevice ¶
func CreateOrUpdateUserDevice(db *gorm.DB, userID uint, deviceID, deviceName, deviceType, os, browser, userAgent, ipAddress, location string) (*UserDevice, error)
CreateOrUpdateUserDevice 创建或更新用户设备
func GetUserDevice ¶
GetUserDevice 获取用户的特定设备
func GetUserLoginDevices ¶
func GetUserLoginDevices(db *gorm.DB, userID uint) ([]UserDevice, error)
GetUserLoginDevices 获取用户的登录设备列表
func (UserDevice) TableName ¶
func (UserDevice) TableName() string