model

package
v0.10.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 3, 2026 License: AGPL-3.0 Imports: 37 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LogTypeUnknown = 0
	LogTypeTopup   = 1
	LogTypeConsume = 2
	LogTypeManage  = 3
	LogTypeSystem  = 4
	LogTypeError   = 5
	LogTypeRefund  = 6
)

don't use iota, avoid change log type value

View Source
const (
	NameRuleExact = iota
	NameRulePrefix
	NameRuleContains
	NameRuleSuffix
)
View Source
const (
	TaskStatusNotStart   TaskStatus = "NOT_START"
	TaskStatusSubmitted             = "SUBMITTED"
	TaskStatusQueued                = "QUEUED"
	TaskStatusInProgress            = "IN_PROGRESS"
	TaskStatusFailure               = "FAILURE"
	TaskStatusSuccess               = "SUCCESS"
	TaskStatusUnknown               = "UNKNOWN"
)
View Source
const (
	BatchUpdateTypeUserQuota = iota
	BatchUpdateTypeTokenQuota
	BatchUpdateTypeUsedQuota
	BatchUpdateTypeChannelUsedQuota
	BatchUpdateTypeRequestCount
	BatchUpdateTypeCount // if you add a new type, you need to add a new map and a new lock
)

Variables

View Source
var (
	ErrPasskeyNotFound         = errors.New("passkey credential not found")
	ErrFriendlyPasskeyNotFound = errors.New("Passkey 验证失败,请重试或联系管理员")
)
View Source
var CacheQuotaData = make(map[string]*QuotaData)
View Source
var CacheQuotaDataLock = sync.Mutex{}
View Source
var DB *gorm.DB
View Source
var ErrTwoFANotEnabled = errors.New("用户未启用2FA")
View Source
var LOG_DB *gorm.DB

Functions

func BatchDeleteChannels

func BatchDeleteChannels(ids []int) error

func BatchDeleteTokens

func BatchDeleteTokens(ids []int, userId int) (int, error)

BatchDeleteTokens 删除指定用户的一组令牌,返回成功删除数量

func BatchInsertChannels

func BatchInsertChannels(channels []Channel) error

func BatchSetChannelTag

func BatchSetChannelTag(ids []int, tag *string) error

func CacheUpdateChannel

func CacheUpdateChannel(channel *Channel)

func CacheUpdateChannelStatus

func CacheUpdateChannelStatus(id int, status int)

func CheckSetup

func CheckSetup()

func CheckUserExistOrDeleted

func CheckUserExistOrDeleted(username string, email string) (bool, error)

CheckUserExistOrDeleted check if user exist or deleted, if not exist, return false, nil, if deleted or exist, return true, nil

func CleanupChannelPollingLocks

func CleanupChannelPollingLocks()

CleanupChannelPollingLocks removes locks for channels that no longer exist This is optional and can be called periodically to prevent memory leaks

func CloseDB

func CloseDB() error

func CountAllChannels

func CountAllChannels() (int64, error)

CountAllChannels returns total channels in DB

func CountAllTags

func CountAllTags() (int64, error)

CountAllTags returns number of non-empty distinct tags

func CountAllTasks

func CountAllTasks(queryParams TaskQueryParams) int64

CountAllTasks returns total midjourney tasks for admin query

func CountAllUserTask

func CountAllUserTask(userId int, queryParams TaskQueryParams) int64

CountAllUserTask returns total midjourney tasks for user

func CountChannelsByType

func CountChannelsByType(channelType int) (int64, error)

Count channels of specific type

func CountChannelsGroupByType

func CountChannelsGroupByType() (map[int64]int64, error)

Return map[type]count for all channels

func CountUserTokens

func CountUserTokens(userId int) (int64, error)

CountUserTokens returns total number of tokens for the given user, used for pagination

func CreateBackupCodes

func CreateBackupCodes(userId int, codes []string) error

CreateBackupCodes 创建备用码

func DecreaseTokenQuota

func DecreaseTokenQuota(id int, key string, quota int) (err error)

func DecreaseUserQuota

func DecreaseUserQuota(id int, quota int) (err error)

func DeleteChannelByStatus

func DeleteChannelByStatus(status int64) (int64, error)

func DeleteDisabledChannel

func DeleteDisabledChannel() (int64, error)

func DeleteInvalidRedemptions

func DeleteInvalidRedemptions() (int64, error)

func DeleteOldLog

func DeleteOldLog(ctx context.Context, targetTimestamp int64, limit int) (int64, error)

func DeletePasskeyByUserID

func DeletePasskeyByUserID(userID int) error

func DeletePrefillGroupByID

func DeletePrefillGroupByID(id int) error

DeleteByID 根据 ID 删除组

func DeleteRedemptionById

func DeleteRedemptionById(id int) (err error)

func DeleteTokenById

func DeleteTokenById(id int, userId int) (err error)

func DeleteUserById

func DeleteUserById(id int) (err error)

func DeltaUpdateUserQuota

func DeltaUpdateUserQuota(id int, delta int) (err error)

func DisableChannelByTag

func DisableChannelByTag(tag string) error

func DisableModelLimits

func DisableModelLimits(tokenId int) error

func DisableTwoFA

func DisableTwoFA(userId int) error

DisableTwoFA 禁用用户的2FA

func EditChannelByTag

func EditChannelByTag(tag string, newTag *string, modelMapping *string, models *string, group *string, priority *int64, weight *uint, paramOverride *string, headerOverride *string) error

func EnableChannelByTag

func EnableChannelByTag(tag string) error

func FixAbility

func FixAbility() (int, int, error)

func GetBoundChannelsByModelsMap

func GetBoundChannelsByModelsMap(modelNames []string) (map[string][]BoundChannel, error)

func GetChannelPollingLock

func GetChannelPollingLock(channelId int) *sync.Mutex

GetChannelPollingLock returns or creates a mutex for the given channel ID

func GetEnabledModels

func GetEnabledModels() []string

func GetGroupEnabledModels

func GetGroupEnabledModels(group string) []string

func GetMaxUserId

func GetMaxUserId() int

func GetMissingModels

func GetMissingModels() ([]string, error)

GetMissingModels returns model names that are referenced in the system

func GetModelEnableGroups

func GetModelEnableGroups(modelName string) []string

func GetModelQuotaTypes

func GetModelQuotaTypes(modelName string) []int

GetModelQuotaTypes 返回指定模型的计费类型集合(来自缓存)

func GetModelSupportEndpointTypes

func GetModelSupportEndpointTypes(model string) []constant.EndpointType

func GetPaginatedTags

func GetPaginatedTags(offset int, limit int) ([]*string, error)

func GetSupportedEndpointMap

func GetSupportedEndpointMap() map[string]common.EndpointInfo

GetSupportedEndpointMap 返回全局端点到路径的映射

func GetTwoFAStats

func GetTwoFAStats() (map[string]interface{}, error)

GetTwoFAStats 获取2FA统计信息(管理员使用)

func GetUnusedBackupCodeCount

func GetUnusedBackupCodeCount(userId int) (int, error)

GetUnusedBackupCodeCount 获取未使用的备用码数量

func GetUserCheckinStats

func GetUserCheckinStats(userId int, month string) (map[string]interface{}, error)

GetUserCheckinStats 获取用户签到统计信息

func GetUserEmail

func GetUserEmail(id int) (email string, err error)

func GetUserGroup

func GetUserGroup(id int, fromDB bool) (group string, err error)

GetUserGroup gets group from Redis first, falls back to DB if needed

func GetUserIdByAffCode

func GetUserIdByAffCode(affCode string) (int, error)

func GetUserQuota

func GetUserQuota(id int, fromDB bool) (quota int, err error)

GetUserQuota gets quota from Redis first, falls back to DB if needed

func GetUserSetting

func GetUserSetting(id int, fromDB bool) (settingMap dto.UserSetting, err error)

GetUserSetting gets setting from Redis first, falls back to DB if needed

func GetUserUsedQuota

func GetUserUsedQuota(id int) (quota int, err error)

func GetUsernameById

func GetUsernameById(id int, fromDB bool) (username string, err error)

GetUsernameById gets username from Redis first, falls back to DB if needed

func GetVendorModelCounts

func GetVendorModelCounts() (map[int64]int64, error)

func HardDeleteUserById

func HardDeleteUserById(id int) error

func HasCheckedInToday

func HasCheckedInToday(userId int) (bool, error)

HasCheckedInToday 检查用户今天是否已签到

func IncreaseTokenQuota

func IncreaseTokenQuota(id int, key string, quota int) (err error)

func IncreaseUserQuota

func IncreaseUserQuota(id int, quota int, db bool) (err error)

func InitBatchUpdater

func InitBatchUpdater()

func InitChannelCache

func InitChannelCache()

func InitDB

func InitDB() (err error)

func InitLogDB

func InitLogDB() (err error)

func InitOptionMap

func InitOptionMap()

func IsAdmin

func IsAdmin(userId int) bool

func IsChannelEnabledForAnyGroupModel

func IsChannelEnabledForAnyGroupModel(groups []string, modelName string, channelID int) bool

func IsChannelEnabledForGroupModel

func IsChannelEnabledForGroupModel(group string, modelName string, channelID int) bool

func IsDiscordIdAlreadyTaken

func IsDiscordIdAlreadyTaken(discordId string) bool

func IsEmailAlreadyTaken

func IsEmailAlreadyTaken(email string) bool

func IsGitHubIdAlreadyTaken

func IsGitHubIdAlreadyTaken(githubId string) bool

func IsLinuxDOIdAlreadyTaken

func IsLinuxDOIdAlreadyTaken(linuxDOId string) bool

func IsModelNameDuplicated

func IsModelNameDuplicated(id int, name string) (bool, error)

func IsOidcIdAlreadyTaken

func IsOidcIdAlreadyTaken(oidcId string) bool

func IsPrefillGroupNameDuplicated

func IsPrefillGroupNameDuplicated(id int, name string) (bool, error)

IsPrefillGroupNameDuplicated 检查组名称是否重复(排除自身 ID)

func IsTelegramIdAlreadyTaken

func IsTelegramIdAlreadyTaken(telegramId string) bool

func IsTwoFAEnabled

func IsTwoFAEnabled(userId int) bool

IsTwoFAEnabled 检查用户是否启用了2FA

func IsVendorNameDuplicated

func IsVendorNameDuplicated(id int, name string) (bool, error)

IsVendorNameDuplicated 检查供应商名称是否重复(排除自身 ID)

func IsWeChatIdAlreadyTaken

func IsWeChatIdAlreadyTaken(wechatId string) bool

func LogQuotaData

func LogQuotaData(userId int, username string, modelName string, quota int, createdAt int64, tokenUsed int)

func ManualCompleteTopUp

func ManualCompleteTopUp(tradeNo string) error

ManualCompleteTopUp 管理员手动完成订单并给用户充值

func MjBulkUpdate

func MjBulkUpdate(mjIds []string, params map[string]any) error

func MjBulkUpdateByTaskIds

func MjBulkUpdateByTaskIds(taskIDs []int, params map[string]any) error

func PingDB

func PingDB() error

func Recharge

func Recharge(referenceId string, customerId string) (err error)

func RechargeCreem

func RechargeCreem(referenceId string, customerEmail string, customerName string) (err error)

func RecordConsumeLog

func RecordConsumeLog(c *gin.Context, userId int, params RecordConsumeLogParams)

func RecordErrorLog

func RecordErrorLog(c *gin.Context, userId int, channelId int, modelName string, tokenName string, content string, tokenId int, useTimeSeconds int,
	isStream bool, group string, other map[string]interface{})

func RecordExist

func RecordExist(err error) (bool, error)

func RecordLog

func RecordLog(userId int, logType int, content string)

func Redeem

func Redeem(key string, userId int) (quota int, err error)

func RefreshPricing

func RefreshPricing()

RefreshPricing 强制立即重新计算与定价相关的缓存。 该方法用于需要最新数据的内部管理 API, 因此会绕过默认的 1 分钟延迟刷新。

func ResetUserPasswordByEmail

func ResetUserPasswordByEmail(email string, password string) error

func RootUserExists

func RootUserExists() bool

func SaveQuotaDataCache

func SaveQuotaDataCache()

func SearchTags

func SearchTags(keyword string, group string, model string, idSort bool) ([]*string, error)

func SumUsedToken

func SumUsedToken(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string) (token int)

func SyncChannelCache

func SyncChannelCache(frequency int)

func SyncOptions

func SyncOptions(frequency int)

func TaskBulkUpdate

func TaskBulkUpdate(TaskIds []string, params map[string]any) error

func TaskBulkUpdateByID

func TaskBulkUpdateByID(ids []int64, params map[string]any) error

func TaskBulkUpdateByTaskIds

func TaskBulkUpdateByTaskIds(taskIDs []int64, params map[string]any) error

func TaskCountAllTasks

func TaskCountAllTasks(queryParams SyncTaskQueryParams) int64

TaskCountAllTasks returns total tasks that match the given query params (admin usage)

func TaskCountAllUserTask

func TaskCountAllUserTask(userId int, queryParams SyncTaskQueryParams) int64

TaskCountAllUserTask returns total tasks for given user

func TaskUpdateProgress

func TaskUpdateProgress(id int64, progress string) error

func UpdateAbilityByTag

func UpdateAbilityByTag(tag string, newTag *string, priority *int64, weight *uint) error

func UpdateAbilityStatus

func UpdateAbilityStatus(channelId int, status bool) error

func UpdateAbilityStatusByTag

func UpdateAbilityStatusByTag(tag string, status bool) error

func UpdateChannelStatus

func UpdateChannelStatus(channelId int, usingKey string, status int, reason string) bool

func UpdateChannelUsedQuota

func UpdateChannelUsedQuota(id int, quota int)

func UpdateOption

func UpdateOption(key string, value string) error

func UpdateProgress

func UpdateProgress(id int, progress string) error

func UpdateQuotaData

func UpdateQuotaData()

func UpdateUserUsedQuotaAndRequestCount

func UpdateUserUsedQuotaAndRequestCount(id int, quota int)

func UpsertPasskeyCredential

func UpsertPasskeyCredential(credential *PasskeyCredential) error

func ValidateBackupCode

func ValidateBackupCode(userId int, code string) (bool, error)

ValidateBackupCode 验证并使用备用码

Types

type Ability

type Ability struct {
	Group     string  `json:"group" gorm:"type:varchar(64);primaryKey;autoIncrement:false"`
	Model     string  `json:"model" gorm:"type:varchar(255);primaryKey;autoIncrement:false"`
	ChannelId int     `json:"channel_id" gorm:"primaryKey;autoIncrement:false;index"`
	Enabled   bool    `json:"enabled"`
	Priority  *int64  `json:"priority" gorm:"bigint;default:0;index"`
	Weight    uint    `json:"weight" gorm:"default:0;index"`
	Tag       *string `json:"tag" gorm:"index"`
}

func GetAllEnableAbilities

func GetAllEnableAbilities() []Ability

type AbilityWithChannel

type AbilityWithChannel struct {
	Ability
	ChannelType int `json:"channel_type"`
}

func GetAllEnableAbilityWithChannels

func GetAllEnableAbilityWithChannels() ([]AbilityWithChannel, error)

type BoundChannel

type BoundChannel struct {
	Name string `json:"name"`
	Type int    `json:"type"`
}

type Channel

type Channel struct {
	Id                 int     `json:"id"`
	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:''"`
	Other              string  `json:"other"`
	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"`
	//MaxInputTokens     *int    `json:"max_input_tokens" gorm:"default:0"`
	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"`
	OtherInfo         string  `json:"other_info"`
	Tag               *string `json:"tag" gorm:"index"`
	Setting           *string `json:"setting" gorm:"type:text"` // 渠道额外设置
	ParamOverride     *string `json:"param_override" gorm:"type:text"`
	HeaderOverride    *string `json:"header_override" gorm:"type:text"`
	Remark            *string `json:"remark" gorm:"type:varchar(255)" validate:"max=255"`
	// add after v0.8.5
	ChannelInfo ChannelInfo `json:"channel_info" gorm:"type:json"`

	OtherSettings string `json:"settings" gorm:"column:settings"` // 其他设置,存储azure版本等不需要检索的信息,详见dto.ChannelOtherSettings

	// cache info
	Keys []string `json:"-" gorm:"-"`
}

func CacheGetChannel

func CacheGetChannel(id int) (*Channel, error)

func GetAllChannels

func GetAllChannels(startIdx int, num int, selectAll bool, idSort bool) ([]*Channel, error)

func GetChannel

func GetChannel(group string, model string, retry int) (*Channel, error)

func GetChannelById

func GetChannelById(id int, selectAll bool) (*Channel, error)

func GetChannelsByIds

func GetChannelsByIds(ids []int) ([]*Channel, error)

func GetChannelsByTag

func GetChannelsByTag(tag string, idSort bool, selectAll bool) ([]*Channel, error)

func GetChannelsByType

func GetChannelsByType(startIdx int, num int, idSort bool, channelType int) ([]*Channel, error)

Get channels of specified type with pagination

func GetRandomSatisfiedChannel

func GetRandomSatisfiedChannel(group string, model string, retry int) (*Channel, error)

func SearchChannels

func SearchChannels(keyword string, group string, model string, idSort bool) ([]*Channel, error)

func (*Channel) AddAbilities

func (channel *Channel) AddAbilities(tx *gorm.DB) error

func (*Channel) Delete

func (channel *Channel) Delete() error

func (*Channel) DeleteAbilities

func (channel *Channel) DeleteAbilities() error

func (*Channel) GetAutoBan

func (channel *Channel) GetAutoBan() bool

func (*Channel) GetBaseURL

func (channel *Channel) GetBaseURL() string

func (*Channel) GetGroups

func (channel *Channel) GetGroups() []string

func (*Channel) GetHeaderOverride

func (channel *Channel) GetHeaderOverride() map[string]interface{}

func (*Channel) GetKeys

func (channel *Channel) GetKeys() []string

func (*Channel) GetModelMapping

func (channel *Channel) GetModelMapping() string

func (*Channel) GetModels

func (channel *Channel) GetModels() []string

func (*Channel) GetNextEnabledKey

func (channel *Channel) GetNextEnabledKey() (string, int, *types.NewAPIError)

func (*Channel) GetOtherInfo

func (channel *Channel) GetOtherInfo() map[string]interface{}

func (*Channel) GetOtherSettings

func (channel *Channel) GetOtherSettings() dto.ChannelOtherSettings

func (*Channel) GetParamOverride

func (channel *Channel) GetParamOverride() map[string]interface{}

func (*Channel) GetPriority

func (channel *Channel) GetPriority() int64

func (*Channel) GetSetting

func (channel *Channel) GetSetting() dto.ChannelSettings

func (*Channel) GetStatusCodeMapping

func (channel *Channel) GetStatusCodeMapping() string

func (*Channel) GetTag

func (channel *Channel) GetTag() string

func (*Channel) GetWeight

func (channel *Channel) GetWeight() int

func (*Channel) Insert

func (channel *Channel) Insert() error

func (*Channel) Save

func (channel *Channel) Save() error

func (*Channel) SaveChannelInfo

func (channel *Channel) SaveChannelInfo() error

func (*Channel) SaveWithoutKey

func (channel *Channel) SaveWithoutKey() error

func (*Channel) SetOtherInfo

func (channel *Channel) SetOtherInfo(otherInfo map[string]interface{})

func (*Channel) SetOtherSettings

func (channel *Channel) SetOtherSettings(setting dto.ChannelOtherSettings)

func (*Channel) SetSetting

func (channel *Channel) SetSetting(setting dto.ChannelSettings)

func (*Channel) SetTag

func (channel *Channel) SetTag(tag string)

func (*Channel) Update

func (channel *Channel) Update() error

func (*Channel) UpdateAbilities

func (channel *Channel) UpdateAbilities(tx *gorm.DB) error

UpdateAbilities updates abilities of this channel. Make sure the channel is completed before calling this function.

func (*Channel) UpdateBalance

func (channel *Channel) UpdateBalance(balance float64)

func (*Channel) UpdateResponseTime

func (channel *Channel) UpdateResponseTime(responseTime int64)

func (*Channel) ValidateSettings

func (channel *Channel) ValidateSettings() error

type ChannelInfo

type ChannelInfo struct {
	IsMultiKey             bool                  `json:"is_multi_key"`                        // 是否多Key模式
	MultiKeySize           int                   `json:"multi_key_size"`                      // 多Key模式下的Key数量
	MultiKeyStatusList     map[int]int           `json:"multi_key_status_list"`               // key状态列表,key index -> status
	MultiKeyDisabledReason map[int]string        `json:"multi_key_disabled_reason,omitempty"` // key禁用原因列表,key index -> reason
	MultiKeyDisabledTime   map[int]int64         `json:"multi_key_disabled_time,omitempty"`   // key禁用时间列表,key index -> time
	MultiKeyPollingIndex   int                   `json:"multi_key_polling_index"`             // 多Key模式下轮询的key索引
	MultiKeyMode           constant.MultiKeyMode `json:"multi_key_mode"`
}

func CacheGetChannelInfo

func CacheGetChannelInfo(id int) (*ChannelInfo, error)

func (*ChannelInfo) Scan

func (c *ChannelInfo) Scan(value interface{}) error

Scan implements sql.Scanner interface

func (ChannelInfo) Value

func (c ChannelInfo) Value() (driver.Value, error)

Value implements driver.Valuer interface

type Checkin

type Checkin struct {
	Id           int    `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId       int    `json:"user_id" gorm:"not null;uniqueIndex:idx_user_checkin_date"`
	CheckinDate  string `json:"checkin_date" gorm:"type:varchar(10);not null;uniqueIndex:idx_user_checkin_date"` // 格式: YYYY-MM-DD
	QuotaAwarded int    `json:"quota_awarded" gorm:"not null"`
	CreatedAt    int64  `json:"created_at" gorm:"bigint"`
}

Checkin 签到记录

func GetUserCheckinRecords

func GetUserCheckinRecords(userId int, startDate, endDate string) ([]Checkin, error)

GetUserCheckinRecords 获取用户在指定日期范围内的签到记录

func UserCheckin

func UserCheckin(userId int) (*Checkin, error)

UserCheckin 执行用户签到 MySQL 和 PostgreSQL 使用事务保证原子性 SQLite 不支持嵌套事务,使用顺序操作 + 手动回滚

func (Checkin) TableName

func (Checkin) TableName() string

type CheckinRecord

type CheckinRecord struct {
	CheckinDate  string `json:"checkin_date"`
	QuotaAwarded int    `json:"quota_awarded"`
}

CheckinRecord 用于API返回的签到记录(不包含敏感字段)

type JSONValue

type JSONValue json.RawMessage

JSONValue 基于 json.RawMessage 实现,支持从数据库的 []byte 和 string 两种类型读取

func (JSONValue) MarshalJSON

func (j JSONValue) MarshalJSON() ([]byte, error)

MarshalJSON 确保在对外编码时与 json.RawMessage 行为一致

func (*JSONValue) Scan

func (j *JSONValue) Scan(value interface{}) error

Scan 实现 sql.Scanner 接口,兼容不同驱动返回的类型

func (*JSONValue) UnmarshalJSON

func (j *JSONValue) UnmarshalJSON(data []byte) error

UnmarshalJSON 确保在对外解码时与 json.RawMessage 行为一致

func (JSONValue) Value

func (j JSONValue) Value() (driver.Value, error)

Value 实现 driver.Valuer 接口,用于数据库写入

type Log

type Log struct {
	Id               int    `json:"id" gorm:"index:idx_created_at_id,priority:1"`
	UserId           int    `json:"user_id" gorm:"index"`
	CreatedAt        int64  `json:"created_at" gorm:"bigint;index:idx_created_at_id,priority:2;index:idx_created_at_type"`
	Type             int    `json:"type" gorm:"index:idx_created_at_type"`
	Content          string `json:"content"`
	Username         string `json:"username" gorm:"index;index:index_username_model_name,priority:2;default:''"`
	TokenName        string `json:"token_name" gorm:"index;default:''"`
	ModelName        string `json:"model_name" gorm:"index;index:index_username_model_name,priority:1;default:''"`
	Quota            int    `json:"quota" gorm:"default:0"`
	PromptTokens     int    `json:"prompt_tokens" gorm:"default:0"`
	CompletionTokens int    `json:"completion_tokens" gorm:"default:0"`
	UseTime          int    `json:"use_time" gorm:"default:0"`
	IsStream         bool   `json:"is_stream"`
	ChannelId        int    `json:"channel" gorm:"index"`
	ChannelName      string `json:"channel_name" gorm:"->"`
	TokenId          int    `json:"token_id" gorm:"default:0;index"`
	Group            string `json:"group" gorm:"index"`
	Ip               string `json:"ip" gorm:"index;default:''"`
	Other            string `json:"other"`
}

func GetAllLogs

func GetAllLogs(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, startIdx int, num int, channel int, group string) (logs []*Log, total int64, err error)

func GetLogByKey

func GetLogByKey(key string) (logs []*Log, err error)

func GetUserLogs

func GetUserLogs(userId int, logType int, startTimestamp int64, endTimestamp int64, modelName string, tokenName string, startIdx int, num int, group string) (logs []*Log, total int64, err error)

func SearchAllLogs

func SearchAllLogs(keyword string) (logs []*Log, err error)

func SearchUserLogs

func SearchUserLogs(userId int, keyword string) (logs []*Log, err error)

type Midjourney

type Midjourney struct {
	Id          int    `json:"id"`
	Code        int    `json:"code"`
	UserId      int    `json:"user_id" gorm:"index"`
	Action      string `json:"action" gorm:"type:varchar(40);index"`
	MjId        string `json:"mj_id" gorm:"index"`
	Prompt      string `json:"prompt"`
	PromptEn    string `json:"prompt_en"`
	Description string `json:"description"`
	State       string `json:"state"`
	SubmitTime  int64  `json:"submit_time" gorm:"index"`
	StartTime   int64  `json:"start_time" gorm:"index"`
	FinishTime  int64  `json:"finish_time" gorm:"index"`
	ImageUrl    string `json:"image_url"`
	VideoUrl    string `json:"video_url"`
	VideoUrls   string `json:"video_urls"`
	Status      string `json:"status" gorm:"type:varchar(20);index"`
	Progress    string `json:"progress" gorm:"type:varchar(30);index"`
	FailReason  string `json:"fail_reason"`
	ChannelId   int    `json:"channel_id"`
	Quota       int    `json:"quota"`
	Buttons     string `json:"buttons"`
	Properties  string `json:"properties"`
}

func GetAllTasks

func GetAllTasks(startIdx int, num int, queryParams TaskQueryParams) []*Midjourney

func GetAllUnFinishTasks

func GetAllUnFinishTasks() []*Midjourney

func GetAllUserTask

func GetAllUserTask(userId int, startIdx int, num int, queryParams TaskQueryParams) []*Midjourney

func GetByMJId

func GetByMJId(userId int, mjId string) *Midjourney

func GetByMJIds

func GetByMJIds(userId int, mjIds []string) []*Midjourney

func GetByOnlyMJId

func GetByOnlyMJId(mjId string) *Midjourney

func GetMjByuId

func GetMjByuId(id int) *Midjourney

func (*Midjourney) Insert

func (midjourney *Midjourney) Insert() error

func (*Midjourney) Update

func (midjourney *Midjourney) Update() error

type Model

type Model struct {
	Id           int            `json:"id"`
	ModelName    string         `json:"model_name" gorm:"size:128;not null;uniqueIndex:uk_model_name_delete_at,priority:1"`
	Description  string         `json:"description,omitempty" gorm:"type:text"`
	Icon         string         `json:"icon,omitempty" gorm:"type:varchar(128)"`
	Tags         string         `json:"tags,omitempty" gorm:"type:varchar(255)"`
	VendorID     int            `json:"vendor_id,omitempty" gorm:"index"`
	Endpoints    string         `json:"endpoints,omitempty" gorm:"type:text"`
	Status       int            `json:"status" gorm:"default:1"`
	SyncOfficial int            `json:"sync_official" gorm:"default:1"`
	CreatedTime  int64          `json:"created_time" gorm:"bigint"`
	UpdatedTime  int64          `json:"updated_time" gorm:"bigint"`
	DeletedAt    gorm.DeletedAt `json:"-" gorm:"index;uniqueIndex:uk_model_name_delete_at,priority:2"`

	BoundChannels []BoundChannel `json:"bound_channels,omitempty" gorm:"-"`
	EnableGroups  []string       `json:"enable_groups,omitempty" gorm:"-"`
	QuotaTypes    []int          `json:"quota_types,omitempty" gorm:"-"`
	NameRule      int            `json:"name_rule" gorm:"default:0"`

	MatchedModels []string `json:"matched_models,omitempty" gorm:"-"`
	MatchedCount  int      `json:"matched_count,omitempty" gorm:"-"`
}

func GetAllModels

func GetAllModels(offset int, limit int) ([]*Model, error)

func SearchModels

func SearchModels(keyword string, vendor string, offset int, limit int) ([]*Model, int64, error)

func (*Model) Delete

func (mi *Model) Delete() error

func (*Model) Insert

func (mi *Model) Insert() error

func (*Model) Update

func (mi *Model) Update() error

type Option

type Option struct {
	Key   string `json:"key" gorm:"primaryKey"`
	Value string `json:"value"`
}

func AllOption

func AllOption() ([]*Option, error)

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(credentialID []byte) (*PasskeyCredential, error)

func GetPasskeyByUserID

func GetPasskeyByUserID(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 PrefillGroup

type PrefillGroup struct {
	Id          int            `json:"id"`
	Name        string         `json:"name" gorm:"size:64;not null;uniqueIndex:uk_prefill_name,where:deleted_at IS NULL"`
	Type        string         `json:"type" gorm:"size:32;index;not null"`
	Items       JSONValue      `json:"items" gorm:"type:json"`
	Description string         `json:"description,omitempty" gorm:"type:varchar(255)"`
	CreatedTime int64          `json:"created_time" gorm:"bigint"`
	UpdatedTime int64          `json:"updated_time" gorm:"bigint"`
	DeletedAt   gorm.DeletedAt `json:"-" gorm:"index"`
}

func GetAllPrefillGroups

func GetAllPrefillGroups(groupType string) ([]*PrefillGroup, error)

GetAllPrefillGroups 获取全部组,可按类型过滤(为空则返回全部)

func (*PrefillGroup) Insert

func (g *PrefillGroup) Insert() error

Insert 新建组

func (*PrefillGroup) Update

func (g *PrefillGroup) Update() error

Update 更新组

type Pricing

type Pricing struct {
	ModelName              string                  `json:"model_name"`
	Description            string                  `json:"description,omitempty"`
	Icon                   string                  `json:"icon,omitempty"`
	Tags                   string                  `json:"tags,omitempty"`
	VendorID               int                     `json:"vendor_id,omitempty"`
	QuotaType              int                     `json:"quota_type"`
	ModelRatio             float64                 `json:"model_ratio"`
	ModelPrice             float64                 `json:"model_price"`
	OwnerBy                string                  `json:"owner_by"`
	CompletionRatio        float64                 `json:"completion_ratio"`
	EnableGroup            []string                `json:"enable_groups"`
	SupportedEndpointTypes []constant.EndpointType `json:"supported_endpoint_types"`
}

func GetPricing

func GetPricing() []Pricing

type PricingVendor

type PricingVendor struct {
	ID          int    `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Icon        string `json:"icon,omitempty"`
}

func GetVendors

func GetVendors() []PricingVendor

GetVendors 返回当前定价接口使用到的供应商信息

type Properties

type Properties struct {
	Input             string `json:"input"`
	UpstreamModelName string `json:"upstream_model_name,omitempty"`
	OriginModelName   string `json:"origin_model_name,omitempty"`
}

func (*Properties) Scan

func (m *Properties) Scan(val interface{}) error

func (Properties) Value

func (m Properties) Value() (driver.Value, error)

type QuotaData

type QuotaData struct {
	Id        int    `json:"id"`
	UserID    int    `json:"user_id" gorm:"index"`
	Username  string `json:"username" gorm:"index:idx_qdt_model_user_name,priority:2;size:64;default:''"`
	ModelName string `json:"model_name" gorm:"index:idx_qdt_model_user_name,priority:1;size:64;default:''"`
	CreatedAt int64  `json:"created_at" gorm:"bigint;index:idx_qdt_created_at,priority:2"`
	TokenUsed int    `json:"token_used" gorm:"default:0"`
	Count     int    `json:"count" gorm:"default:0"`
	Quota     int    `json:"quota" gorm:"default:0"`
}

QuotaData 柱状图数据

func GetAllQuotaDates

func GetAllQuotaDates(startTime int64, endTime int64, username string) (quotaData []*QuotaData, err error)

func GetQuotaDataByUserId

func GetQuotaDataByUserId(userId int, startTime int64, endTime int64) (quotaData []*QuotaData, err error)

func GetQuotaDataByUsername

func GetQuotaDataByUsername(username string, startTime int64, endTime int64) (quotaData []*QuotaData, err error)

type RecordConsumeLogParams

type RecordConsumeLogParams struct {
	ChannelId        int                    `json:"channel_id"`
	PromptTokens     int                    `json:"prompt_tokens"`
	CompletionTokens int                    `json:"completion_tokens"`
	ModelName        string                 `json:"model_name"`
	TokenName        string                 `json:"token_name"`
	Quota            int                    `json:"quota"`
	Content          string                 `json:"content"`
	TokenId          int                    `json:"token_id"`
	UseTimeSeconds   int                    `json:"use_time_seconds"`
	IsStream         bool                   `json:"is_stream"`
	Group            string                 `json:"group"`
	Other            map[string]interface{} `json:"other"`
}

type Redemption

type Redemption struct {
	Id           int            `json:"id"`
	UserId       int            `json:"user_id"`
	Key          string         `json:"key" gorm:"type:char(32);uniqueIndex"`
	Status       int            `json:"status" gorm:"default:1"`
	Name         string         `json:"name" gorm:"index"`
	Quota        int            `json:"quota" gorm:"default:100"`
	CreatedTime  int64          `json:"created_time" gorm:"bigint"`
	RedeemedTime int64          `json:"redeemed_time" gorm:"bigint"`
	Count        int            `json:"count" gorm:"-:all"` // only for api request
	UsedUserId   int            `json:"used_user_id"`
	DeletedAt    gorm.DeletedAt `gorm:"index"`
	ExpiredTime  int64          `json:"expired_time" gorm:"bigint"` // 过期时间,0 表示不过期
}

func GetAllRedemptions

func GetAllRedemptions(startIdx int, num int) (redemptions []*Redemption, total int64, err error)

func GetRedemptionById

func GetRedemptionById(id int) (*Redemption, error)

func SearchRedemptions

func SearchRedemptions(keyword string, startIdx int, num int) (redemptions []*Redemption, total int64, err error)

func (*Redemption) Delete

func (redemption *Redemption) Delete() error

func (*Redemption) Insert

func (redemption *Redemption) Insert() error

func (*Redemption) SelectUpdate

func (redemption *Redemption) SelectUpdate() error

func (*Redemption) Update

func (redemption *Redemption) Update() error

Update Make sure your token's fields is completed, because this will update non-zero values

type Setup

type Setup struct {
	ID            uint   `json:"id" gorm:"primaryKey"`
	Version       string `json:"version" gorm:"type:varchar(50);not null"`
	InitializedAt int64  `json:"initialized_at" gorm:"type:bigint;not null"`
}

func GetSetup

func GetSetup() *Setup

type Stat

type Stat struct {
	Quota int `json:"quota"`
	Rpm   int `json:"rpm"`
	Tpm   int `json:"tpm"`
}

func SumUsedQuota

func SumUsedQuota(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, channel int, group string) (stat Stat)

type SyncTaskQueryParams

type SyncTaskQueryParams struct {
	Platform       constant.TaskPlatform
	ChannelID      string
	TaskID         string
	UserID         string
	Action         string
	Status         string
	StartTimestamp int64
	EndTimestamp   int64
	UserIDs        []int
}

SyncTaskQueryParams 用于包含所有搜索条件的结构体,可以根据需求添加更多字段

type Task

type Task struct {
	ID         int64                 `json:"id" gorm:"primary_key;AUTO_INCREMENT"`
	CreatedAt  int64                 `json:"created_at" gorm:"index"`
	UpdatedAt  int64                 `json:"updated_at"`
	TaskID     string                `json:"task_id" gorm:"type:varchar(191);index"` // 第三方id,不一定有/ song id\ Task id
	Platform   constant.TaskPlatform `json:"platform" gorm:"type:varchar(30);index"` // 平台
	UserId     int                   `json:"user_id" gorm:"index"`
	Group      string                `json:"group" gorm:"type:varchar(50)"` // 修正计费用
	ChannelId  int                   `json:"channel_id" gorm:"index"`
	Quota      int                   `json:"quota"`
	Action     string                `json:"action" gorm:"type:varchar(40);index"` // 任务类型, song, lyrics, description-mode
	Status     TaskStatus            `json:"status" gorm:"type:varchar(20);index"` // 任务状态
	FailReason string                `json:"fail_reason"`
	SubmitTime int64                 `json:"submit_time" gorm:"index"`
	StartTime  int64                 `json:"start_time" gorm:"index"`
	FinishTime int64                 `json:"finish_time" gorm:"index"`
	Progress   string                `json:"progress" gorm:"type:varchar(20);index"`
	Properties Properties            `json:"properties" gorm:"type:json"`
	// 禁止返回给用户,内部可能包含key等隐私信息
	PrivateData TaskPrivateData `json:"-" gorm:"column:private_data;type:json"`
	Data        json.RawMessage `json:"data" gorm:"type:json"`
}

func GetAllUnFinishSyncTasks

func GetAllUnFinishSyncTasks(limit int) []*Task

func GetByOnlyTaskId

func GetByOnlyTaskId(taskId string) (*Task, bool, error)

func GetByTaskId

func GetByTaskId(userId int, taskId string) (*Task, bool, error)

func GetByTaskIds

func GetByTaskIds(userId int, taskIds []any) ([]*Task, error)

func InitTask

func InitTask(platform constant.TaskPlatform, relayInfo *commonRelay.RelayInfo) *Task

func TaskGetAllTasks

func TaskGetAllTasks(startIdx int, num int, queryParams SyncTaskQueryParams) []*Task

func TaskGetAllUserTask

func TaskGetAllUserTask(userId int, startIdx int, num int, queryParams SyncTaskQueryParams) []*Task

func (*Task) GetData

func (t *Task) GetData(v any) error

func (*Task) Insert

func (Task *Task) Insert() error

func (*Task) SetData

func (t *Task) SetData(data any)

func (*Task) ToOpenAIVideo

func (t *Task) ToOpenAIVideo() *dto.OpenAIVideo

func (*Task) Update

func (Task *Task) Update() error

type TaskPrivateData

type TaskPrivateData struct {
	Key string `json:"key,omitempty"`
}

func (*TaskPrivateData) Scan

func (p *TaskPrivateData) Scan(val interface{}) error

func (TaskPrivateData) Value

func (p TaskPrivateData) Value() (driver.Value, error)

type TaskQueryParams

type TaskQueryParams struct {
	ChannelID      string
	MjID           string
	StartTimestamp string
	EndTimestamp   string
}

TaskQueryParams 用于包含所有搜索条件的结构体,可以根据需求添加更多字段

type TaskQuotaUsage

type TaskQuotaUsage struct {
	Mode  string  `json:"mode"`
	Count float64 `json:"count"`
}

func SumUsedTaskQuota

func SumUsedTaskQuota(queryParams SyncTaskQueryParams) (stat []TaskQuotaUsage, err error)

type TaskStatus

type TaskStatus string

func (TaskStatus) ToVideoStatus

func (t TaskStatus) ToVideoStatus() string

type Token

type Token struct {
	Id                 int            `json:"id"`
	UserId             int            `json:"user_id" gorm:"index"`
	Key                string         `json:"key" gorm:"type:char(48);uniqueIndex"`
	Status             int            `json:"status" gorm:"default:1"`
	Name               string         `json:"name" gorm:"index" `
	CreatedTime        int64          `json:"created_time" gorm:"bigint"`
	AccessedTime       int64          `json:"accessed_time" gorm:"bigint"`
	ExpiredTime        int64          `json:"expired_time" gorm:"bigint;default:-1"` // -1 means never expired
	RemainQuota        int            `json:"remain_quota" gorm:"default:0"`
	UnlimitedQuota     bool           `json:"unlimited_quota"`
	ModelLimitsEnabled bool           `json:"model_limits_enabled"`
	ModelLimits        string         `json:"model_limits" gorm:"type:varchar(1024);default:''"`
	AllowIps           *string        `json:"allow_ips" gorm:"default:''"`
	UsedQuota          int            `json:"used_quota" gorm:"default:0"` // used quota
	Group              string         `json:"group" gorm:"default:''"`
	CrossGroupRetry    bool           `json:"cross_group_retry"` // 跨分组重试,仅auto分组有效
	DeletedAt          gorm.DeletedAt `gorm:"index"`
}

func GetAllUserTokens

func GetAllUserTokens(userId int, startIdx int, num int) ([]*Token, error)

func GetTokenById

func GetTokenById(id int) (*Token, error)

func GetTokenByIds

func GetTokenByIds(id int, userId int) (*Token, error)

func GetTokenByKey

func GetTokenByKey(key string, fromDB bool) (token *Token, err error)

func SearchUserTokens

func SearchUserTokens(userId int, keyword string, token string) (tokens []*Token, err error)

func ValidateUserToken

func ValidateUserToken(key string) (token *Token, err error)

func (*Token) Clean

func (token *Token) Clean()

func (*Token) Delete

func (token *Token) Delete() (err error)

func (*Token) GetIpLimits

func (token *Token) GetIpLimits() []string

func (*Token) GetModelLimits

func (token *Token) GetModelLimits() []string

func (*Token) GetModelLimitsMap

func (token *Token) GetModelLimitsMap() map[string]bool

func (*Token) Insert

func (token *Token) Insert() error

func (*Token) IsModelLimitsEnabled

func (token *Token) IsModelLimitsEnabled() bool

func (*Token) SelectUpdate

func (token *Token) SelectUpdate() (err error)

func (*Token) Update

func (token *Token) Update() (err error)

Update Make sure your token's fields is completed, because this will update non-zero values

type TopUp

type TopUp struct {
	Id            int     `json:"id"`
	UserId        int     `json:"user_id" gorm:"index"`
	Amount        int64   `json:"amount"`
	Money         float64 `json:"money"`
	TradeNo       string  `json:"trade_no" gorm:"unique;type:varchar(255);index"`
	PaymentMethod string  `json:"payment_method" gorm:"type:varchar(50)"`
	CreateTime    int64   `json:"create_time"`
	CompleteTime  int64   `json:"complete_time"`
	Status        string  `json:"status"`
}

func GetAllTopUps

func GetAllTopUps(pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)

GetAllTopUps 获取全平台的充值记录(管理员使用)

func GetTopUpById

func GetTopUpById(id int) *TopUp

func GetTopUpByTradeNo

func GetTopUpByTradeNo(tradeNo string) *TopUp

func GetUserTopUps

func GetUserTopUps(userId int, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)

func SearchAllTopUps

func SearchAllTopUps(keyword string, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)

SearchAllTopUps 按订单号搜索全平台充值记录(管理员使用)

func SearchUserTopUps

func SearchUserTopUps(userId int, keyword string, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)

SearchUserTopUps 按订单号搜索某用户的充值记录

func (*TopUp) Insert

func (topUp *TopUp) Insert() error

func (*TopUp) Update

func (topUp *TopUp) Update() error

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

func GetTwoFAByUserId(userId int) (*TwoFA, error)

GetTwoFAByUserId 根据用户ID获取2FA设置

func (*TwoFA) Create

func (t *TwoFA) Create() error

CreateTwoFA 创建2FA设置

func (*TwoFA) Delete

func (t *TwoFA) Delete() error

Delete 删除2FA设置

func (*TwoFA) Enable

func (t *TwoFA) Enable() error

EnableTwoFA 启用2FA

func (*TwoFA) IncrementFailedAttempts

func (t *TwoFA) IncrementFailedAttempts() error

IncrementFailedAttempts 增加失败尝试次数

func (*TwoFA) IsLocked

func (t *TwoFA) IsLocked() bool

IsLocked 检查账户是否被锁定

func (*TwoFA) ResetFailedAttempts

func (t *TwoFA) ResetFailedAttempts() error

ResetFailedAttempts 重置失败尝试次数

func (*TwoFA) Update

func (t *TwoFA) Update() error

Update 更新2FA设置

func (*TwoFA) ValidateBackupCodeAndUpdateUsage

func (t *TwoFA) ValidateBackupCodeAndUpdateUsage(code string) (bool, error)

ValidateBackupCodeAndUpdateUsage 验证备用码并更新使用记录

func (*TwoFA) ValidateTOTPAndUpdateUsage

func (t *TwoFA) ValidateTOTPAndUpdateUsage(code string) (bool, error)

ValidateTOTPAndUpdateUsage 验证TOTP并更新使用记录

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 User

type User struct {
	Id               int            `json:"id"`
	Username         string         `json:"username" gorm:"unique;index" validate:"max=20"`
	Password         string         `json:"password" gorm:"not null;" validate:"min=8,max=20"`
	OriginalPassword string         `json:"original_password" gorm:"-:all"` // this field is only for Password change verification, don't save it to database!
	DisplayName      string         `json:"display_name" gorm:"index" validate:"max=20"`
	Role             int            `json:"role" gorm:"type:int;default:1"`   // admin, common
	Status           int            `json:"status" gorm:"type:int;default:1"` // enabled, disabled
	Email            string         `json:"email" gorm:"index" validate:"max=50"`
	GitHubId         string         `json:"github_id" gorm:"column:github_id;index"`
	DiscordId        string         `json:"discord_id" gorm:"column:discord_id;index"`
	OidcId           string         `json:"oidc_id" gorm:"column:oidc_id;index"`
	WeChatId         string         `json:"wechat_id" gorm:"column:wechat_id;index"`
	TelegramId       string         `json:"telegram_id" gorm:"column:telegram_id;index"`
	VerificationCode string         `json:"verification_code" gorm:"-:all"`                                    // this field is only for Email verification, don't save it to database!
	AccessToken      *string        `json:"access_token" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management
	Quota            int            `json:"quota" gorm:"type:int;default:0"`
	UsedQuota        int            `json:"used_quota" gorm:"type:int;default:0;column:used_quota"` // used quota
	RequestCount     int            `json:"request_count" gorm:"type:int;default:0;"`               // request number
	Group            string         `json:"group" gorm:"type:varchar(64);default:'default'"`
	AffCode          string         `json:"aff_code" gorm:"type:varchar(32);column:aff_code;uniqueIndex"`
	AffCount         int            `json:"aff_count" gorm:"type:int;default:0;column:aff_count"`
	AffQuota         int            `json:"aff_quota" gorm:"type:int;default:0;column:aff_quota"`           // 邀请剩余额度
	AffHistoryQuota  int            `json:"aff_history_quota" gorm:"type:int;default:0;column:aff_history"` // 邀请历史额度
	InviterId        int            `json:"inviter_id" gorm:"type:int;column:inviter_id;index"`
	DeletedAt        gorm.DeletedAt `gorm:"index"`
	LinuxDOId        string         `json:"linux_do_id" gorm:"column:linux_do_id;index"`
	Setting          string         `json:"setting" gorm:"type:text;column:setting"`
	Remark           string         `json:"remark,omitempty" gorm:"type:varchar(255)" validate:"max=255"`
	StripeCustomer   string         `json:"stripe_customer" gorm:"type:varchar(64);column:stripe_customer;index"`
}

User if you add sensitive fields, don't forget to clean them in setupLogin function. Otherwise, the sensitive information will be saved on local storage in plain text!

func GetAllUsers

func GetAllUsers(pageInfo *common.PageInfo) (users []*User, total int64, err error)

func GetRootUser

func GetRootUser() (user *User)

func GetUserById

func GetUserById(id int, selectAll bool) (*User, error)

func SearchUsers

func SearchUsers(keyword string, group string, startIdx int, num int) ([]*User, int64, error)

func ValidateAccessToken

func ValidateAccessToken(token string) (user *User)

func (*User) Delete

func (user *User) Delete() error

func (*User) Edit

func (user *User) Edit(updatePassword bool) error

func (*User) FillUserByDiscordId

func (user *User) FillUserByDiscordId() error

func (*User) FillUserByEmail

func (user *User) FillUserByEmail() error

func (*User) FillUserByGitHubId

func (user *User) FillUserByGitHubId() error

func (*User) FillUserById

func (user *User) FillUserById() error

func (*User) FillUserByLinuxDOId

func (user *User) FillUserByLinuxDOId() error

func (*User) FillUserByOidcId

func (user *User) FillUserByOidcId() error

func (*User) FillUserByTelegramId

func (user *User) FillUserByTelegramId() error

func (*User) FillUserByWeChatId

func (user *User) FillUserByWeChatId() error

func (*User) GetAccessToken

func (user *User) GetAccessToken() string

func (*User) GetSetting

func (user *User) GetSetting() dto.UserSetting

func (*User) HardDelete

func (user *User) HardDelete() error

func (*User) Insert

func (user *User) Insert(inviterId int) error

func (*User) SetAccessToken

func (user *User) SetAccessToken(token string)

func (*User) SetSetting

func (user *User) SetSetting(setting dto.UserSetting)

func (*User) ToBaseUser

func (user *User) ToBaseUser() *UserBase

func (*User) TransferAffQuotaToQuota

func (user *User) TransferAffQuotaToQuota(quota int) error

func (*User) Update

func (user *User) Update(updatePassword bool) error

func (*User) ValidateAndFill

func (user *User) ValidateAndFill() (err error)

ValidateAndFill check password & user status

type UserBase

type UserBase struct {
	Id       int    `json:"id"`
	Group    string `json:"group"`
	Email    string `json:"email"`
	Quota    int    `json:"quota"`
	Status   int    `json:"status"`
	Username string `json:"username"`
	Setting  string `json:"setting"`
}

UserBase struct remains the same as it represents the cached data structure

func GetUserCache

func GetUserCache(userId int) (userCache *UserBase, err error)

GetUserCache gets complete user cache from hash

func (*UserBase) GetSetting

func (user *UserBase) GetSetting() dto.UserSetting

func (*UserBase) WriteContext

func (user *UserBase) WriteContext(c *gin.Context)

type Vendor

type Vendor struct {
	Id          int            `json:"id"`
	Name        string         `json:"name" gorm:"size:128;not null;uniqueIndex:uk_vendor_name_delete_at,priority:1"`
	Description string         `json:"description,omitempty" gorm:"type:text"`
	Icon        string         `json:"icon,omitempty" gorm:"type:varchar(128)"`
	Status      int            `json:"status" gorm:"default:1"`
	CreatedTime int64          `json:"created_time" gorm:"bigint"`
	UpdatedTime int64          `json:"updated_time" gorm:"bigint"`
	DeletedAt   gorm.DeletedAt `json:"-" gorm:"index;uniqueIndex:uk_vendor_name_delete_at,priority:2"`
}

func GetAllVendors

func GetAllVendors(offset int, limit int) ([]*Vendor, error)

GetAllVendors 获取全部供应商(分页)

func GetVendorByID

func GetVendorByID(id int) (*Vendor, error)

GetVendorByID 根据 ID 获取供应商

func SearchVendors

func SearchVendors(keyword string, offset int, limit int) ([]*Vendor, int64, error)

SearchVendors 按关键字搜索供应商

func (*Vendor) Delete

func (v *Vendor) Delete() error

Delete 软删除供应商

func (*Vendor) Insert

func (v *Vendor) Insert() error

Insert 创建新的供应商记录

func (*Vendor) Update

func (v *Vendor) Update() error

Update 更新供应商记录

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL