package api import ( "cockData/server/cache" "cockData/server/log" "crypto/md5" "encoding/hex" "errors" "fmt" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" ) const SessionRedisKey = "cocks:sessions:%s" type SessionCache struct { UserID uint Region string } func getSessionKey(session string) string { return fmt.Sprintf(SessionRedisKey, session) } type SessionParams struct { Session string `json:"session" binding:"required"` } func createSessionAndSave(userID uint, region string) (session string, err error) { //originStr := fmt.Sprintf("%d:%d", userID, time.Now().UnixNano()) originStr := fmt.Sprintf("%d", userID) hash := md5.New() _, err = hash.Write([]byte(originStr)) if err != nil { log.Warn("创建Session MD5失败") return } salt := "rd-session" session = hex.EncodeToString(hash.Sum([]byte(salt))) // TODO 用MD5没问题就不改 sessionCache := SessionCache{ UserID: userID, Region: region, } //ex, _ := time.ParseDuration("72h") err = cache.RedisSetObj(getSessionKey(session), sessionCache) return } func getSession(session string) (userID uint, err error) { var sessionCache SessionCache //ex, _ := time.ParseDuration("72h") err = cache.RedisGetObj(getSessionKey(session), &sessionCache) if err != nil { return } userID = sessionCache.UserID return } func CheckSession(context *gin.Context) { log.Warnf("访问服务端 %s", context.Request.URL) var params SessionParams err := context.ShouldBindBodyWith(¶ms, binding.JSON) if err != nil { log.Warnf("未携带session参数 %+v", params) ResponseApi(context, *CreateSessionErrorResponse()) return } userId, err := getSession(params.Session) if err != nil { log.Warnf("session获取失败 %+v", err) ResponseApi(context, *CreateSessionErrorResponse()) return } saveOpenID(context, userId) } const OpenIdKey = "OPEN_ID" const OpenNameKey = "USER_NAME" const OpenAvatarKey = "USER_AVATAR" func saveOpenID(context *gin.Context, openID uint) { context.Set(OpenIdKey, openID) } func CheckParamsAndOpenId(context *gin.Context, obj interface{}) (uint, error) { err := context.ShouldBindBodyWith(&obj, binding.JSON) log.Infof("请求参数 %s", obj) if err != nil { ResponseApi(context, *CreateParamsErrorResponse()) return 0, errors.New("params error") } return GetOpenId(context) } func GetOpenId(context *gin.Context) (uint, error) { openID := context.GetUint(OpenIdKey) if openID == 0 { return 0, errors.New("no open id") } return openID, nil }