修复会话安全与实时消息
This commit is contained in:
@@ -1,13 +1,16 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"kefu-sys/server/internal/model"
|
||||
)
|
||||
|
||||
var jwtSecret []byte
|
||||
@@ -37,26 +40,91 @@ func GenerateToken(userID, tenantID uint, role string) (string, error) {
|
||||
return token.SignedString(jwtSecret)
|
||||
}
|
||||
|
||||
func ParseToken(tokenStr string) (*Claims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(t *jwt.Token) (interface{}, error) {
|
||||
if t.Method.Alg() != jwt.SigningMethodHS256.Alg() {
|
||||
return nil, errors.New("不支持的签名算法")
|
||||
}
|
||||
return jwtSecret, nil
|
||||
})
|
||||
if err != nil || !token.Valid {
|
||||
if err == nil {
|
||||
err = errors.New("token无效")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*Claims)
|
||||
if !ok {
|
||||
return nil, errors.New("token声明无效")
|
||||
}
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
// ValidateUserAccess 确保令牌对应的账号与租户当前仍可使用。
|
||||
func ValidateUserAccess(userID, tenantID uint, role string) (int, string) {
|
||||
var user model.User
|
||||
if err := model.DB.Select("id", "tenant_id", "role", "status").First(&user, userID).Error; err != nil ||
|
||||
user.TenantID != tenantID || user.Role != role {
|
||||
return http.StatusUnauthorized, "账号状态已变化,请重新登录"
|
||||
}
|
||||
if user.Status == "disabled" {
|
||||
return http.StatusForbidden, "账号已被禁用"
|
||||
}
|
||||
|
||||
if role == "platform_admin" {
|
||||
if tenantID != 0 {
|
||||
return http.StatusUnauthorized, "平台管理员租户无效"
|
||||
}
|
||||
return 0, ""
|
||||
}
|
||||
|
||||
var tenant model.Tenant
|
||||
if err := model.DB.Select("id", "status").First(&tenant, tenantID).Error; err != nil {
|
||||
return http.StatusForbidden, "租户不存在或不可用"
|
||||
}
|
||||
if tenant.Status == "suspended" || tenant.Status == "expired" {
|
||||
return http.StatusForbidden, "租户已暂停或已过期"
|
||||
}
|
||||
return 0, ""
|
||||
}
|
||||
|
||||
func tokenFromRequest(c *gin.Context) string {
|
||||
auth := c.GetHeader("Authorization")
|
||||
if strings.HasPrefix(auth, "Bearer ") {
|
||||
return strings.TrimPrefix(auth, "Bearer ")
|
||||
}
|
||||
|
||||
// 浏览器 WebSocket 无法设置 Authorization;仅接受约定子协议中的令牌。
|
||||
protocols := strings.Split(c.GetHeader("Sec-WebSocket-Protocol"), ",")
|
||||
if len(protocols) == 2 && strings.TrimSpace(protocols[0]) == "kefu-v1" {
|
||||
return strings.TrimSpace(protocols[1])
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func AuthRequired() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
auth := c.GetHeader("Authorization")
|
||||
if auth == "" || !strings.HasPrefix(auth, "Bearer ") {
|
||||
tokenStr := tokenFromRequest(c)
|
||||
if tokenStr == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "未授权"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
tokenStr := strings.TrimPrefix(auth, "Bearer ")
|
||||
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(t *jwt.Token) (interface{}, error) {
|
||||
return jwtSecret, nil
|
||||
})
|
||||
if err != nil || !token.Valid {
|
||||
claims, err := ParseToken(tokenStr)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "token无效"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
claims := token.Claims.(*Claims)
|
||||
if status, message := ValidateUserAccess(claims.UserID, claims.TenantID, claims.Role); status != 0 {
|
||||
c.JSON(status, gin.H{"code": status, "message": message})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("user_id", claims.UserID)
|
||||
c.Set("tenant_id", claims.TenantID)
|
||||
c.Set("role", claims.Role)
|
||||
@@ -64,10 +132,25 @@ func AuthRequired() gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func GetRole(c *gin.Context) string {
|
||||
role, _ := c.Get("role")
|
||||
value, _ := role.(string)
|
||||
return value
|
||||
}
|
||||
|
||||
func HasAnyRole(c *gin.Context, roles ...string) bool {
|
||||
role := GetRole(c)
|
||||
for _, allowed := range roles {
|
||||
if role == allowed {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func AdminRequired() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
role, _ := c.Get("role")
|
||||
if role != "admin" && role != "platform_admin" {
|
||||
if !HasAnyRole(c, "admin", "platform_admin") {
|
||||
c.JSON(http.StatusForbidden, gin.H{"code": 403, "message": "无权限"})
|
||||
c.Abort()
|
||||
return
|
||||
@@ -78,8 +161,7 @@ func AdminRequired() gin.HandlerFunc {
|
||||
|
||||
func PlatformRequired() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
role, _ := c.Get("role")
|
||||
if role != "platform_admin" {
|
||||
if !HasAnyRole(c, "platform_admin") {
|
||||
c.JSON(http.StatusForbidden, gin.H{"code": 403, "message": "仅平台管理员可操作"})
|
||||
c.Abort()
|
||||
return
|
||||
@@ -111,16 +193,25 @@ func GetPageParams(c *gin.Context) (page, pageSize int) {
|
||||
}
|
||||
|
||||
func JSON(c *gin.Context, data interface{}) {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "message": "ok", "data": data})
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "message": "ok", "data": nonNilSlice(data)})
|
||||
}
|
||||
|
||||
func JSONList(c *gin.Context, list interface{}, total int64, page, pageSize int) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"message": "ok",
|
||||
"list": list,
|
||||
"list": nonNilSlice(list),
|
||||
"total": total,
|
||||
"page": page,
|
||||
"pageSize": pageSize,
|
||||
})
|
||||
}
|
||||
|
||||
// nonNilSlice 统一将空切片序列化为 [],避免前端收到 null 后调用数组方法崩溃。
|
||||
func nonNilSlice(data interface{}) interface{} {
|
||||
value := reflect.ValueOf(data)
|
||||
if value.IsValid() && value.Kind() == reflect.Slice && value.IsNil() {
|
||||
return reflect.MakeSlice(value.Type(), 0, 0).Interface()
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user