feat: 心跳接口改用JWT token获取用户设备信息
- JWT Claims 增加 device_id 和 instance_id 字段 - 登录时将设备信息编码到 token - 心跳接口从 token 自动获取用户和设备信息 - 心跳路由移到需要 JWT 认证的路由组 - 更新 API 文档 优点: - 更安全:无法伪造设备信息 - 请求更简洁:心跳无需传递参数 - 符合业界标准做法 Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -88,8 +88,10 @@ func JWT() gin.HandlerFunc {
|
||||
c.Set("user_id", claims.UserID)
|
||||
c.Set("username", claims.Username)
|
||||
c.Set("role", claims.Role)
|
||||
c.Set("device_id", claims.DeviceID)
|
||||
c.Set("instance_id", claims.InstanceID)
|
||||
|
||||
fmt.Printf("JWT中间件: 验证成功, user_id=%d, role=%s\n", claims.UserID, claims.Role)
|
||||
fmt.Printf("JWT中间件: 验证成功, user_id=%d, role=%s, device_id=%s, instance_id=%s\n", claims.UserID, claims.Role, claims.DeviceID, claims.InstanceID)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,23 +65,40 @@ func handleAppHeartbeat(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
UserID uint `json:"user_id"`
|
||||
DeviceID string `json:"device_id"`
|
||||
InstanceID string `json:"instance_id"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.Error(c, 400, "参数错误")
|
||||
// 从 JWT token 中获取用户信息
|
||||
userIDInterface, exists := c.Get("user_id")
|
||||
if !exists {
|
||||
response.Error(c, 401, "未授权")
|
||||
return
|
||||
}
|
||||
userID := userIDInterface.(uint)
|
||||
|
||||
usernameInterface, _ := c.Get("username")
|
||||
username := usernameInterface.(string)
|
||||
|
||||
// 从 JWT token 中获取设备信息
|
||||
deviceIDInterface, exists := c.Get("device_id")
|
||||
deviceID := ""
|
||||
if exists {
|
||||
deviceID = deviceIDInterface.(string)
|
||||
}
|
||||
|
||||
instanceIDInterface, exists := c.Get("instance_id")
|
||||
instanceID := ""
|
||||
if exists {
|
||||
instanceID = instanceIDInterface.(string)
|
||||
}
|
||||
if instanceID == "" {
|
||||
instanceID = deviceID
|
||||
}
|
||||
|
||||
var user model.AppUser
|
||||
if err := database.DB.First(&user, req.UserID).Error; err != nil {
|
||||
if err := database.DB.First(&user, userID).Error; err != nil {
|
||||
response.Error(c, 404, "用户不存在")
|
||||
return
|
||||
}
|
||||
|
||||
if blocked, reason := checkRiskControl(c, app.ID, req.DeviceID, user.Username); blocked {
|
||||
if blocked, reason := checkRiskControl(c, app.ID, deviceID, username); blocked {
|
||||
log.Printf("[DEBUG] Heartbeat blocked by risk control: %s", reason)
|
||||
response.Error(c, 403, reason)
|
||||
return
|
||||
@@ -145,16 +162,16 @@ func handleAppHeartbeat(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if req.DeviceID != "" {
|
||||
if deviceID != "" {
|
||||
var device model.UserDevice
|
||||
err := database.DB.Where("user_id = ? AND application_id = ? AND device_id = ?", user.ID, app.ID, req.DeviceID).First(&device).Error
|
||||
err := database.DB.Where("user_id = ? AND application_id = ? AND device_id = ?", user.ID, app.ID, deviceID).First(&device).Error
|
||||
|
||||
if err != nil {
|
||||
device = model.UserDevice{
|
||||
UserID: user.ID,
|
||||
ApplicationID: app.ID,
|
||||
DeviceID: req.DeviceID,
|
||||
DeviceName: req.DeviceID,
|
||||
DeviceID: deviceID,
|
||||
DeviceName: deviceID,
|
||||
Status: "active",
|
||||
}
|
||||
if err := database.DB.Create(&device).Error; err != nil {
|
||||
@@ -162,11 +179,6 @@ func handleAppHeartbeat(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
instanceID := req.InstanceID
|
||||
if instanceID == "" {
|
||||
instanceID = req.DeviceID
|
||||
}
|
||||
|
||||
if device.ID > 0 {
|
||||
var session model.DeviceSession
|
||||
sessionErr := database.DB.Where("device_id = ? AND instance_id = ?", device.ID, instanceID).First(&session).Error
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
|
||||
func SetupRoutes(r *gin.RouterGroup) {
|
||||
SetupPaymentRoutes(r)
|
||||
SetupAccountRoutes(r)
|
||||
SetupDynamicRoutes(r)
|
||||
SetupUserRoutes(r)
|
||||
SetupTicketRoutes(r)
|
||||
@@ -14,4 +13,5 @@ func SetupRoutes(r *gin.RouterGroup) {
|
||||
|
||||
func SetupAuthRoutes(r *gin.RouterGroup) {
|
||||
SetupDeviceRoutes(r)
|
||||
SetupAccountRoutes(r)
|
||||
}
|
||||
|
||||
@@ -681,7 +681,11 @@ func handleAppLogin(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
token, err := jwt.GenerateToken(user.ID, user.Username, "app_user")
|
||||
tokenInstanceID := req.InstanceID
|
||||
if tokenInstanceID == "" {
|
||||
tokenInstanceID = req.DeviceID
|
||||
}
|
||||
token, err := jwt.GenerateTokenWithDevice(user.ID, user.Username, "app_user", req.DeviceID, tokenInstanceID)
|
||||
if err != nil {
|
||||
log.Printf("[DEBUG] Failed to generate token: %v", err)
|
||||
}
|
||||
|
||||
+17
-8
@@ -10,14 +10,21 @@ import (
|
||||
|
||||
// Claims JWT声明
|
||||
type Claims struct {
|
||||
UserID uint `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
UserID uint `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
DeviceID string `json:"device_id,omitempty"`
|
||||
InstanceID string `json:"instance_id,omitempty"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// GenerateToken 生成JWT令牌
|
||||
func GenerateToken(userID uint, username, role string) (string, error) {
|
||||
return GenerateTokenWithDevice(userID, username, role, "", "")
|
||||
}
|
||||
|
||||
// GenerateTokenWithDevice 生成包含设备信息的JWT令牌
|
||||
func GenerateTokenWithDevice(userID uint, username, role, deviceID, instanceID string) (string, error) {
|
||||
expireHours := config.GetInt("app.jwt_expire_hours")
|
||||
if expireHours <= 0 {
|
||||
expireHours = 24
|
||||
@@ -26,9 +33,11 @@ func GenerateToken(userID uint, username, role string) (string, error) {
|
||||
expiresAt := time.Now().Add(time.Hour * time.Duration(expireHours))
|
||||
|
||||
claims := Claims{
|
||||
UserID: userID,
|
||||
Username: username,
|
||||
Role: role,
|
||||
UserID: userID,
|
||||
Username: username,
|
||||
Role: role,
|
||||
DeviceID: deviceID,
|
||||
InstanceID: instanceID,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(expiresAt),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
@@ -70,6 +79,6 @@ func RefreshToken(tokenString string) (string, error) {
|
||||
return "", errors.New("token is still valid")
|
||||
}
|
||||
|
||||
// 生成新令牌
|
||||
return GenerateToken(claims.UserID, claims.Username, claims.Role)
|
||||
// 生成新令牌,保留设备信息
|
||||
return GenerateTokenWithDevice(claims.UserID, claims.Username, claims.Role, claims.DeviceID, claims.InstanceID)
|
||||
}
|
||||
|
||||
@@ -365,15 +365,10 @@ Content-Type: application/json
|
||||
```
|
||||
POST /api/v1/app/{appKey}/heartbeat
|
||||
Authorization: Bearer {token}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"user_id": 1,
|
||||
"device_id": "设备ID",
|
||||
"instance_id": "实例ID"
|
||||
}
|
||||
```
|
||||
|
||||
> 用户ID、设备ID、实例ID均从 JWT token 中自动获取,无需在请求体中传递。token 在登录时已包含设备信息。
|
||||
|
||||
**响应**
|
||||
```json
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user