123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- 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
- }
|