218 lines
5.3 KiB
Go
218 lines
5.3 KiB
Go
package middleware
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"reflect"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"kefu-cloud/server/internal/model"
|
|
)
|
|
|
|
var jwtSecret []byte
|
|
|
|
func InitJWT(secret string) {
|
|
jwtSecret = []byte(secret)
|
|
}
|
|
|
|
type Claims struct {
|
|
UserID uint `json:"user_id"`
|
|
TenantID uint `json:"tenant_id"`
|
|
Role string `json:"role"`
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
func GenerateToken(userID, tenantID uint, role string) (string, error) {
|
|
claims := Claims{
|
|
UserID: userID,
|
|
TenantID: tenantID,
|
|
Role: role,
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
|
|
IssuedAt: jwt.NewNumericDate(time.Now()),
|
|
},
|
|
}
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
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) {
|
|
tokenStr := tokenFromRequest(c)
|
|
if tokenStr == "" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "未授权"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
claims, err := ParseToken(tokenStr)
|
|
if err != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "message": "token无效"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
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)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
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) {
|
|
if !HasAnyRole(c, "admin", "platform_admin") {
|
|
c.JSON(http.StatusForbidden, gin.H{"code": 403, "message": "无权限"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func PlatformRequired() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if !HasAnyRole(c, "platform_admin") {
|
|
c.JSON(http.StatusForbidden, gin.H{"code": 403, "message": "仅平台管理员可操作"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func GetTenantID(c *gin.Context) uint {
|
|
id, _ := c.Get("tenant_id")
|
|
return id.(uint)
|
|
}
|
|
|
|
func GetUserID(c *gin.Context) uint {
|
|
id, _ := c.Get("user_id")
|
|
return id.(uint)
|
|
}
|
|
|
|
func GetPageParams(c *gin.Context) (page, pageSize int) {
|
|
page, _ = strconv.Atoi(c.DefaultQuery("page", "1"))
|
|
pageSize, _ = strconv.Atoi(c.DefaultQuery("pageSize", "10"))
|
|
if page < 1 {
|
|
page = 1
|
|
}
|
|
if pageSize < 1 || pageSize > 100 {
|
|
pageSize = 10
|
|
}
|
|
return
|
|
}
|
|
|
|
func JSON(c *gin.Context, data interface{}) {
|
|
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": 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
|
|
}
|