You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cls/pkg/jwtfx/claims.go

119 lines
2.5 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package jwtfx
import (
"fmt"
"github.com/gin-gonic/gin"
)
const (
JWTClaimsKey = "JWT_CLAIMS"
)
// Claims 定义了 JWT token 中的标准字段
type Claims struct {
Phone string `json:"phone,omitempty"`
GuestID string `json:"guest_id,omitempty"`
}
// GetUserIdentifier 从上下文中获取用户标识手机号或游客ID
func GetUserIdentifier(c *gin.Context) string {
value, exists := c.Get(JWTClaimsKey)
if !exists {
fmt.Println("未找到claims")
return ""
}
claims, ok := value.(map[string]interface{})
if !ok {
fmt.Printf("claims类型转换失败: %T\n", value)
return ""
}
fmt.Printf("从上下文中提取的claims: %+v\n", claims)
if claims["username"] != nil {
phone := claims["username"].(string)
fmt.Printf("找到用户手机号: %s\n", phone)
return phone
}
if claims["guest_id"] != nil {
guestId := claims["guest_id"].(string)
fmt.Printf("找到游客ID: %s\n", guestId)
return guestId
}
fmt.Println("未找到用户标识")
return ""
}
func GetOpenid(c *gin.Context) string {
value, exists := c.Get(JWTClaimsKey)
if !exists {
return ""
}
claims, ok := value.(map[string]interface{})
if !ok {
return ""
}
if claims["openid"] != nil {
openid := claims["openid"].(string)
return openid
}
return ""
}
// IsGuest 判断当前用户是否为游客
func IsGuest(c *gin.Context) bool {
value, exists := c.Get(JWTClaimsKey)
if !exists {
return true
}
claims, ok := value.(map[string]interface{})
if !ok {
return true
}
isGuest := claims["guest_id"] != nil
fmt.Printf("判断是否为游客: %v\n", isGuest)
return isGuest
}
// GetClaims 获取完整的 Claims 信息
func GetClaims(c *gin.Context) *Claims {
value, exists := c.Get(JWTClaimsKey)
if !exists {
fmt.Println("未找到claims")
return nil
}
claims, ok := value.(map[string]interface{})
if !ok {
fmt.Printf("claims类型转换失败: %T\n", value)
return nil
}
fmt.Printf("获取完整的claims: %+v\n", claims)
return &Claims{
Phone: getStringFromClaims(claims, "phone"),
GuestID: getStringFromClaims(claims, "guest_id"),
}
}
// getStringFromClaims 安全地从 claims 中获取字符串值
func getStringFromClaims(claims map[string]interface{}, key string) string {
if claims[key] != nil {
if str, ok := claims[key].(string); ok {
fmt.Printf("从claims中获取到 %s: %s\n", key, str)
return str
}
fmt.Printf("claims中的 %s 不是字符串类型\n", key)
}
fmt.Printf("claims中不存在 %s\n", key)
return ""
}