session.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package router
  2. import (
  3. "app.yhyue.com/moapp/jybase/redis"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "github.com/gogf/gf/v2/frame/g"
  8. "github.com/gogf/gf/v2/net/ghttp"
  9. "github.com/gogf/gf/v2/util/gconv"
  10. "net/url"
  11. )
  12. const (
  13. JY_SESSIONNAME = "SESSIONID"
  14. )
  15. // JySession 剑鱼程序SESSION获取
  16. type JySession struct {
  17. UserId string // 上下文用户信息
  18. NewUid int64 // 新用户id
  19. EntId int64 // 当前企业id
  20. EntName string // 当前企业名称
  21. Phone string // 手机号
  22. Data g.Map // 当前Session管理对象
  23. }
  24. // GetJySession 获取剑鱼程序session内容
  25. func GetJySession(ctx context.Context) (jSession *JySession) {
  26. jSession = &JySession{}
  27. value := ctx.Value(JY_SESSIONNAME)
  28. if value == nil {
  29. return
  30. }
  31. if localCtx, ok := value.(*JySession); ok {
  32. jSession = localCtx
  33. }
  34. return
  35. }
  36. // InitJySessionContext 获取用户session
  37. func InitJySessionContext(r *ghttp.Request) (jSession *JySession, err error) {
  38. jSession = &JySession{}
  39. cookie, err := r.Request.Cookie(JY_SESSIONNAME)
  40. if err != nil {
  41. return
  42. }
  43. if cookie.Value == "" {
  44. err = fmt.Errorf("cookie 内容为空")
  45. return
  46. }
  47. findKey, _ := url.QueryUnescape(cookie.Value)
  48. bs, err := redis.GetBytes("session", findKey)
  49. if err != nil {
  50. return
  51. }
  52. var data map[string]interface{}
  53. err = json.Unmarshal(*bs, &data)
  54. jSession.Phone, _ = data["phone"].(string)
  55. jSession.UserId, _ = data["userId"].(string)
  56. jSession.EntName, _ = data["entName"].(string)
  57. jSession.EntId = gconv.Int64(data["entId"])
  58. jSession.NewUid = gconv.Int64(data["userId_new"])
  59. jSession.Data = data
  60. return
  61. }