package utils import ( "context" "net/url" "strconv" "github.com/mssola/user_agent" "google.golang.org/grpc/metadata" ) type UserInfo struct { ID int64 Name string RawUID string Refresh string ClientIP string // 客户端ip UserAgent string // 完整原始ua BrowserName string // 浏览器名称 BrowserVer string // 浏览器版本 StoreName string // 店铺名称 StoreId int64 // 店铺id SaleName string // 销售名称 SaleId int64 // 销售id SaleMobile string // 销售手机 SaleProvince int64 // 销售省份 GroupId int64 // 分组ID GroupName string // 分组名称 Type uint8 // 用户类型 ClientCode string Valid bool } func firstMD(md metadata.MD, keys ...string) string { for _, key := range keys { vals := md.Get(key) if len(vals) > NumberZero && vals[NumberZero] != StringEmpty { return vals[NumberZero] } } return StringEmpty } func parseInt64MD(md metadata.MD, keys ...string) int64 { raw := firstMD(md, keys...) if raw == StringEmpty { return NumberZero } v, _ := strconv.ParseInt(raw, NumberTen, NumberSixtyFourth) return v } func GetUserFromCtx(ctx context.Context) UserInfo { md, ok := metadata.FromIncomingContext(ctx) if !ok { return UserInfo{Valid: false} } userInfo := UserInfo{ RawUID: firstMD(md, "x-user-id"), Name: firstMD(md, "x-user-name"), Refresh: firstMD(md, "x-refresh", "X-Refresh"), ClientIP: firstMD(md, "x-client-ip"), UserAgent: firstMD(md, "x-user-agent"), StoreName: firstMD(md, "x-store-name"), StoreId: parseInt64MD(md, "x-store-id"), SaleName: firstMD(md, "x-sale-name"), SaleId: parseInt64MD(md, "x-sale-id"), SaleMobile: firstMD(md, "x-sale-mobile"), SaleProvince: parseInt64MD(md, "x-sale-province"), GroupId: parseInt64MD(md, "x-group-id"), GroupName: firstMD(md, "x-group-name"), ClientCode: firstMD(md, "x-client-code"), } if typeRaw := firstMD(md, "x-user-type"); typeRaw != StringEmpty { typeInt, _ := strconv.ParseInt(typeRaw, NumberTen, NumberSixtyFourth) userInfo.Type = uint8(typeInt) } if userInfo.UserAgent != StringEmpty { userInfo.UserAgent, _ = url.QueryUnescape(userInfo.UserAgent) ua := user_agent.New(userInfo.UserAgent) userInfo.BrowserName, userInfo.BrowserVer = ua.Browser() } userInfo.Valid = false if userInfo.RawUID == StringEmpty { return userInfo } uid, err := strconv.ParseInt(userInfo.RawUID, NumberTen, NumberSixtyFourth) if err != nil { return userInfo } userName, _ := url.QueryUnescape(userInfo.Name) userInfo.ID = uid userInfo.Name = userName if userInfo.SaleName != StringEmpty { userInfo.SaleName, _ = url.QueryUnescape(userInfo.SaleName) } if userInfo.StoreName != StringEmpty { userInfo.StoreName, _ = url.QueryUnescape(userInfo.StoreName) } if userInfo.GroupName != StringEmpty { userInfo.GroupName, _ = url.QueryUnescape(userInfo.GroupName) } userInfo.Valid = true return userInfo }