Documentation
¶
Index ¶
- Constants
- Variables
- func AcquireRegistrationLock(email string) (bool, error)
- func AddDuration(d time.Duration) int64
- func AesDecrypt(key, ciphertext []byte) (buf []byte, err error)
- func AesEncrypt(key, plaintext []byte) (buf []byte, err error)
- func BytesToString(b []byte) string
- func CalculateAge(birthday time.Time) int
- func CalculateFileHash(filePath string) (string, error)
- func CheckValue(db *gorm.DB, key, defaultValue, format string, autoload, public bool)
- func ComputeSampleByteCount(rate, depth, chans int) int
- func ConfigureConnectionPool(db *gorm.DB)
- func CopyFile(src, dst string) error
- func Difference[T comparable](slice1, slice2 []T) []T
- func EndOfDay(t time.Time) time.Time
- func EnsureDirectory(path string) error
- func ExtractKeyFromURL(url string) string
- func FileExists(path string) bool
- func GenerateID() string
- func GenerateRandomString(length int) string
- func GenerateSecureToken(length int) (string, error)
- func GetBoolEnv(key string) bool
- func GetBoolValue(db *gorm.DB, key string) bool
- func GetContentType(suffix string) (tp string)
- func GetCrc16(val int64) uint16
- func GetDeviceID(userAgent, ipAddress string) string
- func GetDistance(lon1, lat1, lon2, lat2 float64) float64
- func GetEnv(key string) string
- func GetFileExtension(filename string) string
- func GetFileSize(filePath string) (int64, error)
- func GetFileType(buf []byte) (fileType string)
- func GetFileTypeBySuffix(suffix string) int32
- func GetFloatEnv(key string) float64
- func GetIPLocation(ip string) (country, city, location string, err error)
- func GetIntEnv(key string) int64
- func GetIntValue(db *gorm.DB, key string, defaultVal int) int
- func GetRealAddressByIP(ip string) string
- func GetValue(db *gorm.DB, key string) string
- func InArray[T comparable](needle T, haystack []T) bool
- func InitConfigManager(cacheInstance cache.Cache)
- func InitDatabase(logWrite io.Writer, driver, dsn string) (*gorm.DB, error)
- func InitGlobalDistributedLock()
- func InitGlobalIPLocationService(logger *zap.Logger)
- func InitGlobalLoginSecurityManager(logger *zap.Logger, cacheInstance cache.Cache)
- func InitGlobalRegistrationGuard(logger *zap.Logger, cacheInstance cache.Cache)
- func Intersect[T comparable](slice1, slice2 []T) []T
- func IsDirectory(path string) bool
- func IsFile(path string) bool
- func IsInternalIP(ip string) bool
- func Join[T any](arg []T, str string) string
- func LoadAutoloads(db *gorm.DB)
- func LoadEnv(env string) error
- func LoadEnvs(objPtr any)
- func LookupEnv(key string) (value string, found bool)
- func MD5(str string) string
- func MakeMigrates(db *gorm.DB, insts []any) error
- func Merge[T any](slice1, slice2 []T) []T
- func MillisFromTime(t time.Time) int64
- func NormalizeFramePeriod(d string) time.Duration
- func NowUnix() int64
- func ParseUserAgent(userAgent string) (deviceType, os, browser string)
- func RC4Decrypt(str string, key []byte) string
- func RC4Encrypt(str string, key []byte) string
- func RandNumberText(n int) string
- func RandString(n int) string
- func RandText(n int) string
- func ReadFile(filename string) ([]byte, error)
- func ReleaseRegistrationLock(email string) error
- func RemoveDirectory(path string) error
- func RemoveEmoji(text string) string
- func RemoveEmojiFromJSON(jsonStr string) string
- func RemoveFile(path string) error
- func RenderJSON(c *gin.Context, code int, obj any)
- func SafeCall(f func() error, failHandle func(error)) 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 SanitizeValue(value interface{}) interface{}
- func SetValue(db *gorm.DB, key, value, format string, autoload, public bool)
- func SixteenMD5(str string) string
- func StartOfDay(t time.Time) time.Time
- func StringToBytes(s string) []byte
- func StructAsMap(form any, fields []string) (vals map[string]any)
- func TimeFromMillis(millis int64) time.Time
- func UnZlib(in []byte) (out []byte)
- func Unique[T comparable](slice []T) []T
- func ValidateDisplayName(name string) error
- func ValidateEmailFormat(email string) error
- func ValidateInput(input interface{}) error
- func ValidatePasswordFormat(password string) error
- func ValidateSQLInjection(input string) error
- func ValidateUserName(username string) error
- func ValidateXSS(input string) error
- func WriteFile(filename string, data []byte) error
- func WriteJSON(w http.ResponseWriter, obj any) error
- func Yesterday() time.Time
- func Zlib(in []byte) (out []byte)
- type AccountLockInfo
- type CarrotJSON
- type CarrotJsonBinding
- type CheckAccountLockFunc
- type CheckPasswordLoginLimitFunc
- type Config
- type ConfigManager
- type Decoder
- type DistributedLock
- type Encoder
- type Error
- type GetRecentLoginLocationsFunc
- type IPGeolocationResponse
- type IPLocationResponse
- type IPLocationService
- 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 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 SecureQueryBuilder
- func (sqb *SecureQueryBuilder) SafeCount(model interface{}) (int64, error)
- func (sqb *SecureQueryBuilder) SafeExists(model interface{}, conditions map[string]interface{}) (bool, error)
- func (sqb *SecureQueryBuilder) SafeFind(dest interface{}, conditions map[string]interface{}) error
- func (sqb *SecureQueryBuilder) SafeFirst(dest interface{}, conditions map[string]interface{}) error
- func (sqb *SecureQueryBuilder) SafeGroup(columns []string) *gorm.DB
- func (sqb *SecureQueryBuilder) SafeHaving(condition string, args ...interface{}) *gorm.DB
- func (sqb *SecureQueryBuilder) SafeOrder(column string, direction string) *gorm.DB
- func (sqb *SecureQueryBuilder) SafePaginate(page, pageSize int) *gorm.DB
- func (sqb *SecureQueryBuilder) SafeQuery(query string, args ...interface{}) *gorm.DB
- func (sqb *SecureQueryBuilder) SafeSelect(columns []string) *gorm.DB
- func (sqb *SecureQueryBuilder) SafeTransaction(fn func(*gorm.DB) error) error
- func (sqb *SecureQueryBuilder) SafeWhere(column string, operator string, value interface{}) *gorm.DB
- type Session
- type SessionManager
- 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" )
const ( FILE_TYPE_IMAGE int32 = 3 FILE_TYPE_FILE int32 = 4 FILE_TYPE_AUDIO int32 = 5 FILE_TYPE_MEDIA int32 = 6 )
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 ( Marshal = json.Marshal Unmarshal = json.Unmarshal MarshalIndent = json.MarshalIndent NewDecoder func(r io.Reader) Decoder = useJsonNewDecoder NewEncoder func(w io.Writer) Encoder = useJsonNewEncoder )
var EnableDecoderDisallowUnknownFields = false
EnableDecoderDisallowUnknownFields is used to call the DisallowUnknownFields method on the JSON Decoder instance. DisallowUnknownFields causes the Decoder to return an error when the destination is a struct and the input contains object keys which do not match any non-ignored, exported fields in the destination.
var EnableDecoderUseNumber = false
EnableDecoderUseNumber is used to call the UseNumber method on the JSON Decoder instance. UseNumber causes the Decoder to unmarshal a number into an any as a Number instead of as a float64.
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
var (
JsonContentType = []string{"application/json; charset=utf-8"}
)
Functions ¶
func AcquireRegistrationLock ¶
AcquireRegistrationLock 获取注册锁(防止并发注册同一邮箱)
func AddDuration ¶
func AesDecrypt ¶
func AesEncrypt ¶
func CalculateAge ¶
func CalculateFileHash ¶
CalculateFileHash 计算文件的SHA1哈希
func CheckValue ¶
func ComputeSampleByteCount ¶
ComputeSampleByteCount calculates bytes per millisecond for given audio parameters
func ConfigureConnectionPool ¶
ConfigureConnectionPool configure database connection pool
func Difference ¶
func Difference[T comparable](slice1, slice2 []T) []T
Difference get difference set slice1-intersection
func GenerateRandomString ¶
GenerateRandomString 生成指定长度的随机字符串
func GenerateSecureToken ¶
GenerateSecureToken generate a fixed-length secure token
func GetBoolEnv ¶
func GetContentType ¶
func GetDeviceID ¶
GetDeviceID 从User-Agent生成设备ID
func GetDistance ¶
Calculate distance between two points
func GetFileType ¶
func GetFileTypeBySuffix ¶
func GetFloatEnv ¶
func GetIPLocation ¶
GetIPLocation 获取IP地理位置(使用全局服务实例)
func GetRealAddressByIP ¶
GetRealAddressByIP 根据IP获取真实地址(兼容旧接口,返回完整地址字符串)
func InArray ¶
func InArray[T comparable](needle T, haystack []T) bool
InArray check if element is in array
func InitConfigManager ¶
InitConfigManager 初始化配置管理器
func InitGlobalDistributedLock ¶
func InitGlobalDistributedLock()
InitGlobalDistributedLock 初始化全局分布式锁
func InitGlobalIPLocationService ¶
InitGlobalIPLocationService 初始化全局IP地理位置服务
func InitGlobalLoginSecurityManager ¶
InitGlobalLoginSecurityManager 初始化全局登录安全管理器
func InitGlobalRegistrationGuard ¶
InitGlobalRegistrationGuard 初始化全局注册防护服务
func LoadAutoloads ¶
func MillisFromTime ¶
func NormalizeFramePeriod ¶
ValidateAndNormalizeDuration uses different validation logic with explicit bounds checking
func ParseUserAgent ¶
ParseUserAgent 解析User-Agent获取设备信息
func RC4Decrypt ¶
func RC4Encrypt ¶
func RandNumberText ¶
func RandString ¶
func ReleaseRegistrationLock ¶
ReleaseRegistrationLock 释放注册锁
func RemoveEmojiFromJSON ¶
removeEmojiFromJSON 从 JSON 字符串中移除 emoji(仅从字符串值中移除,保持 JSON 结构)
func SanitizeAndValidate ¶
SanitizeAndValidate 清理并验证输入
func SanitizePassword ¶
SanitizePassword 清理密码(保留空格,但去除首尾空格)
func SanitizeValue ¶
func SanitizeValue(value interface{}) interface{}
SanitizeValue sanitize value to prevent injection
func SixteenMD5 ¶
func TimeFromMillis ¶
func ValidateInput ¶
func ValidateInput(input interface{}) error
ValidateInput validate input parameters
func ValidatePasswordFormat ¶
ValidatePasswordFormat 验证密码格式
func ValidateSQLInjection ¶
ValidateSQLInjection 检查SQL注入风险
Types ¶
type AccountLockInfo ¶
AccountLockInfo 账号锁定信息
type CarrotJSON ¶
type CarrotJSON struct {
Data any
}
func (CarrotJSON) Render ¶
func (r CarrotJSON) Render(w http.ResponseWriter) error
Render (JSON) writes data with custom ContentType.
func (CarrotJSON) WriteContentType ¶
func (r CarrotJSON) WriteContentType(w http.ResponseWriter)
WriteContentType (JSON) writes JSON ContentType.
type CarrotJsonBinding ¶
type CarrotJsonBinding struct{}
func (CarrotJsonBinding) Name ¶
func (CarrotJsonBinding) Name() string
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 ConfigManager ¶
type ConfigManager struct {
// contains filtered or unexported fields
}
ConfigManager 配置管理器
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 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地理位置服务
var GlobalIPLocationService *IPLocationService
GlobalIPLocationService 全局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 LoginSecurityManager ¶
type LoginSecurityManager struct {
// contains filtered or unexported fields
}
LoginSecurityManager 登录安全管理器
var GlobalLoginSecurityManager *LoginSecurityManager
GlobalLoginSecurityManager 全局登录安全管理器
func NewLoginSecurityManager ¶
func NewLoginSecurityManager(logger *zap.Logger, cacheInstance cache.Cache) *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 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, cacheInstance cache.Cache) *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 SecureQueryBuilder ¶
SecureQueryBuilder secure query builder
func NewSecureQueryBuilder ¶
func NewSecureQueryBuilder(db *gorm.DB) *SecureQueryBuilder
NewSecureQueryBuilder create a secure query builder
func (*SecureQueryBuilder) SafeCount ¶
func (sqb *SecureQueryBuilder) SafeCount(model interface{}) (int64, error)
SafeCount secure count query
func (*SecureQueryBuilder) SafeExists ¶
func (sqb *SecureQueryBuilder) SafeExists(model interface{}, conditions map[string]interface{}) (bool, error)
SafeExists secure existence check
func (*SecureQueryBuilder) SafeFind ¶
func (sqb *SecureQueryBuilder) SafeFind(dest interface{}, conditions map[string]interface{}) error
SafeFind secure batch query
func (*SecureQueryBuilder) SafeFirst ¶
func (sqb *SecureQueryBuilder) SafeFirst(dest interface{}, conditions map[string]interface{}) error
SafeFirst secure first record query
func (*SecureQueryBuilder) SafeGroup ¶
func (sqb *SecureQueryBuilder) SafeGroup(columns []string) *gorm.DB
SafeGroup secure GROUP BY builder
func (*SecureQueryBuilder) SafeHaving ¶
func (sqb *SecureQueryBuilder) SafeHaving(condition string, args ...interface{}) *gorm.DB
SafeHaving secure HAVING condition builder
func (*SecureQueryBuilder) SafeOrder ¶
func (sqb *SecureQueryBuilder) SafeOrder(column string, direction string) *gorm.DB
SafeOrder secure ORDER BY builder
func (*SecureQueryBuilder) SafePaginate ¶
func (sqb *SecureQueryBuilder) SafePaginate(page, pageSize int) *gorm.DB
SafePaginate secure pagination query
func (*SecureQueryBuilder) SafeQuery ¶
func (sqb *SecureQueryBuilder) SafeQuery(query string, args ...interface{}) *gorm.DB
SafeQuery execute secure raw query
func (*SecureQueryBuilder) SafeSelect ¶
func (sqb *SecureQueryBuilder) SafeSelect(columns []string) *gorm.DB
SafeSelect secure SELECT field builder
func (*SecureQueryBuilder) SafeTransaction ¶
func (sqb *SecureQueryBuilder) SafeTransaction(fn func(*gorm.DB) error) error
SafeTransaction execute secure transaction
type Session ¶
type Session struct {
// Session ID
ID string
// Creation time
CreatedAt time.Time
// Last activity time
LastActivity time.Time
// Session data
Data map[string]interface{}
// contains filtered or unexported fields
}
Session represents a server-side session
func (*Session) GetCreatedAt ¶
GetCreatedAt returns the session creation time
func (*Session) GetLastActivity ¶
GetLastActivity returns the last activity time
func (*Session) UpdateActivity ¶
func (s *Session) UpdateActivity()
UpdateActivity updates the last activity time
type SessionManager ¶
type SessionManager struct {
// contains filtered or unexported fields
}
SessionManager manages server-side sessions
func NewSessionManager ¶
func NewSessionManager(expirySeconds int) *SessionManager
NewSessionManager creates a session manager
func (*SessionManager) CreateSession ¶
func (m *SessionManager) CreateSession() *Session
CreateSession creates a new session
func (*SessionManager) GetActiveSessions ¶
func (m *SessionManager) GetActiveSessions() []string
GetActiveSessions retrieves all active session IDs
func (*SessionManager) GetSession ¶
func (m *SessionManager) GetSession(id string) (*Session, bool)
GetSession retrieves a session
func (*SessionManager) TerminateSession ¶
func (m *SessionManager) TerminateSession(id string) bool
TerminateSession terminates a session
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
func (*Signals) Disconnect ¶
Source Files
¶
- configs.go
- dbs.go
- dbs_sqlite.go
- distributed_lock.go
- errors.go
- ip_location.go
- json.go
- login_security.go
- random.go
- registration_guard.go
- secure_query.go
- session.go
- signals.go
- utils.go
- utils_array.go
- utils_content_type.go
- utils_crc16.go
- utils_encrypt.go
- utils_file_type.go
- utils_files.go
- utils_geo.go
- utils_strings.go
- utils_time.go
- utils_zlib.go