package utils import ( "context" "google.golang.org/grpc/metadata" "strconv" "strings" ) type UserSession struct { USN int64 `json:"usn" redis:"usn"` IP string `json:"ip" redis:"ip"` UserAgent string `json:"ua" redis:"ua"` AccessToken string `json:"at" redis:"at"` RefreshToken string `json:"rt" redis:"rt"` } func (us *UserSession) GetUsnKey() string { return "usn" } func (us *UserSession) GetAccessTokenKey() string { return "at" } func (us *UserSession) GetRefreshTokenKey() string { return "rt" } // Deprecated: 请使用 ShouldGetUsn 替代,示例: // usn := utils.ShouldGetUsn(ctx) // 不需要判断 usn 是否为 0,只有不鉴权接口的 usn 才可能是 0。 func ShouldBindUsn(ctx context.Context, usn *int64) bool { if md, ok := metadata.FromIncomingContext(ctx); ok { usnArr := md.Get("X-Usn") if len(usnArr) == 0 || usnArr[0] == "" { return false } *usn = StringToInt64(usnArr[0]) } return *usn != 0 } func ShouldGetUsn(ctx context.Context) int64 { if md, ok := metadata.FromIncomingContext(ctx); ok { usnArr := md.Get("X-Usn") if len(usnArr) == 0 || usnArr[0] == "" { return 0 } return StringToInt64(usnArr[0]) } return 0 } func GetPlatformAndUsn(token string) (int32, int64, bool) { str := strings.Split(token, ":") if len(str) != 3 { return 0, 0, false } platform, err := strconv.Atoi(str[0]) if err != nil { return 0, 0, false } usn, err := strconv.Atoi(str[1]) if err != nil { return 0, 0, false } return int32(platform), int64(usn), true }