package handlers
|
|
import (
|
"net/http"
|
"time"
|
|
"gamebox-server/config"
|
"gamebox-server/models"
|
|
"github.com/gin-gonic/gin"
|
)
|
|
func cardDuration(cardType string) time.Duration {
|
switch cardType {
|
case "day":
|
return 24 * time.Hour
|
case "month":
|
return 30 * 24 * time.Hour
|
case "year":
|
return 365 * 24 * time.Hour
|
}
|
return 0 // forever(永久卡)无固定时长,由调用方特殊处理
|
}
|
|
// validCardType 是否为合法卡类型
|
func validCardType(cardType string) bool {
|
switch cardType {
|
case "day", "month", "year", "forever":
|
return true
|
}
|
return false
|
}
|
|
// ActivateKey 激活会员密钥(绑定机器)
|
func ActivateKey(c *gin.Context) {
|
userID := c.GetUint("user_id")
|
var req struct {
|
Code string `json:"code"`
|
MachineCode string `json:"machine_code"`
|
}
|
if err := c.ShouldBindJSON(&req); err != nil || req.Code == "" {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "请输入激活码"})
|
return
|
}
|
if req.MachineCode == "" {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "获取机器码失败"})
|
return
|
}
|
var key models.MemberKey
|
if err := config.DB.Where("code = ?", req.Code).First(&key).Error; err != nil {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "激活码不存在,请检查后重新输入"})
|
return
|
}
|
// 冻结的密钥不可使用
|
if key.Frozen {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "该激活码已被冻结,无法使用!"})
|
return
|
}
|
|
now := time.Now()
|
if key.Status == 0 {
|
// 未使用,直接激活
|
updates := map[string]interface{}{
|
"status": 1,
|
"user_id": userID,
|
"machine_code": req.MachineCode,
|
"activated_at": now,
|
}
|
// 永久卡不设置到期时间
|
if key.CardType == "forever" {
|
updates["expired_at"] = nil
|
} else {
|
updates["expired_at"] = now.Add(cardDuration(key.CardType))
|
}
|
config.DB.Model(&key).Updates(updates)
|
expireStr := "永久"
|
if expiredAt, ok := updates["expired_at"].(time.Time); ok {
|
expireStr = expiredAt.Format("2006-01-02 15:04:05")
|
}
|
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "激活成功!", "data": gin.H{
|
"expire_at": expireStr,
|
}})
|
return
|
}
|
|
// 已使用的密钥
|
if key.MachineCode != req.MachineCode {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "该激活码已在其他电脑上使用,无法在此设备激活!"})
|
return
|
}
|
if key.ExpiredAt != nil && key.ExpiredAt.Before(now) {
|
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "该激活码已过期,请使用新的激活码!"})
|
return
|
}
|
// 同机器重复激活,返回当前有效期
|
expireStr := "永久"
|
if key.ExpiredAt != nil {
|
expireStr = key.ExpiredAt.Format("2006-01-02 15:04:05")
|
}
|
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "该激活码已在此设备激活", "data": gin.H{
|
"expire_at": expireStr,
|
}})
|
}
|