This commit is contained in:
2025-12-09 18:55:28 +08:00
parent 8d00d67540
commit c23ab8338b
209 changed files with 5445 additions and 3963 deletions

View File

@@ -4,7 +4,6 @@ import (
"context"
"ycc-server/app/main/model"
jwtx "ycc-server/common/jwt"
"encoding/json"
"errors"
"fmt"
)
@@ -17,40 +16,25 @@ var (
ErrInvalidUserId = errors.New("用户ID格式无效") // 数据异常
)
// GetUidFromCtx 从 context 中获取用户 ID
func GetUidFromCtx(ctx context.Context) (int64, error) {
// GetUidFromCtx 从 context 中获取用户 ID(字符串)
func GetUidFromCtx(ctx context.Context) (string, error) {
// 尝试从上下文中获取 jwtUserId
value := ctx.Value(CtxKeyJwtUserId)
if value == nil {
claims, err := GetClaimsFromCtx(ctx)
if err != nil {
return 0, err
}
return claims.UserId, nil
}
if value == nil {
claims, err := GetClaimsFromCtx(ctx)
if err != nil {
return "", err
}
return claims.UserId, nil
}
// 根据值的类型进行不同处理
switch v := value.(type) {
case json.Number:
// 如果是 json.Number 类型,转换为 int64
uid, err := v.Int64()
if err != nil {
return 0, fmt.Errorf("%w: %v", ErrInvalidUserId, err)
}
return uid, nil
case int64:
// 如果已经是 int64 类型,直接返回
return v, nil
case float64:
// 有些JSON解析器可能会将数字解析为float64
return int64(v), nil
case int:
// 处理int类型
return int64(v), nil
default:
// 其他类型都视为无效
return 0, fmt.Errorf("%w: 期望类型 json.Number 或 int64, 实际类型 %T", ErrInvalidUserId, value)
}
switch v := value.(type) {
case string:
return v, nil
default:
return "", fmt.Errorf("%w: 期望类型 string, 实际类型 %T", ErrInvalidUserId, value)
}
}
func GetClaimsFromCtx(ctx context.Context) (*jwtx.JwtClaims, error) {