Documentation
¶
Index ¶
- Constants
- Variables
- func AcquireRegistrationLock(email string) (bool, error)
- func CheckValue(db *gorm.DB, key, defaultValue, format string, autoload, public bool)
- func ConfigureConnectionPool(db *gorm.DB)
- func ExtractKeyFromURL(url string) string
- func FileExists(path string) bool
- func GenerateDefaultSessionSecret() string
- func GenerateRandomString(length int) string
- func GetBoolEnv(key string) bool
- func GetBoolOrDefault(key string, defaultValue bool) bool
- func GetBoolValue(db *gorm.DB, key string) bool
- func GetDeviceID(userAgent, ipAddress string) string
- func GetEnv(key string) string
- func GetFileExtension(filename string) string
- func GetFloatEnv(key string) float64
- func GetIPLocation(ip string) (country, city, location string, err error)
- func GetInt64OrDefault(key string, defaultValue int64) int64
- func GetIntEnv(key string) int64
- func GetIntOrDefault(key string, defaultValue int) int
- func GetIntValue(db *gorm.DB, key string, defaultVal int) int
- func GetRealAddressByIP(ip string) string
- func GetStringOrDefault(key, defaultValue string) string
- func GetValue(db *gorm.DB, key string) string
- func InitDatabase(logWrite io.Writer, driver, dsn string) (*gorm.DB, error)
- func InitGlobalCache(maxSize int, expiration time.Duration)
- func InitGlobalDistributedLock()
- func InitGlobalLoginSecurityManager(logger *zap.Logger)
- func InitGlobalRegistrationGuard(logger *zap.Logger)
- func IsInternalIP(ip string) bool
- func LoadAutoloads(db *gorm.DB)
- func LoadEnv(env string) error
- func LoadEnvs(objPtr any)
- func LookupEnv(key string) (value string, found bool)
- func MakeMigrates(db *gorm.DB, insts []any) error
- func ParseUserAgent(userAgent string) (deviceType, os, browser string)
- func RandNumberText(n int) string
- func RandString(n int) string
- func RandText(n int) string
- func ReleaseRegistrationLock(email string) error
- func SanitizeAndValidate(input string, inputType string) (string, error)
- func SanitizeEmail(email string) string
- func SanitizeInput(input string) string
- func SanitizePassword(password string) string
- func SetValue(db *gorm.DB, key, value, format string, autoload, public bool)
- func StructAsMap(form any, fields []string) (vals map[string]any)
- func UnZlib(in []byte) (out []byte)
- func ValidateDisplayName(name string) error
- func ValidateEmailFormat(email string) error
- func ValidatePasswordFormat(password string) error
- func ValidateSQLInjection(input string) error
- func ValidateUserName(username string) error
- func ValidateXSS(input string) error
- func Zlib(in []byte) (out []byte)
- type AVProbeOutput
- type AccountLockInfo
- type CheckAccountLockFunc
- type CheckPasswordLoginLimitFunc
- type Config
- type DistributedLock
- type Error
- type ExpiredLRUCache
- type FileMetadata
- type GetRecentLoginLocationsFunc
- type IPGeolocationResponse
- type IPLocationResponse
- type IPLocationService
- type ImageInfo
- type LoginLocation
- type LoginSecurityManager
- func (lsm *LoginSecurityManager) CheckAccountLock(db *gorm.DB, email string, userID uint, checkFunc CheckAccountLockFunc) error
- func (lsm *LoginSecurityManager) CheckIPRateLimit(ip string) error
- func (lsm *LoginSecurityManager) CheckPasswordLoginLimit(db *gorm.DB, userID uint, email string, checkFunc CheckPasswordLoginLimitFunc) (bool, error)
- func (lsm *LoginSecurityManager) CheckProxyIP(ip string) (bool, error)
- func (lsm *LoginSecurityManager) ClearFailedLoginCount(email string)
- func (lsm *LoginSecurityManager) DetectSuspiciousLogin(db *gorm.DB, userID uint, currentIP, currentLocation, currentCountry string, ...) (bool, error)
- func (lsm *LoginSecurityManager) RecordFailedLogin(db *gorm.DB, email string, userID uint, ipAddress string, ...) error
- type MemoryLock
- type MetadataService
- type RecordFailedLoginFunc
- type RegistrationAttempt
- type RegistrationGuard
- func (rg *RegistrationGuard) AddIPToBlacklist(cidr string) error
- func (rg *RegistrationGuard) CheckFailedAttempts(ip string) error
- func (rg *RegistrationGuard) CheckIPRateLimit(ip string) error
- func (rg *RegistrationGuard) CheckRegistrationAllowed(ip string, email string, password string) error
- func (rg *RegistrationGuard) RecordRegistrationAttempt(ip string, email string, success bool, reason string)
- func (rg *RegistrationGuard) ValidateEmail(email string) error
- func (rg *RegistrationGuard) ValidateIP(ip string) error
- func (rg *RegistrationGuard) ValidatePassword(password string) error
- type SigHandler
- type SigHandlerEvent
- type SignalHandler
- type Signals
- type Snowflake
Constants ¶
const ( // IP地址查询API(国内) PCONLINE_IP_URL = "http://whois.pconline.com.cn/ipJson.jsp" // IP地址查询API(国际) IP_API_URL = "http://ip-api.com/json/" // 未知地址 UNKNOWN = "Unknown" // 内网IP标识 INTERNAL_IP = "内网IP" LOCAL_NETWORK = "Local Network" )
Variables ¶
var ( // Tools related errors ErrInvalidToolListFormat = errors.New("invalid tool list response format") ErrInvalidToolFormat = errors.New("invalid tool format") ErrToolNotFound = errors.New("tool not found") ErrInvalidToolParams = errors.New("invalid tool parameters") // JSON-RPC related errors ErrParseJSONRPC = errors.New("failed to parse JSON-RPC message") ErrInvalidJSONRPCFormat = errors.New("invalid JSON-RPC format") ErrInvalidJSONRPCResponse = errors.New("invalid JSON-RPC response") ErrInvalidJSONRPCRequest = errors.New("invalid JSON-RPC request") ErrInvalidJSONRPCParams = errors.New("invalid JSON-RPC parameters") // Resource related errors ErrInvalidResourceFormat = errors.New("invalid resource format") ErrResourceNotFound = errors.New("resource not found") // Prompt related errors ErrInvalidPromptFormat = errors.New("invalid prompt format") ErrPromptNotFound = errors.New("prompt not found") // Tool manager errors ErrEmptyToolName = errors.New("tool name cannot be empty") ErrToolAlreadyRegistered = errors.New("tool already registered") ErrToolExecutionFailed = errors.New("tool execution failed") // Resource manager errors ErrEmptyResourceURI = errors.New("resource URI cannot be empty") // Prompt manager errors ErrEmptyPromptName = errors.New("prompt name cannot be empty") // Lifecycle manager errors ErrSessionAlreadyInitialized = errors.New("session already initialized") ErrSessionNotInitialized = errors.New("session not initialized") // Parameter errors ErrInvalidParams = errors.New("invalid parameters") ErrMissingParams = errors.New("missing required parameters") // Client errors ErrAlreadyInitialized = errors.New("client already initialized") ErrNotInitialized = errors.New("client not initialized") ErrInvalidServerURL = errors.New("invalid server URL") )
Common errors
var ErrAttachmentNotExist = &Error{Code: http.StatusNotFound, Message: "attachment not exist"}
var ErrBadToken = errors.New("bad token") // Token has been tampered with, forged or is invalid
var ErrEmailExists = errors.New("email exists, please use another email") // Email already exists, trying to register or update to an already registered email
var ErrEmailRequired = errors.New("email required") // Email field must be provided but was not provided
var ErrEmptyEmail = errors.New("empty email") // Email is empty, typically used for registration, login, password recovery and other operations
var ErrEmptyPassword = errors.New("empty password") // Password is empty, typically used for registration or login validation failure
var ErrForbidden = errors.New("forbidden access") // Access denied, user is logged in but has no permission to access the target resource
var ErrInvalidPrimaryKey = errors.New("invalid primary key") // Primary key is invalid, possibly due to format error or missing
var ErrInvalidToken = errors.New("invalid token") // Token format is illegal or does not conform to specifications
var ErrInvalidView = errors.New("with invalid view") // Request used an invalid view identifier or parameter
var ErrLLMCallFailed = errors.New("failed to call language model") // Failed to call language model
var ErrNotActivated = errors.New("user not activated") // User account is not activated, usually used when email activation is not completed
var ErrNotAttachmentOwner = &Error{Code: http.StatusForbidden, Message: "not attachment owner"}
var ErrNotChanged = errors.New("not changed") // Data has not changed, for example no actual field changes in update request
var ErrNotFound = errors.New("not found") // Requested data or resource not found
var ErrOnlySuperUser = errors.New("only super user can do this") // Operations limited to super users only
var ErrQuotaExceeded = errors.New("quota exceeded") // User quota has been exhausted
var ErrSameEmail = errors.New("same email") // Old and new email are the same, triggered when user tries to change email
var ErrTokenExpired = errors.New("token expired") // Token has expired
var ErrTokenRequired = errors.New("token required") // Missing required token, for example when accessing protected resources
var ErrUserNotAllowLogin = errors.New("user not allow login") // User is prohibited from logging in, possibly banned by administrator
var ErrUserNotAllowSignup = errors.New("user not allow signup") // User is prohibited from registering, system configuration or policy restricts registration behavior
var ErrUserNotExists = errors.New("user not exists") // User does not exist, commonly used for login, query or operations on non-existent users
Functions ¶
func AcquireRegistrationLock ¶
AcquireRegistrationLock 获取注册锁(防止并发注册同一邮箱)
func CheckValue ¶
func ConfigureConnectionPool ¶
ConfigureConnectionPool configure database connection pool
func GenerateDefaultSessionSecret ¶
func GenerateDefaultSessionSecret() string
GenerateDefaultSessionSecret 生成默认的会话密钥(仅用于开发环境)
func GenerateRandomString ¶
GenerateRandomString 生成指定长度的随机字符串
func GetBoolEnv ¶
func GetBoolOrDefault ¶
GetBoolOrDefault 获取布尔环境变量值,如果为空则返回默认值
func GetDeviceID ¶
GetDeviceID 从User-Agent生成设备ID
func GetFloatEnv ¶
func GetIPLocation ¶
func GetInt64OrDefault ¶
GetInt64OrDefault 获取整数环境变量值,如果为空则返回默认值
func GetIntOrDefault ¶
GetIntOrDefault 获取整数环境变量值,如果为空则返回默认值
func GetRealAddressByIP ¶
GetRealAddressByIP 根据IP获取真实地址(兼容旧接口,返回完整地址字符串)
func GetStringOrDefault ¶
GetStringOrDefault 获取环境变量值,如果为空则返回默认值
func InitGlobalCache ¶
func InitGlobalDistributedLock ¶
func InitGlobalDistributedLock()
InitGlobalDistributedLock 初始化全局分布式锁
func InitGlobalLoginSecurityManager ¶
InitGlobalLoginSecurityManager 初始化全局登录安全管理器
func InitGlobalRegistrationGuard ¶
InitGlobalRegistrationGuard 初始化全局注册防护服务
func LoadAutoloads ¶
func ParseUserAgent ¶
ParseUserAgent 解析User-Agent获取设备信息
func RandNumberText ¶
func RandString ¶
func ReleaseRegistrationLock ¶
ReleaseRegistrationLock 释放注册锁
func SanitizeAndValidate ¶
SanitizeAndValidate 清理并验证输入
func SanitizePassword ¶
SanitizePassword 清理密码(保留空格,但去除首尾空格)
func ValidatePasswordFormat ¶
ValidatePasswordFormat 验证密码格式
func ValidateSQLInjection ¶
ValidateSQLInjection 检查SQL注入风险
Types ¶
type AVProbeOutput ¶
type AVProbeOutput struct {
Streams []map[string]any `json:"streams"`
Format map[string]any `json:"format"`
}
AVProbeOutput 为 ffprobe -print_format json 的核心输出结构 这里使用 map 保留所有字段(你示例里的 streams/format/tags/disposition 等都能透传)
type AccountLockInfo ¶
AccountLockInfo 账号锁定信息
type CheckAccountLockFunc ¶
CheckAccountLockFunc 检查账号锁定的函数类型
type CheckPasswordLoginLimitFunc ¶
CheckPasswordLoginLimitFunc 检查密码登录次数限制的函数类型
type Config ¶
type Config struct {
ID uint `json:"id" gorm:"primaryKey"`
Key string `json:"key" gorm:"size:128;uniqueIndex"`
Desc string `json:"desc" gorm:"size:200"`
Autoload bool `json:"autoload" gorm:"index"`
Public bool `json:"public" gorm:"index" default:"false"`
Format string `json:"format" gorm:"size:20" default:"text" comment:"json,yaml,int,float,bool,text"`
Value string
CreatedAt time.Time `json:"-" gorm:"autoCreateTime"`
UpdatedAt time.Time `json:"-" gorm:"autoUpdateTime"`
}
func LoadPublicConfigs ¶
type DistributedLock ¶
type DistributedLock interface {
Lock(key string, ttl time.Duration) (bool, error)
Unlock(key string) error
TryLock(key string, ttl time.Duration) (bool, error)
}
DistributedLock 分布式锁接口
var GlobalDistributedLock DistributedLock
GlobalDistributedLock 全局分布式锁实例
type Error ¶
func (Error) StatusCode ¶
type ExpiredLRUCache ¶
type ExpiredLRUCache[K comparable, V any] struct { *lru.Cache[K, expiredLRUCacheValue[V]] // contains filtered or unexported fields }
var GlobalCache *ExpiredLRUCache[string, any]
GlobalCache is a global cache instance that supports generic key-value pairs
func NewExpiredLRUCache ¶
func NewExpiredLRUCache[K comparable, V any](size int, expired time.Duration) *ExpiredLRUCache[K, V]
func (*ExpiredLRUCache[K, V]) Add ¶
func (c *ExpiredLRUCache[K, V]) Add(key K, value V) (evicted bool)
func (*ExpiredLRUCache[K, V]) Contains ¶
func (c *ExpiredLRUCache[K, V]) Contains(key K) bool
func (*ExpiredLRUCache[K, V]) Get ¶
func (c *ExpiredLRUCache[K, V]) Get(key K) (value V, ok bool)
func (*ExpiredLRUCache[K, V]) Remove ¶
func (c *ExpiredLRUCache[K, V]) Remove(key K) (present bool)
type FileMetadata ¶
type FileMetadata struct {
FilePath string `json:"filePath"`
FileName string `json:"fileName"`
FileExtension string `json:"fileExtension,omitempty"`
Size int64 `json:"size"`
ModTime int64 `json:"modTime"` // Unix timestamp
MimeType string `json:"mimeType,omitempty"`
Kind string `json:"kind,omitempty"` // image / video / audio / other
Image *ImageInfo `json:"image,omitempty"`
AV *AVProbeOutput `json:"av,omitempty"`
}
FileMetadata 为统一元数据输出(基础信息 + 可选 image/av)
type GetRecentLoginLocationsFunc ¶
GetRecentLoginLocationsFunc 获取最近登录位置的函数类型
type IPGeolocationResponse ¶
type IPGeolocationResponse struct {
Country string `json:"country"`
CountryCode string `json:"countryCode"`
Region string `json:"region"`
City string `json:"city"`
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
Timezone string `json:"timezone"`
ISP string `json:"isp"`
Org string `json:"org"`
AS string `json:"as"`
Query string `json:"query"`
Status string `json:"status"`
Message string `json:"message"`
}
IPGeolocationResponse IP地理位置API响应(ip-api格式)
type IPLocationResponse ¶
IPLocationResponse IP地理位置查询响应结构(pconline格式)
type IPLocationService ¶
type IPLocationService struct {
// contains filtered or unexported fields
}
IPLocationService IP地理位置服务
func NewIPLocationService ¶
func NewIPLocationService(logger *zap.Logger) *IPLocationService
NewIPLocationService 创建IP地理位置服务
func NewIPLocationServiceWithPconline ¶
func NewIPLocationServiceWithPconline(logger *zap.Logger) *IPLocationService
NewIPLocationServiceWithPconline 创建使用pconline API的IP地理位置服务(国内IP更准确)
func (*IPLocationService) GetLocation ¶
func (ils *IPLocationService) GetLocation(ip string) (country, city, location string, err error)
GetLocation 获取IP地理位置(返回国家、城市、完整位置字符串)
type ImageInfo ¶
type ImageInfo struct {
Width int `json:"width"`
Height int `json:"height"`
Format string `json:"format"`
ColorModel string `json:"colorModel"`
BitsPerPixel int `json:"bitsPerPixel,omitempty"`
Channels int `json:"channels,omitempty"`
HasTransparency bool `json:"hasTransparency,omitempty"`
}
ImageInfo 表示图片元数据(仅图片维度)
type LoginSecurityManager ¶
type LoginSecurityManager struct {
// contains filtered or unexported fields
}
LoginSecurityManager 登录安全管理器
var GlobalLoginSecurityManager *LoginSecurityManager
GlobalLoginSecurityManager 全局登录安全管理器
func NewLoginSecurityManager ¶
func NewLoginSecurityManager(logger *zap.Logger) *LoginSecurityManager
NewLoginSecurityManager 创建登录安全管理器
func (*LoginSecurityManager) CheckAccountLock ¶
func (lsm *LoginSecurityManager) CheckAccountLock(db *gorm.DB, email string, userID uint, checkFunc CheckAccountLockFunc) error
CheckAccountLock 检查账号是否被锁定
func (*LoginSecurityManager) CheckIPRateLimit ¶
func (lsm *LoginSecurityManager) CheckIPRateLimit(ip string) error
CheckIPRateLimit 检查IP登录限流
func (*LoginSecurityManager) CheckPasswordLoginLimit ¶
func (lsm *LoginSecurityManager) CheckPasswordLoginLimit(db *gorm.DB, userID uint, email string, checkFunc CheckPasswordLoginLimitFunc) (bool, error)
CheckPasswordLoginLimit 检查密码登录次数限制
func (*LoginSecurityManager) CheckProxyIP ¶
func (lsm *LoginSecurityManager) CheckProxyIP(ip string) (bool, error)
CheckProxyIP 检查是否为代理IP(简单检测)
func (*LoginSecurityManager) ClearFailedLoginCount ¶
func (lsm *LoginSecurityManager) ClearFailedLoginCount(email string)
ClearFailedLoginCount 清除失败登录计数(登录成功时调用)
func (*LoginSecurityManager) DetectSuspiciousLogin ¶
func (lsm *LoginSecurityManager) DetectSuspiciousLogin(db *gorm.DB, userID uint, currentIP, currentLocation, currentCountry string, getLocationsFunc GetRecentLoginLocationsFunc) (bool, error)
DetectSuspiciousLogin 检测可疑登录(异地登录)
func (*LoginSecurityManager) RecordFailedLogin ¶
func (lsm *LoginSecurityManager) RecordFailedLogin(db *gorm.DB, email string, userID uint, ipAddress string, recordFunc RecordFailedLoginFunc) error
RecordFailedLogin 记录失败登录
type MemoryLock ¶
type MemoryLock struct {
// contains filtered or unexported fields
}
MemoryLock 内存锁实现(单机版)
type MetadataService ¶
type MetadataService interface {
// GetFileMetadata 返回统一元数据(会自动尝试识别图片信息;不自动跑 ffprobe)
GetFileMetadata(filePath string) (*FileMetadata, error)
// GetAVMetadata 通过 ffprobe 获取音视频元数据(用于 ?avinfo=true)
GetAVMetadata(filePath string) (*AVProbeOutput, error)
}
MetadataService 定义元数据解析服务接口
func NewMetadataService ¶
func NewMetadataService() MetadataService
NewMetadataService 创建新的元数据解析服务实例
type RecordFailedLoginFunc ¶
RecordFailedLoginFunc 记录失败登录的函数类型
type RegistrationAttempt ¶
type RegistrationAttempt struct {
IP string
Email string
Timestamp time.Time
Success bool
Reason string
}
RegistrationAttempt 注册尝试记录
type RegistrationGuard ¶
type RegistrationGuard struct {
// contains filtered or unexported fields
}
RegistrationGuard 注册防护服务
var GlobalRegistrationGuard *RegistrationGuard
GlobalRegistrationGuard 全局注册防护服务实例
func NewRegistrationGuard ¶
func NewRegistrationGuard(logger *zap.Logger) *RegistrationGuard
NewRegistrationGuard 创建注册防护服务实例
func (*RegistrationGuard) AddIPToBlacklist ¶
func (rg *RegistrationGuard) AddIPToBlacklist(cidr string) error
AddIPToBlacklist 动态添加IP到黑名单
func (*RegistrationGuard) CheckFailedAttempts ¶
func (rg *RegistrationGuard) CheckFailedAttempts(ip string) error
CheckFailedAttempts 检查失败尝试次数
func (*RegistrationGuard) CheckIPRateLimit ¶
func (rg *RegistrationGuard) CheckIPRateLimit(ip string) error
CheckIPRateLimit 检查IP注册限流
func (*RegistrationGuard) CheckRegistrationAllowed ¶
func (rg *RegistrationGuard) CheckRegistrationAllowed(ip string, email string, password string) error
CheckRegistrationAllowed 综合检查是否允许注册
func (*RegistrationGuard) RecordRegistrationAttempt ¶
func (rg *RegistrationGuard) RecordRegistrationAttempt(ip string, email string, success bool, reason string)
RecordRegistrationAttempt 记录注册尝试
func (*RegistrationGuard) ValidateEmail ¶
func (rg *RegistrationGuard) ValidateEmail(email string) error
ValidateEmail 验证邮箱格式和域名
func (*RegistrationGuard) ValidateIP ¶
func (rg *RegistrationGuard) ValidateIP(ip string) error
ValidateIP 验证IP地址是否在黑名单中
func (*RegistrationGuard) ValidatePassword ¶
func (rg *RegistrationGuard) ValidatePassword(password string) error
ValidatePassword 验证密码强度
type SigHandler ¶
type SigHandler struct {
ID uint
Handler SignalHandler
}
type SigHandlerEvent ¶
type SigHandlerEvent struct {
EvType int
SignalName string
SigHandler SigHandler
}
type Signals ¶
type Signals struct {
// contains filtered or unexported fields
}
func NewSignals ¶
func NewSignals() *Signals