package models import ( "encoding/json" "errors" "log" "os" "gorm.io/driver/sqlite" "gorm.io/gorm" ) // AuthCode 表示授权码数据表 type AuthCode struct { ID uint `gorm:"primaryKey"` // 自增主键 UUID string `gorm:"unique"` // 授权码唯一标识 DeviceID string // 设备唯一标识 } // License 表示单个授权码的 JSON 数据 type License struct { UUID string `json:"uuid"` // 授权码 LicenseFile string `json:"license_file"` // 授权文件路径 } // LicenseImportData 表示整个 JSON 导入文件的数据结构 type LicenseImportData struct { Name string `json:"name"` // 授权组名称 AppID string `json:"app_id"` // 应用 ID ExpireTime string `json:"expire_time"` // 授权码过期时间 Licenses []License `json:"licenses"` // 授权码列表 } // DB 数据库实例 var DB *gorm.DB // InitDatabase 初始化数据库 func InitDatabase(dbPath string) { var err error DB, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{}) if err != nil { log.Fatal("Failed to connect to database:", err) } // 自动迁移数据库表 err = DB.AutoMigrate(&AuthCode{}) if err != nil { log.Fatal("Failed to migrate database:", err) } } // FindAuthCode 根据 UUID 查询授权码 func FindAuthCode(uuid string) (*AuthCode, error) { var authCode AuthCode result := DB.Where("uuid = ?", uuid).First(&authCode) if result.Error != nil { return nil, result.Error } return &authCode, nil } // SaveAuthCode 保存授权码 func SaveAuthCode(authCode *AuthCode) error { return DB.Save(authCode).Error } // ImportLicenses 从 JSON 文件导入授权码到数据库 func ImportLicenses(filePath string) error { // 1. 读取 JSON 文件 data, err := os.ReadFile(filePath) if err != nil { return errors.New("failed to read JSON file: " + err.Error()) } // 2. 解析 JSON 数据 var importData LicenseImportData if err := json.Unmarshal(data, &importData); err != nil { return errors.New("failed to parse JSON: " + err.Error()) } // 3. 打印导入信息 log.Printf("Importing licenses for app: %s, name: %s, expire_time: %s", importData.AppID, importData.Name, importData.ExpireTime) // 4. 遍历授权码并写入数据库 for _, license := range importData.Licenses { authCode := &AuthCode{ UUID: license.UUID, DeviceID: license.LicenseFile, // 假设 LicenseFile 存储为 DeviceID } // 保存到数据库 if err := SaveAuthCode(authCode); err != nil { log.Printf("Failed to save license with UUID %s: %v", license.UUID, err) } else { log.Printf("Successfully imported license: %s", license.UUID) } } log.Println("All licenses imported successfully!") return nil }