卡型里本来就有 recharge_type(balance 余额 / subscription 时长)在管计费方式,
cards.purpose(recharge/credential)是后来叠上去的第二套分类,同一件商品挂两个
维度。后果是:在 login_mode=card 的应用里生成卡密,purpose 默认落到 recharge,
拿它登录必然 401「卡密无效或已失效」,而这句话把人往「卡有问题」方向带。
新模型:卡 = 一把钥匙 + 一份面值。
卡已激活(subject_id 有值) → 回到它绑定的主体
卡未激活 + 当前已登录 → 充到当前主体
卡未激活 + 没登录 → 创建新主体,这张卡就是它的钥匙
后端改动:
- auth.go resolveCardSubject 查卡去掉 purpose='credential' 条件
- payment.go 删掉「登录卡不能充值」的拦截(已激活的卡由 status 挡住)
- applications.go 识别卡密主体改用 cards.subject_id,不再靠 purpose 反查
- users.go 主体绑卡展示去掉 purpose 过滤,按 id 倒序取最新一张
- devices.go 设备自助用卡密定位主体,去掉 purpose
- cards.go 补发不再限于 credential,改为「已激活即可补发」;
补发新卡继承原卡 purpose 字段(字段保留但不参与判断);
安全概览统计换成 total/activated/used/unused/void
前端改动:
- 卡型创建页删掉「卡型用途」单选(只留余额/订阅),提交不再传 purpose
- 卡密页补发提示改为按 subject_id 判断;安全概览卡片改为
已激活(有主体/总数) / 未使用 / 已作废
数据未动:cards.purpose 与 card_types.purpose 两列保留、继续写入,只是不再
参与任何判断。当前库里 0 张 credential 卡、0 个卡密主体,没有历史数据要迁移。
测试:go build ✓ go test ./internal/...(admin、service)✓ npm run build(vue-tsc + vite)✓
521 lines
14 KiB
Go
521 lines
14 KiB
Go
package app
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
"verification-platform-backend/internal/database"
|
|
"verification-platform-backend/internal/model"
|
|
"verification-platform-backend/internal/service"
|
|
"verification-platform-backend/pkg/response"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func SetupDeviceRoutes(r *gin.RouterGroup) {
|
|
r.GET("/devices", handleAppGetDevices)
|
|
r.POST("/unbind-device", handleAppUnbindDevice)
|
|
r.GET("/device-count", handleAppGetDeviceCount)
|
|
r.GET("/instances", handleAppGetInstances)
|
|
r.POST("/instances/:instance_id/offline", handleAppForceOfflineInstance)
|
|
}
|
|
|
|
func SetupDevicePublicRoutes(r *gin.RouterGroup) {
|
|
r.POST("/unbind-device-with-auth", handleAppUnbindDeviceWithAuth)
|
|
r.POST("/card-devices", handleAppCardDevices)
|
|
r.POST("/card-unbind", handleAppCardUnbind)
|
|
r.POST("/change-password", handleAppChangePassword)
|
|
}
|
|
|
|
func handleAppUnbindDeviceWithAuth(c *gin.Context) {
|
|
appKey := c.Param("appKey")
|
|
var app model.Application
|
|
if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
|
|
response.Error(c, 404, "应用不存在")
|
|
return
|
|
}
|
|
|
|
if service.GetApplicationDisabledStatus(app.ID) {
|
|
response.Error(c, 403, "该应用已被禁用")
|
|
return
|
|
}
|
|
|
|
var req struct {
|
|
Username string `json:"username"`
|
|
Password string `json:"password"`
|
|
DeviceID string `json:"device_id"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
response.Error(c, 400, "参数错误")
|
|
return
|
|
}
|
|
|
|
if req.Username == "" || req.Password == "" || req.DeviceID == "" {
|
|
response.Error(c, 400, "用户名、密码和设备ID不能为空")
|
|
return
|
|
}
|
|
|
|
var user model.AppUser
|
|
if err := database.DB.Where("username = ? AND application_id = ?", req.Username, app.ID).First(&user).Error; err != nil {
|
|
response.Error(c, 404, "用户不存在")
|
|
return
|
|
}
|
|
|
|
if !service.VerifyAppUserPassword(&user, req.Password) {
|
|
response.Error(c, 401, "密码错误")
|
|
return
|
|
}
|
|
|
|
var device model.UserDevice
|
|
if err := database.DB.Where("user_id = ? AND application_id = ? AND device_id = ?", user.ID, app.ID, req.DeviceID).First(&device).Error; err != nil {
|
|
response.Error(c, 404, "设备不存在")
|
|
return
|
|
}
|
|
|
|
database.DB.Where("device_id = ?", device.ID).Delete(&model.DeviceSession{})
|
|
|
|
if err := database.DB.Delete(&device).Error; err != nil {
|
|
response.Error(c, 500, "解绑设备失败")
|
|
return
|
|
}
|
|
|
|
if user.DeviceID == req.DeviceID {
|
|
now := time.Now()
|
|
database.DB.Model(&user).Updates(map[string]interface{}{
|
|
"device_id": "",
|
|
"last_heartbeat_at": &now,
|
|
})
|
|
}
|
|
|
|
service.LogVerification(c, &app.ID, &user.ID, "unbind_device", fmt.Sprintf("用户解绑设备(认证): %s", req.DeviceID), req.DeviceID, nil)
|
|
|
|
response.Success(c, gin.H{
|
|
"message": "解绑成功",
|
|
})
|
|
}
|
|
|
|
func handleAppGetDevices(c *gin.Context) {
|
|
appKey := c.Param("appKey")
|
|
var app model.Application
|
|
if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
|
|
response.Error(c, 404, "应用不存在")
|
|
return
|
|
}
|
|
|
|
if service.GetApplicationDisabledStatus(app.ID) {
|
|
response.Error(c, 403, "该应用已被禁用")
|
|
return
|
|
}
|
|
|
|
userID, exists := c.Get("user_id")
|
|
if !exists {
|
|
response.Error(c, 401, "未授权")
|
|
return
|
|
}
|
|
|
|
var devices []model.UserDevice
|
|
if err := database.DB.Where("user_id = ? AND application_id = ?", userID, app.ID).Find(&devices).Error; err != nil {
|
|
response.Error(c, 500, "获取设备列表失败")
|
|
return
|
|
}
|
|
|
|
result := make([]gin.H, 0)
|
|
for _, device := range devices {
|
|
var onlineSessionCount int64
|
|
tenMinutesAgo := time.Now().Add(-10 * time.Minute)
|
|
database.DB.Model(&model.DeviceSession{}).
|
|
Where("device_id = ? AND last_heartbeat > ?", device.ID, tenMinutesAgo).
|
|
Count(&onlineSessionCount)
|
|
|
|
result = append(result, gin.H{
|
|
"id": device.ID,
|
|
"device_id": device.DeviceID,
|
|
"device_name": device.DeviceName,
|
|
"device_type": device.DeviceType,
|
|
"status": device.Status,
|
|
"online_sessions": onlineSessionCount,
|
|
"created_at": device.CreatedAt,
|
|
})
|
|
}
|
|
|
|
response.Success(c, result)
|
|
}
|
|
|
|
func handleAppGetDeviceCount(c *gin.Context) {
|
|
appKey := c.Param("appKey")
|
|
var app model.Application
|
|
if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
|
|
response.Error(c, 404, "应用不存在")
|
|
return
|
|
}
|
|
|
|
if service.GetApplicationDisabledStatus(app.ID) {
|
|
response.Error(c, 403, "该应用已被禁用")
|
|
return
|
|
}
|
|
|
|
var req struct {
|
|
UserID uint `json:"user_id"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
response.Error(c, 400, "参数错误")
|
|
return
|
|
}
|
|
|
|
var count int64
|
|
if err := database.DB.Model(&model.UserDevice{}).Where("user_id = ? AND application_id = ?", req.UserID, app.ID).Count(&count).Error; err != nil {
|
|
response.Error(c, 500, "获取设备数量失败")
|
|
return
|
|
}
|
|
|
|
response.Success(c, gin.H{
|
|
"count": count,
|
|
"max_devices": app.MaxDevices,
|
|
"remaining": app.MaxDevices - int(count),
|
|
})
|
|
}
|
|
|
|
func handleAppUnbindDevice(c *gin.Context) {
|
|
appKey := c.Param("appKey")
|
|
var app model.Application
|
|
if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
|
|
response.Error(c, 404, "应用不存在")
|
|
return
|
|
}
|
|
|
|
if service.GetApplicationDisabledStatus(app.ID) {
|
|
response.Error(c, 403, "该应用已被禁用")
|
|
return
|
|
}
|
|
|
|
var req struct {
|
|
UserID uint `json:"user_id"`
|
|
DeviceID string `json:"device_id"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
response.Error(c, 400, "参数错误")
|
|
return
|
|
}
|
|
|
|
var device model.UserDevice
|
|
if err := database.DB.Where("user_id = ? AND application_id = ? AND device_id = ?", req.UserID, app.ID, req.DeviceID).First(&device).Error; err != nil {
|
|
response.Error(c, 404, "设备不存在")
|
|
return
|
|
}
|
|
|
|
database.DB.Where("device_id = ?", device.ID).Delete(&model.DeviceSession{})
|
|
|
|
if err := database.DB.Delete(&device).Error; err != nil {
|
|
response.Error(c, 500, "解绑设备失败")
|
|
return
|
|
}
|
|
|
|
var user model.AppUser
|
|
if err := database.DB.First(&user, req.UserID).Error; err == nil {
|
|
if user.DeviceID == req.DeviceID {
|
|
now := time.Now()
|
|
database.DB.Model(&user).Updates(map[string]interface{}{
|
|
"device_id": "",
|
|
"last_heartbeat_at": &now,
|
|
})
|
|
}
|
|
}
|
|
|
|
service.LogVerification(c, &app.ID, &user.ID, "unbind_device", fmt.Sprintf("用户解绑设备: %s", req.DeviceID), req.DeviceID, nil)
|
|
|
|
response.Success(c, gin.H{
|
|
"message": "解绑成功",
|
|
})
|
|
}
|
|
|
|
func handleAppGetInstances(c *gin.Context) {
|
|
appKey := c.Param("appKey")
|
|
var app model.Application
|
|
if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
|
|
response.Error(c, 404, "应用不存在")
|
|
return
|
|
}
|
|
|
|
if service.GetApplicationDisabledStatus(app.ID) {
|
|
response.Error(c, 403, "该应用已被禁用")
|
|
return
|
|
}
|
|
|
|
var req struct {
|
|
UserID uint `json:"user_id"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
response.Error(c, 400, "参数错误")
|
|
return
|
|
}
|
|
|
|
var devices []model.UserDevice
|
|
if err := database.DB.Where("user_id = ? AND application_id = ?", req.UserID, app.ID).Find(&devices).Error; err != nil {
|
|
response.Error(c, 500, "获取设备列表失败")
|
|
return
|
|
}
|
|
|
|
deviceIDs := make([]uint, len(devices))
|
|
for i, d := range devices {
|
|
deviceIDs[i] = d.ID
|
|
}
|
|
|
|
heartbeatTimeout := app.HeartbeatTimeout
|
|
if heartbeatTimeout <= 0 {
|
|
heartbeatTimeout = 10
|
|
}
|
|
timeoutThreshold := time.Now().Add(-time.Duration(heartbeatTimeout) * time.Minute)
|
|
|
|
var sessions []model.DeviceSession
|
|
if len(deviceIDs) > 0 {
|
|
if err := database.DB.Where("device_id IN ?", deviceIDs).Order("last_heartbeat DESC").Find(&sessions).Error; err != nil {
|
|
response.Error(c, 500, "获取实例列表失败")
|
|
return
|
|
}
|
|
}
|
|
|
|
result := make([]gin.H, 0)
|
|
for _, session := range sessions {
|
|
isOnline := session.LastHeartbeat != nil && session.LastHeartbeat.After(timeoutThreshold)
|
|
|
|
var device model.UserDevice
|
|
for _, d := range devices {
|
|
if d.ID == session.UserDeviceID {
|
|
device = d
|
|
break
|
|
}
|
|
}
|
|
|
|
result = append(result, gin.H{
|
|
"id": session.ID,
|
|
"instance_id": session.InstanceID,
|
|
"device_id": device.DeviceID,
|
|
"device_name": device.DeviceName,
|
|
"is_online": isOnline,
|
|
"last_heartbeat": session.LastHeartbeat,
|
|
"created_at": session.CreatedAt,
|
|
})
|
|
}
|
|
|
|
response.Success(c, result)
|
|
}
|
|
|
|
func handleAppForceOfflineInstance(c *gin.Context) {
|
|
appKey := c.Param("appKey")
|
|
instanceID := c.Param("instance_id")
|
|
|
|
var app model.Application
|
|
if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
|
|
response.Error(c, 404, "应用不存在")
|
|
return
|
|
}
|
|
|
|
if service.GetApplicationDisabledStatus(app.ID) {
|
|
response.Error(c, 403, "该应用已被禁用")
|
|
return
|
|
}
|
|
|
|
var req struct {
|
|
UserID uint `json:"user_id"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
response.Error(c, 400, "参数错误")
|
|
return
|
|
}
|
|
|
|
var devices []model.UserDevice
|
|
if err := database.DB.Where("user_id = ? AND application_id = ?", req.UserID, app.ID).Find(&devices).Error; err != nil {
|
|
response.Error(c, 500, "获取设备列表失败")
|
|
return
|
|
}
|
|
|
|
deviceIDs := make([]uint, len(devices))
|
|
for i, d := range devices {
|
|
deviceIDs[i] = d.ID
|
|
}
|
|
|
|
if len(deviceIDs) == 0 {
|
|
response.Error(c, 404, "实例不存在")
|
|
return
|
|
}
|
|
|
|
result := database.DB.Where("instance_id = ? AND device_id IN ?", instanceID, deviceIDs).Delete(&model.DeviceSession{})
|
|
if result.RowsAffected == 0 {
|
|
response.Error(c, 404, "实例不存在")
|
|
return
|
|
}
|
|
|
|
service.LogVerification(c, &app.ID, &req.UserID, "force_offline", fmt.Sprintf("强制离线实例: %s", instanceID), instanceID, nil)
|
|
|
|
response.Success(c, gin.H{
|
|
"message": "已强制离线",
|
|
})
|
|
}
|
|
|
|
func handleAppChangePassword(c *gin.Context) {
|
|
appKey := c.Param("appKey")
|
|
var app model.Application
|
|
if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
|
|
response.Error(c, 404, "应用不存在")
|
|
return
|
|
}
|
|
|
|
var req struct {
|
|
Username string `json:"username" binding:"required"`
|
|
OldPassword string `json:"old_password" binding:"required"`
|
|
NewPassword string `json:"new_password" binding:"required,min=6"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
response.Error(c, 400, "参数错误")
|
|
return
|
|
}
|
|
|
|
var user model.AppUser
|
|
if err := database.DB.Where("username = ? AND application_id = ?", req.Username, app.ID).First(&user).Error; err != nil {
|
|
response.Error(c, 404, "用户不存在")
|
|
return
|
|
}
|
|
|
|
if !service.VerifyAppUserPassword(&user, req.OldPassword) {
|
|
response.Error(c, 400, "原密码错误")
|
|
return
|
|
}
|
|
|
|
newHash, hashErr := service.HashAppUserPassword(req.NewPassword)
|
|
if hashErr != nil {
|
|
response.Error(c, 500, "密码修改失败")
|
|
return
|
|
}
|
|
user.Password = newHash
|
|
if err := database.DB.Save(&user).Error; err != nil {
|
|
response.Error(c, 500, "密码修改失败")
|
|
return
|
|
}
|
|
|
|
response.Success(c, gin.H{
|
|
"message": "密码修改成功",
|
|
})
|
|
}
|
|
|
|
// resolveCardOwner 用卡密定位主体(卡密本身就是钥匙,能拿出来就等于持有它)
|
|
func resolveCardOwner(app *model.Application, cardKey string) (*model.AppUser, *model.Card, error) {
|
|
var card model.Card
|
|
if err := database.DB.Where("card_key = ? AND application_id = ?", cardKey, app.ID).
|
|
First(&card).Error; err != nil {
|
|
return nil, nil, fmt.Errorf("卡密不存在")
|
|
}
|
|
if card.Status == "void" {
|
|
return nil, nil, fmt.Errorf("卡密已作废")
|
|
}
|
|
if card.SubjectID == nil {
|
|
return nil, &card, fmt.Errorf("卡密尚未激活,先登录一次即可激活")
|
|
}
|
|
var subject model.AppUser
|
|
if err := database.DB.Where("id = ? AND application_id = ?", *card.SubjectID, app.ID).First(&subject).Error; err != nil {
|
|
return nil, &card, fmt.Errorf("卡密对应的主体不存在")
|
|
}
|
|
return &subject, &card, nil
|
|
}
|
|
|
|
// handleAppCardDevices 卡密用户自助查看已绑设备(不需要先登录,卡密就是身份)
|
|
func handleAppCardDevices(c *gin.Context) {
|
|
appKey := c.Param("appKey")
|
|
var app model.Application
|
|
if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
|
|
response.Error(c, 404, "应用不存在")
|
|
return
|
|
}
|
|
|
|
var req struct {
|
|
CardKey string `json:"card_key" binding:"required"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
response.Error(c, 400, "请提供卡密")
|
|
return
|
|
}
|
|
|
|
subject, _, err := resolveCardOwner(&app, strings.TrimSpace(req.CardKey))
|
|
if err != nil {
|
|
response.Error(c, 401, err.Error())
|
|
return
|
|
}
|
|
|
|
var devices []model.UserDevice
|
|
database.DB.Where("user_id = ? AND application_id = ?", subject.ID, app.ID).
|
|
Order("created_at DESC").Find(&devices)
|
|
|
|
timeout := app.HeartbeatTimeout
|
|
if timeout == 0 {
|
|
timeout = 300
|
|
}
|
|
threshold := time.Now().Add(-time.Duration(timeout) * time.Second)
|
|
|
|
list := make([]gin.H, 0, len(devices))
|
|
for _, d := range devices {
|
|
var online int64
|
|
database.DB.Model(&model.DeviceSession{}).
|
|
Where("device_id = ? AND last_heartbeat > ?", d.ID, threshold).Count(&online)
|
|
list = append(list, gin.H{
|
|
"device_id": d.DeviceID,
|
|
"device_name": d.DeviceName,
|
|
"device_type": d.DeviceType,
|
|
"created_at": d.CreatedAt,
|
|
"online_count": online,
|
|
})
|
|
}
|
|
|
|
response.Success(c, gin.H{
|
|
"max_devices": app.MaxDevices,
|
|
"device_count": len(list),
|
|
"devices": list,
|
|
"expiry_at": subject.ExpiryAt,
|
|
"balance": subject.Balance,
|
|
})
|
|
}
|
|
|
|
// handleAppCardUnbind 卡密用户自助解绑其中一台设备
|
|
func handleAppCardUnbind(c *gin.Context) {
|
|
appKey := c.Param("appKey")
|
|
var app model.Application
|
|
if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
|
|
response.Error(c, 404, "应用不存在")
|
|
return
|
|
}
|
|
|
|
var req struct {
|
|
CardKey string `json:"card_key" binding:"required"`
|
|
DeviceID string `json:"device_id" binding:"required"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
response.Error(c, 400, "请提供卡密与设备ID")
|
|
return
|
|
}
|
|
|
|
subject, _, err := resolveCardOwner(&app, strings.TrimSpace(req.CardKey))
|
|
if err != nil {
|
|
response.Error(c, 401, err.Error())
|
|
return
|
|
}
|
|
|
|
var device model.UserDevice
|
|
if err := database.DB.Where("user_id = ? AND application_id = ? AND device_id = ?",
|
|
subject.ID, app.ID, req.DeviceID).First(&device).Error; err != nil {
|
|
response.Error(c, 404, "设备不存在或已解绑")
|
|
return
|
|
}
|
|
|
|
database.DB.Where("device_id = ?", device.ID).Delete(&model.DeviceSession{})
|
|
if err := database.DB.Delete(&device).Error; err != nil {
|
|
response.Error(c, 500, "解绑失败")
|
|
return
|
|
}
|
|
if subject.DeviceID == req.DeviceID {
|
|
database.DB.Model(&model.AppUser{}).Where("id = ?", subject.ID).Update("device_id", "")
|
|
}
|
|
|
|
service.LogVerification(c, &app.ID, &subject.ID, "card_unbind_device",
|
|
fmt.Sprintf("卡密自助解绑设备: %s", req.DeviceID), req.DeviceID, nil)
|
|
|
|
response.Success(c, gin.H{"message": "解绑成功"})
|
|
}
|