mirror of
https://github.com/skyle1995/NetworkAuth.git
synced 2026-05-25 02:24:05 +08:00
Add classification annotations
This commit is contained in:
16
cmd/root.go
16
cmd/root.go
@@ -13,8 +13,16 @@ import (
|
||||
"gopkg.in/natefinch/lumberjack.v2"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 全局变量
|
||||
// ============================================================================
|
||||
|
||||
var cfgFile string
|
||||
|
||||
// ============================================================================
|
||||
// 命令定义
|
||||
// ============================================================================
|
||||
|
||||
// rootCmd 代表没有调用子命令时的基础命令
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "networkDev",
|
||||
@@ -29,6 +37,10 @@ var rootCmd = &cobra.Command{
|
||||
},
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 公共函数
|
||||
// ============================================================================
|
||||
|
||||
// Execute 添加所有子命令到根命令并设置适当的标志
|
||||
// 这由main.main()调用。只需要对rootCmd执行一次。
|
||||
func Execute() {
|
||||
@@ -45,6 +57,10 @@ func init() {
|
||||
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "配置文件路径 (默认为 config.json)")
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 私有函数
|
||||
// ============================================================================
|
||||
|
||||
// setupLogrusForNonHTTP 配置logrus用于非HTTP日志
|
||||
// 在加载配置文件之前进行基本的logrus设置
|
||||
func setupLogrusForNonHTTP() {
|
||||
|
||||
@@ -23,6 +23,10 @@ import (
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 命令定义
|
||||
// ============================================================================
|
||||
|
||||
// serverCmd 代表服务器命令
|
||||
var serverCmd = &cobra.Command{
|
||||
Use: "server",
|
||||
@@ -31,6 +35,10 @@ var serverCmd = &cobra.Command{
|
||||
Run: runServer,
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 初始化函数
|
||||
// ============================================================================
|
||||
|
||||
func init() {
|
||||
// 将服务器命令添加到根命令
|
||||
rootCmd.AddCommand(serverCmd)
|
||||
@@ -40,6 +48,10 @@ func init() {
|
||||
serverCmd.Flags().IntP("port", "p", 0, "服务器监听端口 (覆盖配置文件)")
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 主要函数
|
||||
// ============================================================================
|
||||
|
||||
// runServer 运行HTTP服务器
|
||||
func runServer(cmd *cobra.Command, args []string) {
|
||||
// 获取配置
|
||||
@@ -75,6 +87,10 @@ func runServer(cmd *cobra.Command, args []string) {
|
||||
startServer(server)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 辅助函数
|
||||
// ============================================================================
|
||||
|
||||
// getServerHost 获取服务器监听地址
|
||||
func getServerHost(cmd *cobra.Command) string {
|
||||
if host, _ := cmd.Flags().GetString("host"); host != "" {
|
||||
|
||||
@@ -11,6 +11,10 @@ import (
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 结构体定义
|
||||
// ============================================================================
|
||||
|
||||
// ServerConfig 服务器配置结构体
|
||||
// 包含服务器运行相关的配置信息
|
||||
type ServerConfig struct {
|
||||
@@ -93,6 +97,10 @@ type AppConfig struct {
|
||||
Security SecurityConfig `json:"security" mapstructure:"security"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 公共函数
|
||||
// ============================================================================
|
||||
|
||||
// GetDefaultAppConfig 获取默认应用配置
|
||||
func GetDefaultAppConfig() *AppConfig {
|
||||
return &AppConfig{
|
||||
|
||||
@@ -7,6 +7,10 @@ import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 公共函数
|
||||
// ============================================================================
|
||||
|
||||
// GenerateSecureJWTSecret 生成安全的JWT密钥
|
||||
// 生成64字节(512位)的随机密钥,使用base64编码
|
||||
func GenerateSecureJWTSecret() (string, error) {
|
||||
|
||||
@@ -13,6 +13,10 @@ import (
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 公共函数
|
||||
// ============================================================================
|
||||
|
||||
// ValidateConfig 验证配置
|
||||
func ValidateConfig() (*AppConfig, error) {
|
||||
var config AppConfig
|
||||
@@ -31,6 +35,10 @@ func ValidateConfig() (*AppConfig, error) {
|
||||
return &config, nil
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 私有函数
|
||||
// ============================================================================
|
||||
|
||||
// validateConfig 验证配置
|
||||
func validateConfig(config *AppConfig) error {
|
||||
// 验证服务器配置
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
package constants
|
||||
|
||||
// ============================================================================
|
||||
// 常量定义
|
||||
// ============================================================================
|
||||
|
||||
// 应用程序版本信息
|
||||
const (
|
||||
// AppVersion 应用程序版本号
|
||||
|
||||
@@ -13,9 +13,17 @@ import (
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 全局变量
|
||||
// ============================================================================
|
||||
|
||||
// 创建基础控制器实例
|
||||
var apiBaseController = controllers.NewBaseController()
|
||||
|
||||
// ============================================================================
|
||||
// 页面处理器
|
||||
// ============================================================================
|
||||
|
||||
// APIFragmentHandler 接口列表页面片段处理器
|
||||
func APIFragmentHandler(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "apis.html", gin.H{
|
||||
@@ -23,6 +31,10 @@ func APIFragmentHandler(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// API处理器
|
||||
// ============================================================================
|
||||
|
||||
// APIListHandler 接口列表API处理器
|
||||
func APIListHandler(c *gin.Context) {
|
||||
// 获取分页参数
|
||||
@@ -142,6 +154,10 @@ func APIListHandler(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, response)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 辅助函数
|
||||
// ============================================================================
|
||||
|
||||
// getAPIStatusName 获取API状态名称
|
||||
func getAPIStatusName(status int) string {
|
||||
switch status {
|
||||
@@ -238,7 +254,7 @@ func APIGetTypesHandler(c *gin.Context) {
|
||||
validTypes := []int{
|
||||
models.APITypeGetBulletin, models.APITypeGetUpdateUrl, models.APITypeCheckAppVersion, models.APITypeGetCardInfo,
|
||||
models.APITypeSingleLogin,
|
||||
models.APITypeUserLogin, models.APITypeUserRegin, models.APITypeUserRecharge, models.APITypeCardRegin,
|
||||
models.APITypeUserLogin, models.APITypeUserRegin, models.APITypeUserRecharge,
|
||||
models.APITypeLogOut,
|
||||
models.APITypeGetExpired, models.APITypeCheckUserStatus, models.APITypeGetAppData, models.APITypeGetVariable,
|
||||
models.APITypeUpdatePwd, models.APITypeMacChangeBind, models.APITypeIPChangeBind,
|
||||
|
||||
@@ -15,8 +15,16 @@ import (
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 全局变量
|
||||
// ============================================================================
|
||||
|
||||
var appBaseController = controllers.NewBaseController()
|
||||
|
||||
// ============================================================================
|
||||
// 页面处理器
|
||||
// ============================================================================
|
||||
|
||||
// AppsFragmentHandler 应用列表页面片段处理器
|
||||
func AppsFragmentHandler(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "apps.html", gin.H{
|
||||
@@ -24,6 +32,10 @@ func AppsFragmentHandler(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// API处理器
|
||||
// ============================================================================
|
||||
|
||||
// AppsListHandler 应用列表API处理器
|
||||
func AppsListHandler(c *gin.Context) {
|
||||
// 获取分页参数
|
||||
@@ -338,28 +350,7 @@ func AppCreateHandler(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 为应用创建所有默认接口
|
||||
defaultAPITypes := []int{
|
||||
models.APITypeGetBulletin, // 获取程序公告
|
||||
models.APITypeGetUpdateUrl, // 获取更新地址
|
||||
models.APITypeCheckAppVersion, // 检测最新版本
|
||||
models.APITypeGetCardInfo, // 获取卡密信息
|
||||
models.APITypeSingleLogin, // 卡密登录
|
||||
models.APITypeUserLogin, // 用户登录
|
||||
models.APITypeUserRegin, // 用户注册
|
||||
models.APITypeUserRecharge, // 用户充值
|
||||
models.APITypeCardRegin, // 卡密注册
|
||||
models.APITypeLogOut, // 退出登录
|
||||
models.APITypeGetExpired, // 获取到期时间
|
||||
models.APITypeCheckUserStatus, // 检测账号状态
|
||||
models.APITypeGetAppData, // 获取程序数据
|
||||
models.APITypeGetVariable, // 获取变量数据
|
||||
models.APITypeUpdatePwd, // 修改账号密码
|
||||
models.APITypeMacChangeBind, // 机器码转绑
|
||||
models.APITypeIPChangeBind, // IP转绑
|
||||
models.APITypeDisableUser, // 封停用户
|
||||
models.APITypeBlackUser, // 添加黑名单
|
||||
models.APITypeUserDeductedTime, // 扣除时间
|
||||
}
|
||||
defaultAPITypes := models.GetDefaultAPITypes()
|
||||
|
||||
// 批量创建默认接口
|
||||
for _, apiType := range defaultAPITypes {
|
||||
|
||||
@@ -16,9 +16,17 @@ import (
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 全局变量
|
||||
// ============================================================================
|
||||
|
||||
// 创建BaseController实例
|
||||
var authBaseController = controllers.NewBaseController()
|
||||
|
||||
// ============================================================================
|
||||
// 页面处理器
|
||||
// ============================================================================
|
||||
|
||||
// LoginPageHandler 管理员登录页渲染处理器
|
||||
// - 如果已登录则重定向到 /admin
|
||||
// - 否则渲染 web/template/admin/login.html 模板
|
||||
@@ -63,6 +71,10 @@ func LoginPageHandler(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "login.html", data)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// API处理器
|
||||
// ============================================================================
|
||||
|
||||
// LoginHandler 管理员登录接口
|
||||
// - 接收JSON: {username, password}
|
||||
// - 验证用户存在与密码正确性
|
||||
@@ -178,7 +190,11 @@ func LogoutHandler(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// clearInvalidJWTCookie 清理失效的JWT Cookie
|
||||
// ============================================================================
|
||||
// 辅助函数
|
||||
// ============================================================================
|
||||
|
||||
// clearInvalidJWTCookie 清理无效的JWT Cookie
|
||||
// - 统一的Cookie清理函数,确保一致性
|
||||
// - 在JWT校验失败时自动调用,提升安全性和用户体验
|
||||
func clearInvalidJWTCookie(c *gin.Context) {
|
||||
@@ -192,7 +208,11 @@ func getJWTSecret() []byte {
|
||||
return []byte(viper.GetString("security.jwt_secret"))
|
||||
}
|
||||
|
||||
// JWTClaims JWT载荷结构
|
||||
// ============================================================================
|
||||
// 结构体定义
|
||||
// ============================================================================
|
||||
|
||||
// JWTClaims JWT载荷结构体
|
||||
type JWTClaims struct {
|
||||
Username string `json:"username"`
|
||||
PasswordHash string `json:"password_hash"` // 密码哈希摘要,用于验证密码是否被修改
|
||||
|
||||
@@ -15,12 +15,20 @@ import (
|
||||
"github.com/mojocn/base64Captcha"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 全局变量
|
||||
// ============================================================================
|
||||
|
||||
// 创建基础控制器实例
|
||||
var captchaBaseController = controllers.NewBaseController()
|
||||
|
||||
// 全局验证码存储器
|
||||
var store = base64Captcha.DefaultMemStore
|
||||
|
||||
// ============================================================================
|
||||
// 辅助函数
|
||||
// ============================================================================
|
||||
|
||||
// secureRandomInt 生成安全的随机整数,范围 [0, max)
|
||||
func secureRandomInt(max int) (int, error) {
|
||||
n, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
|
||||
@@ -30,6 +38,10 @@ func secureRandomInt(max int) (int, error) {
|
||||
return int(n.Int64()), nil
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// API处理器
|
||||
// ============================================================================
|
||||
|
||||
// CaptchaHandler 生成验证码图片
|
||||
// GET /admin/captcha - 返回验证码图片
|
||||
func CaptchaHandler(c *gin.Context) {
|
||||
@@ -87,8 +99,6 @@ func CaptchaHandler(c *gin.Context) {
|
||||
c.Data(http.StatusOK, "image/png", imgData)
|
||||
}
|
||||
|
||||
|
||||
|
||||
// VerifyCaptcha 验证验证码
|
||||
// 这个函数将在登录处理中被调用
|
||||
// 支持大小写不敏感匹配
|
||||
|
||||
@@ -12,9 +12,17 @@ import (
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 全局变量
|
||||
// ============================================================================
|
||||
|
||||
// 创建基础控制器实例
|
||||
var functionBaseController = controllers.NewBaseController()
|
||||
|
||||
// ============================================================================
|
||||
// 页面处理器
|
||||
// ============================================================================
|
||||
|
||||
// FunctionFragmentHandler 公共函数列表页面片段处理器
|
||||
func FunctionFragmentHandler(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "functions.html", gin.H{
|
||||
@@ -22,6 +30,10 @@ func FunctionFragmentHandler(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// API处理器
|
||||
// ============================================================================
|
||||
|
||||
// FunctionListHandler 函数列表API处理器
|
||||
func FunctionListHandler(c *gin.Context) {
|
||||
// 获取分页参数
|
||||
|
||||
@@ -14,9 +14,17 @@ import (
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 全局变量
|
||||
// ============================================================================
|
||||
|
||||
// 创建基础控制器实例
|
||||
var handlersBaseController = controllers.NewBaseController()
|
||||
|
||||
// ============================================================================
|
||||
// 辅助函数
|
||||
// ============================================================================
|
||||
|
||||
// formatDBType 格式化数据库类型显示
|
||||
// 将配置文件中的小写类型转换为友好的显示格式
|
||||
func formatDBType(dbType string) string {
|
||||
@@ -34,6 +42,10 @@ func formatDBType(dbType string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 页面处理器
|
||||
// ============================================================================
|
||||
|
||||
// AdminIndexHandler 后台首页处理器/admin 与 /admin/ 根路径入口
|
||||
// - 未登录:重定向到 /admin/login
|
||||
// - 已登录:渲染后台布局页(或重定向到 /admin/layout)
|
||||
@@ -107,6 +119,10 @@ func DashboardFragmentHandler(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "dashboard.html", data)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// API处理器
|
||||
// ============================================================================
|
||||
|
||||
// SystemInfoHandler 系统信息API接口
|
||||
// - 返回系统运行状态的JSON数据,用于前端定时刷新
|
||||
func SystemInfoHandler(c *gin.Context) {
|
||||
|
||||
@@ -12,15 +12,27 @@ import (
|
||||
"networkDev/utils"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 全局变量
|
||||
// ============================================================================
|
||||
|
||||
// 创建基础控制器实例
|
||||
var settingsBaseController = controllers.NewBaseController()
|
||||
|
||||
// ============================================================================
|
||||
// 页面处理器
|
||||
// ============================================================================
|
||||
|
||||
// SettingsFragmentHandler 设置片段渲染
|
||||
// - 渲染设置表单(通过前端JS调用API加载/保存)
|
||||
func SettingsFragmentHandler(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "settings.html", gin.H{})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// API处理器
|
||||
// ============================================================================
|
||||
|
||||
// SettingsQueryHandler 设置查询API
|
||||
// - 返回所有设置项的 name:value 映射
|
||||
func SettingsQueryHandler(c *gin.Context) {
|
||||
|
||||
@@ -10,15 +10,27 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 全局变量
|
||||
// ============================================================================
|
||||
|
||||
// 创建基础控制器实例
|
||||
var baseController = controllers.NewBaseController()
|
||||
|
||||
// ============================================================================
|
||||
// 页面处理器
|
||||
// ============================================================================
|
||||
|
||||
// UserFragmentHandler 个人资料片段渲染
|
||||
// - 渲染个人资料与修改密码表单
|
||||
func UserFragmentHandler(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "user.html", gin.H{})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// API处理器
|
||||
// ============================================================================
|
||||
|
||||
// UserProfileQueryHandler 获取当前登录管理员的用户名
|
||||
// - 返回 JSON: {username}
|
||||
// - 直接从JWT获取用户名信息
|
||||
|
||||
@@ -12,9 +12,17 @@ import (
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 全局变量
|
||||
// ============================================================================
|
||||
|
||||
// 创建基础控制器实例
|
||||
var variableBaseController = controllers.NewBaseController()
|
||||
|
||||
// ============================================================================
|
||||
// 页面处理器
|
||||
// ============================================================================
|
||||
|
||||
// VariableFragmentHandler 公共变量列表页面片段处理器
|
||||
func VariableFragmentHandler(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "variables.html", gin.H{
|
||||
@@ -22,6 +30,10 @@ func VariableFragmentHandler(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// API处理器
|
||||
// ============================================================================
|
||||
|
||||
// VariableListHandler 变量列表API处理器
|
||||
func VariableListHandler(c *gin.Context) {
|
||||
// 获取分页参数
|
||||
|
||||
@@ -10,14 +10,26 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 结构体定义
|
||||
// ============================================================================
|
||||
|
||||
// BaseController 基础控制器结构体
|
||||
type BaseController struct{}
|
||||
|
||||
// ============================================================================
|
||||
// 构造函数
|
||||
// ============================================================================
|
||||
|
||||
// NewBaseController 创建基础控制器实例
|
||||
func NewBaseController() *BaseController {
|
||||
return &BaseController{}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 数据库相关方法
|
||||
// ============================================================================
|
||||
|
||||
// GetDB 获取数据库连接,统一错误处理
|
||||
func (bc *BaseController) GetDB(c *gin.Context) (*gorm.DB, bool) {
|
||||
db, err := database.GetDB()
|
||||
@@ -28,6 +40,10 @@ func (bc *BaseController) GetDB(c *gin.Context) (*gorm.DB, bool) {
|
||||
return db, true
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 错误处理方法
|
||||
// ============================================================================
|
||||
|
||||
// HandleDatabaseError 统一处理数据库连接错误
|
||||
func (bc *BaseController) HandleDatabaseError(c *gin.Context, err error) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
@@ -64,6 +80,10 @@ func (bc *BaseController) HandleInternalError(c *gin.Context, message string, er
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 成功响应方法
|
||||
// ============================================================================
|
||||
|
||||
// HandleSuccess 统一处理成功响应
|
||||
func (bc *BaseController) HandleSuccess(c *gin.Context, message string, data interface{}) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
@@ -82,6 +102,10 @@ func (bc *BaseController) HandleCreated(c *gin.Context, message string, data int
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 辅助方法
|
||||
// ============================================================================
|
||||
|
||||
// ValidateRequired 验证必填字段
|
||||
func (bc *BaseController) ValidateRequired(c *gin.Context, fields map[string]interface{}) bool {
|
||||
for fieldName, fieldValue := range fields {
|
||||
|
||||
@@ -10,8 +10,16 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 全局变量
|
||||
// ============================================================================
|
||||
|
||||
var homeBaseController = controllers.NewBaseController()
|
||||
|
||||
// ============================================================================
|
||||
// 辅助函数
|
||||
// ============================================================================
|
||||
|
||||
// getSettingValue 获取配置值,优先从数据库获取,不存在时使用默认值
|
||||
func getSettingValue(settingName string, defaultValue string, db *gorm.DB) string {
|
||||
if setting, err := services.FindSettingByName(settingName, db); err == nil {
|
||||
@@ -20,6 +28,10 @@ func getSettingValue(settingName string, defaultValue string, db *gorm.DB) strin
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 页面处理器
|
||||
// ============================================================================
|
||||
|
||||
// RootHandler 主页处理器
|
||||
func RootHandler(c *gin.Context) {
|
||||
// 获取数据库连接
|
||||
|
||||
@@ -12,6 +12,10 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 全局变量
|
||||
// ============================================================================
|
||||
|
||||
var (
|
||||
// dbInstance 全局 *gorm.DB 实例,使用单例确保全局复用
|
||||
dbInstance *gorm.DB
|
||||
@@ -19,6 +23,10 @@ var (
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 公共函数
|
||||
// ============================================================================
|
||||
|
||||
// Init 初始化数据库连接(根据配置自动选择驱动)
|
||||
// - 默认使用 SQLite(github.com/glebarez/sqlite)
|
||||
// - 生产环境支持 MySQL(gorm.io/driver/mysql)
|
||||
@@ -72,6 +80,10 @@ func GetDB() (*gorm.DB, error) {
|
||||
return Init()
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 私有函数
|
||||
// ============================================================================
|
||||
|
||||
// initSQLite 初始化 SQLite 数据库
|
||||
// 使用 viper 中的 database.sqlite.path 作为数据库文件路径
|
||||
func initSQLite() error {
|
||||
|
||||
@@ -9,6 +9,10 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 公共函数
|
||||
// ============================================================================
|
||||
|
||||
// AutoMigrate 自动迁移数据库模型
|
||||
// - 会确保必要的数据表结构存在
|
||||
// - 不会破坏已有数据
|
||||
@@ -38,6 +42,10 @@ func AutoMigrate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 私有函数
|
||||
// ============================================================================
|
||||
|
||||
// ensureVerificationCodeType 确保tasks.verification_code字段类型为LONGTEXT以支持大图片数据
|
||||
// 中文注释:检查并修改verification_code字段类型,支持Base64编码的大图片数据存储
|
||||
func ensureVerificationCodeType(db *gorm.DB) error {
|
||||
|
||||
@@ -8,6 +8,10 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 公共函数
|
||||
// ============================================================================
|
||||
|
||||
// SeedDefaultSettings 初始化默认系统设置
|
||||
// - 检查各项设置是否已存在,如不存在则创建默认值
|
||||
// - 包含站点基本信息、SEO设置等常用配置项
|
||||
@@ -120,7 +124,7 @@ func SeedDefaultSettings() error {
|
||||
logrus.WithError(err).WithField("name", setting.Name).Error("创建默认设置失败")
|
||||
return err
|
||||
}
|
||||
logrus.WithField("name", setting.Name).WithField("value", setting.Value).Info("创建默认设置项")
|
||||
logrus.WithField("name", setting.Name).WithField("value", setting.Value).Debug("创建默认设置项")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,6 +137,10 @@ func SeedDefaultSettings() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 私有函数
|
||||
// ============================================================================
|
||||
|
||||
// initDefaultAdmin 初始化默认管理员账号
|
||||
// 如果admin_password为空,则生成默认密码admin123的哈希值
|
||||
func initDefaultAdmin(db *gorm.DB) error {
|
||||
|
||||
@@ -7,6 +7,10 @@ import (
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 结构体定义
|
||||
// ============================================================================
|
||||
|
||||
// DevModeConfig 开发模式配置
|
||||
type DevModeConfig struct {
|
||||
// 是否启用模板热重载
|
||||
@@ -19,6 +23,10 @@ type DevModeConfig struct {
|
||||
EnableDebugLog bool
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 中间件函数
|
||||
// ============================================================================
|
||||
|
||||
// DevModeMiddleware 开发模式中间件
|
||||
// 统一管理所有开发模式相关的功能
|
||||
func DevModeMiddleware(engine *gin.Engine) gin.HandlerFunc {
|
||||
@@ -45,6 +53,10 @@ func DevModeMiddleware(engine *gin.Engine) gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 公共函数
|
||||
// ============================================================================
|
||||
|
||||
// IsDevMode 检查是否为开发模式
|
||||
func IsDevMode() bool {
|
||||
return viper.GetBool("server.dev_mode")
|
||||
@@ -92,6 +104,10 @@ func ShouldSkipCaptcha(c *gin.Context) bool {
|
||||
return config.SkipCaptcha
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 私有函数
|
||||
// ============================================================================
|
||||
|
||||
// reloadTemplates 重新加载模板(内部函数)
|
||||
func reloadTemplates(engine *gin.Engine) {
|
||||
if tmpl, err := web.ParseTemplates(); err == nil {
|
||||
|
||||
@@ -8,12 +8,20 @@ import (
|
||||
"networkDev/utils/logger"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 结构体定义
|
||||
// ============================================================================
|
||||
|
||||
// LoggingMiddleware 日志记录中间件结构体
|
||||
// 用于记录HTTP请求的详细信息,包括方法、路径、状态码和响应时间
|
||||
type LoggingMiddleware struct {
|
||||
logger *logger.Logger
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 构造函数
|
||||
// ============================================================================
|
||||
|
||||
// NewLoggingMiddleware 创建新的日志记录中间件实例
|
||||
func NewLoggingMiddleware(logger *logger.Logger) *LoggingMiddleware {
|
||||
return &LoggingMiddleware{
|
||||
@@ -21,6 +29,10 @@ func NewLoggingMiddleware(logger *logger.Logger) *LoggingMiddleware {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 中间件函数
|
||||
// ============================================================================
|
||||
|
||||
// Handler 返回Gin中间件函数,用于记录HTTP请求日志
|
||||
// 记录格式遵循Apache Common Log Format
|
||||
func (lm *LoggingMiddleware) Handler() gin.HandlerFunc {
|
||||
@@ -51,6 +63,10 @@ func (lm *LoggingMiddleware) Handler() gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 私有函数
|
||||
// ============================================================================
|
||||
|
||||
// getClientIP 获取客户端真实IP地址
|
||||
// 优先从X-Forwarded-For、X-Real-IP等头部获取,最后使用RemoteAddr
|
||||
func getClientIP(c *gin.Context) string {
|
||||
@@ -88,6 +104,10 @@ func getClientIP(c *gin.Context) string {
|
||||
return remoteAddr
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 公共函数
|
||||
// ============================================================================
|
||||
|
||||
// WrapHandler 创建Gin日志中间件
|
||||
// 使用全局日志记录器创建日志中间件
|
||||
func WrapHandler() gin.HandlerFunc {
|
||||
|
||||
339
models/api.go
339
models/api.go
@@ -8,11 +8,63 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 常量定义
|
||||
// ============================================================================
|
||||
|
||||
// API类型常量定义
|
||||
const (
|
||||
// 基础信息
|
||||
APITypeGetBulletin = 1 // 获取程序公告
|
||||
APITypeGetUpdateUrl = 2 // 获取更新地址
|
||||
APITypeCheckAppVersion = 3 // 检测最新版本
|
||||
APITypeGetCardInfo = 4 // 获取卡密信息
|
||||
|
||||
// 卡密相关
|
||||
APITypeSingleLogin = 10 // 卡密登录
|
||||
|
||||
// 账号管理
|
||||
APITypeUserLogin = 20 // 用户登录
|
||||
APITypeUserRegin = 21 // 用户注册
|
||||
APITypeUserRecharge = 22 // 用户充值
|
||||
|
||||
// 登出操作
|
||||
APITypeLogOut = 30 // 退出登录
|
||||
|
||||
// 状态查询
|
||||
APITypeGetExpired = 40 // 获取到期时间
|
||||
APITypeCheckUserStatus = 41 // 检测账号状态
|
||||
APITypeGetAppData = 42 // 获取程序数据
|
||||
APITypeGetVariable = 43 // 获取变量数据
|
||||
APITypeExecuteFunction = 44 // 执行远程函数
|
||||
|
||||
// 用户操作
|
||||
APITypeUpdatePwd = 50 // 修改账号密码
|
||||
APITypeMacChangeBind = 51 // 机器码转绑
|
||||
APITypeIPChangeBind = 52 // IP转绑
|
||||
|
||||
// 风控操作
|
||||
APITypeDisableUser = 60 // 封停用户
|
||||
APITypeBlackUser = 61 // 添加黑名单
|
||||
APITypeUserDeductedTime = 62 // 扣除时间
|
||||
)
|
||||
|
||||
// 算法类型常量
|
||||
const (
|
||||
AlgorithmNone = 0 // 不加密
|
||||
AlgorithmRC4 = 1 // RC4
|
||||
AlgorithmRSA = 2 // RSA
|
||||
AlgorithmRSADynamic = 3 // RSA(动态)
|
||||
AlgorithmEasy = 4 // 易加密
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 结构体定义
|
||||
// ============================================================================
|
||||
|
||||
// API 接口表模型
|
||||
// 用于管理API接口的配置信息
|
||||
// 包含加密算法配置、密钥管理等功能
|
||||
// 支持多种加密算法:不加密、RC4、RSA、RSA(动态)
|
||||
|
||||
// CreatedAt/UpdatedAt 由 GORM 自动维护
|
||||
type API struct {
|
||||
// ID:主键,自增
|
||||
ID uint `gorm:"primaryKey;comment:API接口ID,自增主键" json:"id"`
|
||||
@@ -54,6 +106,10 @@ type API struct {
|
||||
UpdatedAt time.Time `gorm:"comment:更新时间" json:"updated_at"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 结构体方法
|
||||
// ============================================================================
|
||||
|
||||
// BeforeCreate 在创建记录前自动生成UUID
|
||||
func (api *API) BeforeCreate(tx *gorm.DB) error {
|
||||
if api.UUID == "" {
|
||||
@@ -67,51 +123,9 @@ func (API) TableName() string {
|
||||
return "apis"
|
||||
}
|
||||
|
||||
// API类型常量定义
|
||||
const (
|
||||
// 基础信息获取类API
|
||||
APITypeGetBulletin = 1 // 获取程序公告
|
||||
APITypeGetUpdateUrl = 2 // 获取更新地址
|
||||
APITypeCheckAppVersion = 3 // 检测最新版本
|
||||
APITypeGetCardInfo = 4 // 获取卡密信息
|
||||
|
||||
// 登录相关API
|
||||
APITypeSingleLogin = 10 // 卡密登录
|
||||
|
||||
// 用户账号管理API
|
||||
APITypeUserLogin = 20 // 用户登录
|
||||
APITypeUserRegin = 21 // 用户注册
|
||||
APITypeUserRecharge = 22 // 用户充值
|
||||
APITypeCardRegin = 23 // 卡密注册
|
||||
|
||||
// 登出API
|
||||
APITypeLogOut = 30 // 退出登录
|
||||
|
||||
// 用户状态查询API
|
||||
APITypeGetExpired = 40 // 获取到期时间
|
||||
APITypeCheckUserStatus = 41 // 检测账号状态
|
||||
APITypeGetAppData = 42 // 获取程序数据
|
||||
APITypeGetVariable = 43 // 获取变量数据
|
||||
|
||||
// 用户操作API
|
||||
APITypeUpdatePwd = 50 // 修改账号密码
|
||||
APITypeMacChangeBind = 51 // 机器码转绑
|
||||
APITypeIPChangeBind = 52 // IP转绑
|
||||
|
||||
// 管理员操作API
|
||||
APITypeDisableUser = 60 // 封停用户
|
||||
APITypeBlackUser = 61 // 添加黑名单
|
||||
APITypeUserDeductedTime = 62 // 扣除时间
|
||||
)
|
||||
|
||||
// 算法类型常量
|
||||
const (
|
||||
AlgorithmNone = 0 // 不加密
|
||||
AlgorithmRC4 = 1 // RC4
|
||||
AlgorithmRSA = 2 // RSA
|
||||
AlgorithmRSADynamic = 3 // RSA(动态)
|
||||
AlgorithmEasy = 4 // 易加密
|
||||
)
|
||||
// ============================================================================
|
||||
// 独立函数
|
||||
// ============================================================================
|
||||
|
||||
// GetAlgorithmName 获取算法名称
|
||||
func GetAlgorithmName(algorithm int) string {
|
||||
@@ -131,84 +145,134 @@ func GetAlgorithmName(algorithm int) string {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 基础结构体定义
|
||||
// ============================================================================
|
||||
|
||||
// APITypeInfo 接口类型信息
|
||||
type APITypeInfo struct {
|
||||
Type int `json:"type"` // 接口类型
|
||||
Name string `json:"name"` // 接口名称
|
||||
}
|
||||
|
||||
// APICategoryInfo 接口分类信息
|
||||
type APICategoryInfo struct {
|
||||
Name string `json:"name"` // 分类名称
|
||||
Types []APITypeInfo `json:"types"` // 该分类下的接口类型列表
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 核心功能函数
|
||||
// ============================================================================
|
||||
|
||||
// GetAPITypes 获取API接口类型,支持按分类返回或返回完整列表
|
||||
// categorized: true=按分类返回[]APICategoryInfo, false=返回完整列表[]int
|
||||
func GetAPITypes(categorized bool) interface{} {
|
||||
// 层次化的接口类型组织结构
|
||||
apiCategories := []APICategoryInfo{
|
||||
{
|
||||
Name: "基础信息",
|
||||
Types: []APITypeInfo{
|
||||
{Type: APITypeGetBulletin, Name: "获取程序公告"},
|
||||
{Type: APITypeGetUpdateUrl, Name: "获取更新地址"},
|
||||
{Type: APITypeCheckAppVersion, Name: "检测最新版本"},
|
||||
{Type: APITypeGetCardInfo, Name: "获取卡密信息"},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "卡密相关",
|
||||
Types: []APITypeInfo{
|
||||
{Type: APITypeSingleLogin, Name: "卡密登录"},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "账号管理",
|
||||
Types: []APITypeInfo{
|
||||
{Type: APITypeUserLogin, Name: "用户登录"},
|
||||
{Type: APITypeUserRegin, Name: "用户注册"},
|
||||
{Type: APITypeUserRecharge, Name: "用户充值"},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "登出操作",
|
||||
Types: []APITypeInfo{
|
||||
{Type: APITypeLogOut, Name: "退出登录"},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "状态查询",
|
||||
Types: []APITypeInfo{
|
||||
{Type: APITypeGetExpired, Name: "获取到期时间"},
|
||||
{Type: APITypeCheckUserStatus, Name: "检测账号状态"},
|
||||
{Type: APITypeGetAppData, Name: "获取程序数据"},
|
||||
{Type: APITypeGetVariable, Name: "获取变量数据"},
|
||||
{Type: APITypeExecuteFunction, Name: "执行远程函数"},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "用户操作",
|
||||
Types: []APITypeInfo{
|
||||
{Type: APITypeUpdatePwd, Name: "修改账号密码"},
|
||||
{Type: APITypeMacChangeBind, Name: "机器码转绑"},
|
||||
{Type: APITypeIPChangeBind, Name: "IP转绑"},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "风控操作",
|
||||
Types: []APITypeInfo{
|
||||
{Type: APITypeDisableUser, Name: "封停用户"},
|
||||
{Type: APITypeBlackUser, Name: "添加黑名单"},
|
||||
{Type: APITypeUserDeductedTime, Name: "扣除时间"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if categorized {
|
||||
// 返回层次化的分类结构
|
||||
return apiCategories
|
||||
}
|
||||
|
||||
// 返回所有接口类型的扁平列表
|
||||
var allTypes []int
|
||||
for _, category := range apiCategories {
|
||||
for _, typeInfo := range category.Types {
|
||||
allTypes = append(allTypes, typeInfo.Type)
|
||||
}
|
||||
}
|
||||
return allTypes
|
||||
}
|
||||
|
||||
// GetAPITypeName 获取API类型名称
|
||||
// 通过调用GetAPITypes函数来获取名称,避免重复维护数据
|
||||
func GetAPITypeName(apiType int) string {
|
||||
// 获取分类化的API类型数据
|
||||
categories := GetAPITypes(true).([]APICategoryInfo)
|
||||
|
||||
// 遍历所有分类和类型,查找匹配的API类型
|
||||
for _, category := range categories {
|
||||
for _, typeInfo := range category.Types {
|
||||
if typeInfo.Type == apiType {
|
||||
return typeInfo.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 如果没有找到匹配的类型,返回默认值
|
||||
return "未知API类型"
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 验证函数
|
||||
// ============================================================================
|
||||
|
||||
// IsValidAlgorithm 验证算法类型是否有效
|
||||
func IsValidAlgorithm(algorithm int) bool {
|
||||
return algorithm >= AlgorithmNone && algorithm <= AlgorithmEasy
|
||||
}
|
||||
|
||||
// GetAPITypeName 获取API类型名称
|
||||
func GetAPITypeName(apiType int) string {
|
||||
switch apiType {
|
||||
// 基础信息获取类API
|
||||
case APITypeGetBulletin:
|
||||
return "获取程序公告"
|
||||
case APITypeGetUpdateUrl:
|
||||
return "获取更新地址"
|
||||
case APITypeCheckAppVersion:
|
||||
return "检测最新版本"
|
||||
case APITypeGetCardInfo:
|
||||
return "获取卡密信息"
|
||||
|
||||
// 登录相关API
|
||||
case APITypeSingleLogin:
|
||||
return "卡密登录"
|
||||
|
||||
// 用户账号管理API
|
||||
case APITypeUserLogin:
|
||||
return "用户登录"
|
||||
case APITypeUserRegin:
|
||||
return "用户注册"
|
||||
case APITypeUserRecharge:
|
||||
return "用户充值"
|
||||
case APITypeCardRegin:
|
||||
return "卡密注册"
|
||||
|
||||
// 登出API
|
||||
case APITypeLogOut:
|
||||
return "退出登录"
|
||||
|
||||
// 用户状态查询API
|
||||
case APITypeGetExpired:
|
||||
return "获取到期时间"
|
||||
case APITypeCheckUserStatus:
|
||||
return "检测账号状态"
|
||||
case APITypeGetAppData:
|
||||
return "获取程序数据"
|
||||
case APITypeGetVariable:
|
||||
return "获取变量数据"
|
||||
|
||||
// 用户操作API
|
||||
case APITypeUpdatePwd:
|
||||
return "修改账号密码"
|
||||
case APITypeMacChangeBind:
|
||||
return "机器码转绑"
|
||||
case APITypeIPChangeBind:
|
||||
return "IP转绑"
|
||||
|
||||
// 管理员操作API
|
||||
case APITypeDisableUser:
|
||||
return "封停用户"
|
||||
case APITypeBlackUser:
|
||||
return "添加黑名单"
|
||||
case APITypeUserDeductedTime:
|
||||
return "扣除时间"
|
||||
|
||||
default:
|
||||
return "未知API类型"
|
||||
}
|
||||
}
|
||||
|
||||
// IsValidAPIType 验证API类型是否有效
|
||||
func IsValidAPIType(apiType int) bool {
|
||||
validTypes := []int{
|
||||
APITypeGetBulletin, APITypeGetUpdateUrl, APITypeCheckAppVersion, APITypeGetCardInfo,
|
||||
APITypeSingleLogin,
|
||||
APITypeUserLogin, APITypeUserRegin, APITypeUserRecharge, APITypeCardRegin,
|
||||
APITypeLogOut,
|
||||
APITypeGetExpired, APITypeCheckUserStatus, APITypeGetAppData, APITypeGetVariable,
|
||||
APITypeUpdatePwd, APITypeMacChangeBind, APITypeIPChangeBind,
|
||||
APITypeDisableUser, APITypeBlackUser, APITypeUserDeductedTime,
|
||||
}
|
||||
validTypes := GetDefaultAPITypes()
|
||||
|
||||
for _, validType := range validTypes {
|
||||
if apiType == validType {
|
||||
@@ -218,15 +282,34 @@ func IsValidAPIType(apiType int) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// GetAPITypesByCategory 根据分类获取API类型列表
|
||||
// ============================================================================
|
||||
// 兼容性函数
|
||||
// ============================================================================
|
||||
|
||||
// GetDefaultAPITypes 获取默认创建的API接口类型列表(兼容性函数)
|
||||
func GetDefaultAPITypes() []int {
|
||||
return GetAPITypes(false).([]int)
|
||||
}
|
||||
|
||||
// GetAPITypesByCategory 根据分类获取API类型列表(兼容性函数)
|
||||
// 返回传统的 map[string][]int 格式以保持向后兼容
|
||||
func GetAPITypesByCategory() map[string][]int {
|
||||
return map[string][]int{
|
||||
"基础信息获取": {APITypeGetBulletin, APITypeGetUpdateUrl, APITypeCheckAppVersion, APITypeGetCardInfo},
|
||||
"登录相关": {APITypeSingleLogin},
|
||||
"用户账号管理": {APITypeUserLogin, APITypeUserRegin, APITypeUserRecharge, APITypeCardRegin},
|
||||
"登出": {APITypeLogOut},
|
||||
"用户状态查询": {APITypeGetExpired, APITypeCheckUserStatus, APITypeGetAppData, APITypeGetVariable},
|
||||
"用户操作": {APITypeUpdatePwd, APITypeMacChangeBind, APITypeIPChangeBind},
|
||||
"管理员操作": {APITypeDisableUser, APITypeBlackUser, APITypeUserDeductedTime},
|
||||
categories := GetAPITypes(true).([]APICategoryInfo)
|
||||
result := make(map[string][]int)
|
||||
|
||||
for _, category := range categories {
|
||||
var types []int
|
||||
for _, typeInfo := range category.Types {
|
||||
types = append(types, typeInfo.Type)
|
||||
}
|
||||
result[category.Name] = types
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// GetAPICategoriesInfo 获取完整的层次化分类信息
|
||||
// 返回新的 []APICategoryInfo 格式,包含完整的类型名称信息
|
||||
func GetAPICategoriesInfo() []APICategoryInfo {
|
||||
return GetAPITypes(true).([]APICategoryInfo)
|
||||
}
|
||||
|
||||
@@ -10,15 +10,13 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 结构体定义
|
||||
// ============================================================================
|
||||
|
||||
// App 应用表模型
|
||||
// 用于管理应用程序的基本信息
|
||||
// UUID 为应用的唯一标识符,自动生成
|
||||
// Status 为应用状态(1:启用 0:禁用),默认为1
|
||||
// Name 为应用名称
|
||||
// Secret 为应用密钥,用于API认证
|
||||
// Version 为应用版本号
|
||||
// CreatedAt/UpdatedAt 由 GORM 自动维护
|
||||
|
||||
type App struct {
|
||||
// ID:主键,自增,同时通过 json 标签保证前端接收为 id
|
||||
ID uint `gorm:"primaryKey;comment:应用ID,自增主键" json:"id"`
|
||||
@@ -107,6 +105,10 @@ type App struct {
|
||||
UpdatedAt time.Time `gorm:"comment:更新时间" json:"updated_at"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 结构体方法
|
||||
// ============================================================================
|
||||
|
||||
// BeforeCreate 在创建记录前自动生成UUID和密钥
|
||||
func (app *App) BeforeCreate(tx *gorm.DB) error {
|
||||
if app.UUID == "" {
|
||||
|
||||
@@ -9,14 +9,13 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 结构体定义
|
||||
// ============================================================================
|
||||
|
||||
// Function 函数表模型
|
||||
// 用于管理应用程序的函数代码
|
||||
// UUID 为函数的唯一标识符,自动生成并转换为大写
|
||||
// Alias 为函数别名,便于识别和管理
|
||||
// Code 为函数代码内容
|
||||
// Remark 为备注信息,用于描述函数用途
|
||||
// CreatedAt/UpdatedAt 由 GORM 自动维护
|
||||
|
||||
type Function struct {
|
||||
// ID:主键,自增
|
||||
ID uint `gorm:"primaryKey;comment:函数ID,自增主键" json:"id"`
|
||||
@@ -44,6 +43,10 @@ type Function struct {
|
||||
UpdatedAt time.Time `gorm:"comment:更新时间" json:"updated_at"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 结构体方法
|
||||
// ============================================================================
|
||||
|
||||
// BeforeCreate 在创建记录前自动生成UUID和Number
|
||||
func (function *Function) BeforeCreate(tx *gorm.DB) error {
|
||||
// 生成UUID
|
||||
|
||||
@@ -2,13 +2,13 @@ package models
|
||||
|
||||
import "time"
|
||||
|
||||
// ============================================================================
|
||||
// 结构体定义
|
||||
// ============================================================================
|
||||
|
||||
// Settings 系统设置表模型
|
||||
// 用于存储应用的配置参数
|
||||
// Name 为配置项名称,唯一索引
|
||||
// Value 为配置项的值
|
||||
// Description 为配置项描述说明
|
||||
// CreatedAt/UpdatedAt 由 GORM 自动维护
|
||||
|
||||
type Settings struct {
|
||||
ID uint `gorm:"primaryKey;comment:设置ID,自增主键"`
|
||||
Name string `gorm:"uniqueIndex;size:64;not null;comment:配置项名称,唯一索引"`
|
||||
|
||||
@@ -8,9 +8,13 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 结构体定义
|
||||
// ============================================================================
|
||||
|
||||
// User 用户表模型
|
||||
// 说明:PasswordSalt 使用 32 字节随机盐(以 16 进制存储为 64 个字符),因此列长度设置为 64
|
||||
// 注意:此表只存储普通用户,管理员账号存储在settings表中
|
||||
// 此表只存储普通用户,管理员账号存储在settings表中
|
||||
// CreatedAt/UpdatedAt 由 GORM 自动维护
|
||||
type User struct {
|
||||
ID uint `gorm:"primaryKey;comment:用户ID,自增主键"`
|
||||
UUID string `gorm:"uniqueIndex;size:36;not null;comment:用户的唯一标识符" json:"uuid"`
|
||||
@@ -21,6 +25,10 @@ type User struct {
|
||||
UpdatedAt time.Time `gorm:"comment:更新时间"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 结构体方法
|
||||
// ============================================================================
|
||||
|
||||
// BeforeCreate 在创建记录前自动生成UUID
|
||||
func (user *User) BeforeCreate(tx *gorm.DB) error {
|
||||
// 生成UUID
|
||||
|
||||
@@ -9,14 +9,13 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 结构体定义
|
||||
// ============================================================================
|
||||
|
||||
// Variable 变量表模型
|
||||
// 用于管理应用程序的变量数据
|
||||
// UUID 为变量的唯一标识符,自动生成并转换为大写
|
||||
// Alias 为变量别名,便于识别和管理
|
||||
// Data 为变量数据内容
|
||||
// Remark 为备注信息,用于描述变量用途
|
||||
// CreatedAt/UpdatedAt 由 GORM 自动维护
|
||||
|
||||
type Variable struct {
|
||||
// ID:主键,自增
|
||||
ID uint `gorm:"primaryKey;comment:变量ID,自增主键" json:"id"`
|
||||
@@ -44,6 +43,10 @@ type Variable struct {
|
||||
UpdatedAt time.Time `gorm:"comment:更新时间" json:"updated_at"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 结构体方法
|
||||
// ============================================================================
|
||||
|
||||
// BeforeCreate 在创建记录前自动生成UUID和Number
|
||||
func (variable *Variable) BeforeCreate(tx *gorm.DB) error {
|
||||
// 生成UUID
|
||||
|
||||
@@ -7,6 +7,10 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 路由注册函数
|
||||
// ============================================================================
|
||||
|
||||
// RegisterAdminRoutes 注册管理员后台相关路由
|
||||
// - /admin/login: 支持GET渲染登录页、POST提交登录
|
||||
// - /admin/logout: 管理员退出登录
|
||||
|
||||
@@ -6,6 +6,10 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 路由注册函数
|
||||
// ============================================================================
|
||||
|
||||
// RegisterHomeRoutes 注册主页路由
|
||||
// 只包含根路径,用于主页功能
|
||||
func RegisterHomeRoutes(router *gin.Engine) {
|
||||
|
||||
@@ -9,6 +9,10 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 公共函数
|
||||
// ============================================================================
|
||||
|
||||
// RegisterRoutes 聚合注册所有路由
|
||||
func RegisterRoutes(router *gin.Engine) {
|
||||
registerStaticRoutes(router)
|
||||
@@ -18,6 +22,10 @@ func RegisterRoutes(router *gin.Engine) {
|
||||
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 私有函数
|
||||
// ============================================================================
|
||||
|
||||
// registerStaticRoutes 注册静态资源路由
|
||||
// 静态资源服务,将 /static/ 和 /assets/ 映射到嵌入的文件系统
|
||||
func registerStaticRoutes(router *gin.Engine) {
|
||||
|
||||
@@ -10,6 +10,10 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 查询函数
|
||||
// ============================================================================
|
||||
|
||||
// FindSettingByName 根据名称查找设置
|
||||
// name: 设置名称
|
||||
// db: 数据库连接
|
||||
@@ -26,6 +30,10 @@ func FindSettingByName(name string, db *gorm.DB) (*models.Settings, error) {
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 更新函数
|
||||
// ============================================================================
|
||||
|
||||
// UpdateEntityByID 根据ID更新实体
|
||||
// model: 模型类型
|
||||
// id: 实体ID
|
||||
@@ -49,6 +57,10 @@ func BatchUpdateEntityStatus(model interface{}, ids []uint, status int, db *gorm
|
||||
return db.Model(model).Where("id IN ?", ids).Update("status", status).Error
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 统计函数
|
||||
// ============================================================================
|
||||
|
||||
// CountEntitiesByCondition 根据条件统计实体数量
|
||||
// model: 模型类型
|
||||
// condition: 查询条件
|
||||
@@ -61,6 +73,10 @@ func CountEntitiesByCondition(model interface{}, condition string, db *gorm.DB,
|
||||
return count, err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 通用查询函数
|
||||
// ============================================================================
|
||||
|
||||
// FindEntitiesByCondition 根据条件查找实体
|
||||
// model: 模型类型
|
||||
// result: 结果容器
|
||||
|
||||
@@ -9,15 +9,27 @@ import (
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 结构体定义
|
||||
// ============================================================================
|
||||
|
||||
// SettingsService 设置服务
|
||||
type SettingsService struct {
|
||||
mu sync.RWMutex
|
||||
cache map[string]string
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 全局变量
|
||||
// ============================================================================
|
||||
|
||||
var settingsService *SettingsService
|
||||
var settingsOnce sync.Once
|
||||
|
||||
// ============================================================================
|
||||
// 公共函数
|
||||
// ============================================================================
|
||||
|
||||
// GetSettingsService 获取设置服务单例
|
||||
func GetSettingsService() *SettingsService {
|
||||
settingsOnce.Do(func() {
|
||||
@@ -30,6 +42,10 @@ func GetSettingsService() *SettingsService {
|
||||
return settingsService
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 私有函数
|
||||
// ============================================================================
|
||||
|
||||
// loadAllSettings 从数据库加载所有设置到缓存
|
||||
func (s *SettingsService) loadAllSettings() {
|
||||
db, err := database.GetDB()
|
||||
|
||||
@@ -7,6 +7,10 @@ import (
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// Cookie创建函数
|
||||
// ============================================================================
|
||||
|
||||
// CreateSecureCookie 创建安全的Cookie
|
||||
// name: Cookie名称
|
||||
// value: Cookie值
|
||||
@@ -67,6 +71,10 @@ func CreateExpiredCookie(name string) *http.Cookie {
|
||||
return CreateSecureCookie(name, "", -1)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 配置函数
|
||||
// ============================================================================
|
||||
|
||||
// GetDefaultCookieMaxAge 获取默认Cookie过期时间
|
||||
func GetDefaultCookieMaxAge() int {
|
||||
maxAge := viper.GetInt("security.cookie.max_age")
|
||||
|
||||
@@ -15,6 +15,10 @@ import (
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 结构体定义
|
||||
// ============================================================================
|
||||
|
||||
// CryptoManager 加密管理器,提供高性能的加密解密服务
|
||||
type CryptoManager struct {
|
||||
key []byte
|
||||
@@ -23,9 +27,17 @@ type CryptoManager struct {
|
||||
inited bool
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 全局变量
|
||||
// ============================================================================
|
||||
|
||||
// 全局加密管理器实例
|
||||
var cryptoManager = &CryptoManager{}
|
||||
|
||||
// ============================================================================
|
||||
// 私有函数
|
||||
// ============================================================================
|
||||
|
||||
// initCrypto 初始化加密管理器
|
||||
// 缓存密钥和GCM实例,避免重复创建
|
||||
func (cm *CryptoManager) initCrypto() error {
|
||||
@@ -63,6 +75,10 @@ func (cm *CryptoManager) initCrypto() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 加密解密函数
|
||||
// ============================================================================
|
||||
|
||||
// EncryptString 字符串加密(AES-256-GCM)
|
||||
// 使用缓存的密钥和GCM实例,提高性能
|
||||
func EncryptString(plain string) (string, error) {
|
||||
|
||||
@@ -9,6 +9,10 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 常量定义
|
||||
// ============================================================================
|
||||
|
||||
const (
|
||||
CSRFTokenLength = 32
|
||||
CSRFCookieName = "csrf_token"
|
||||
@@ -16,6 +20,10 @@ const (
|
||||
CSRFFormField = "csrf_token"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 私有函数
|
||||
// ============================================================================
|
||||
|
||||
// generateRandomBytes 生成指定长度的随机字节
|
||||
func generateRandomBytes(length int) ([]byte, error) {
|
||||
bytes := make([]byte, length)
|
||||
@@ -26,6 +34,10 @@ func generateRandomBytes(length int) ([]byte, error) {
|
||||
return bytes, nil
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 公共函数
|
||||
// ============================================================================
|
||||
|
||||
// GenerateCSRFToken 生成CSRF令牌
|
||||
func GenerateCSRFToken() (string, error) {
|
||||
bytes, err := generateRandomBytes(CSRFTokenLength)
|
||||
|
||||
@@ -14,6 +14,10 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 结构体定义
|
||||
// ============================================================================
|
||||
|
||||
// DatabaseConfig 数据库连接池配置结构体
|
||||
// 用于配置数据库连接池的各项参数,包括连接池大小、生命周期管理和健康检查等
|
||||
type DatabaseConfig struct {
|
||||
@@ -28,6 +32,10 @@ type DatabaseConfig struct {
|
||||
HealthCheckInterval time.Duration `mapstructure:"health_check_interval"` // 健康检查间隔
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 配置函数
|
||||
// ============================================================================
|
||||
|
||||
// GetDefaultDatabaseConfig 获取默认数据库配置
|
||||
// 返回一个包含合理默认值的数据库配置实例
|
||||
func GetDefaultDatabaseConfig() *DatabaseConfig {
|
||||
@@ -197,6 +205,10 @@ func ValidateDatabaseConfig(config *DatabaseConfig) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 全局变量
|
||||
// ============================================================================
|
||||
|
||||
var (
|
||||
// redisClient 全局Redis客户端
|
||||
redisClient *redis.Client
|
||||
@@ -206,6 +218,10 @@ var (
|
||||
redisAvailable bool
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// Redis函数
|
||||
// ============================================================================
|
||||
|
||||
// InitRedis 初始化Redis客户端(仅在配置存在时尝试连接)
|
||||
// - 从 viper 读取 security.redis.* 配置
|
||||
// - 如果连接失败,则标记为不可用,不影响主流程
|
||||
|
||||
@@ -8,12 +8,20 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 结构体定义
|
||||
// ============================================================================
|
||||
|
||||
// EasyEncrypt 易加密算法结构体
|
||||
type EasyEncrypt struct {
|
||||
encryptKey []int // 加密密钥
|
||||
decryptKey []int // 解密密钥
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 构造函数
|
||||
// ============================================================================
|
||||
|
||||
// NewEasyEncrypt 创建新的易加密实例
|
||||
func NewEasyEncrypt(encryptKey, decryptKey []int) *EasyEncrypt {
|
||||
return &EasyEncrypt{
|
||||
@@ -22,6 +30,10 @@ func NewEasyEncrypt(encryptKey, decryptKey []int) *EasyEncrypt {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 密钥生成函数
|
||||
// ============================================================================
|
||||
|
||||
// GenerateEasyKey 生成易加密密钥对
|
||||
func GenerateEasyKey() ([]int, []int, error) {
|
||||
// 使用crypto/rand生成随机长度(15-30位)
|
||||
@@ -60,6 +72,10 @@ func GenerateEasyKey() ([]int, []int, error) {
|
||||
return encryptKey, decryptKey, nil
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 方法函数
|
||||
// ============================================================================
|
||||
|
||||
// Encrypt 加密函数 - 对应 UserLogin_encrypt_Up_42510
|
||||
func (e *EasyEncrypt) Encrypt(input string) string {
|
||||
if input == "" {
|
||||
@@ -140,6 +156,10 @@ func (e *EasyEncrypt) Decrypt(input string) string {
|
||||
return result.String()
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 工具函数
|
||||
// ============================================================================
|
||||
|
||||
// EncryptWithKey 使用指定密钥加密
|
||||
func EncryptWithKey(input string, key []int) string {
|
||||
if input == "" || len(key) == 0 {
|
||||
|
||||
@@ -11,6 +11,10 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 结构体定义
|
||||
// ============================================================================
|
||||
|
||||
// ErrorResponse 统一的错误响应结构
|
||||
// 用于标准化API错误响应格式
|
||||
type ErrorResponse struct {
|
||||
@@ -30,6 +34,10 @@ type SuccessResponse struct {
|
||||
Timestamp int64 `json:"timestamp"` // 响应时间戳
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 常量定义
|
||||
// ============================================================================
|
||||
|
||||
// ErrorCode 错误代码常量
|
||||
// 定义标准化的错误代码,用于客户端识别和处理不同类型的错误
|
||||
const (
|
||||
@@ -68,6 +76,10 @@ type LogEntry struct {
|
||||
Line int `json:"line"` // 源文件行号
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 响应函数
|
||||
// ============================================================================
|
||||
|
||||
// WriteErrorResponse 写入错误响应
|
||||
// c: Gin上下文
|
||||
// statusCode: HTTP状态码
|
||||
@@ -102,6 +114,10 @@ func WriteSuccessResponse(c *gin.Context, statusCode int, message string, data i
|
||||
c.JSON(statusCode, response)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 错误处理函数
|
||||
// ============================================================================
|
||||
|
||||
// HandleDatabaseError 处理数据库错误
|
||||
// c: Gin上下文
|
||||
// err: 数据库错误
|
||||
@@ -152,6 +168,10 @@ func HandleInternalError(c *gin.Context, err error, operation string) {
|
||||
WriteErrorResponse(c, 500, "服务器内部错误", ErrCodeInternalError, nil)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 日志函数
|
||||
// ============================================================================
|
||||
|
||||
// LogInfo 记录信息日志
|
||||
// message: 日志消息
|
||||
// context: 上下文信息
|
||||
@@ -189,6 +209,10 @@ func LogDebug(message string, context interface{}) {
|
||||
printLog(logEntry)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 私有函数
|
||||
// ============================================================================
|
||||
|
||||
// createLogEntry 创建日志条目
|
||||
// level: 日志级别
|
||||
// message: 日志消息
|
||||
|
||||
@@ -4,12 +4,20 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 结构体定义
|
||||
// ============================================================================
|
||||
|
||||
// Logger 日志工具结构体
|
||||
// 封装logrus.Logger,提供统一的日志接口
|
||||
type Logger struct {
|
||||
*log.Logger // 嵌入logrus.Logger,继承其所有方法
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 构造函数
|
||||
// ============================================================================
|
||||
|
||||
// NewLogger 创建新的日志实例,使用全局logrus配置
|
||||
// 返回: 新的Logger实例
|
||||
func NewLogger() *Logger {
|
||||
@@ -32,6 +40,10 @@ func InitLogger() *Logger {
|
||||
return logger
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 方法函数
|
||||
// ============================================================================
|
||||
|
||||
// WithFields 添加字段到日志条目
|
||||
// fields: 要添加的字段映射
|
||||
// 返回: 包含字段的日志条目
|
||||
@@ -89,6 +101,10 @@ func (l *Logger) LogError(err error, msg string) {
|
||||
l.WithError(err).Error(msg)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 全局变量
|
||||
// ============================================================================
|
||||
|
||||
// GlobalLogger 全局日志实例
|
||||
// 提供全局访问的日志记录器
|
||||
var GlobalLogger *Logger
|
||||
@@ -99,6 +115,10 @@ func init() {
|
||||
GlobalLogger = NewLogger()
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 全局函数
|
||||
// ============================================================================
|
||||
|
||||
// GetLogger 获取全局日志实例
|
||||
// 返回: 全局Logger实例
|
||||
func GetLogger() *Logger {
|
||||
|
||||
@@ -5,9 +5,17 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// 全局变量
|
||||
// ============================================================================
|
||||
|
||||
// serverStartTime 记录进程启动时间(近似服务器启动时间)
|
||||
var serverStartTime = time.Now()
|
||||
|
||||
// ============================================================================
|
||||
// 公共函数
|
||||
// ============================================================================
|
||||
|
||||
// GetServerStartTime 获取服务器启动时间
|
||||
// 返回: 服务器启动的时间戳
|
||||
func GetServerStartTime() time.Time {
|
||||
|
||||
Reference in New Issue
Block a user