context.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package service
  2. import (
  3. "context"
  4. "dashoo.cn/opms_libary/myerrors"
  5. "github.com/gogf/gf/errors/gerror"
  6. "github.com/gogf/gf/os/glog"
  7. "dashoo.cn/opms_libary/micro_srv"
  8. "dashoo.cn/opms_libary/request"
  9. )
  10. // ContextService 上下文管理服务
  11. type ContextService struct {
  12. Tenant string `json:"tenant"`
  13. Table string `json:"table"`
  14. Ctx context.Context `json:"ctx"`
  15. CxtUser *request.UserInfo `json:"cxtUser"`
  16. }
  17. // Init 初始化上下文对象指针到上下文对象中,以便后续的请求流程中可以修改。
  18. func (c *ContextService) Init(ctx context.Context) (*ContextService, error) {
  19. cs := ctx.Value("contextService")
  20. if cs != nil {
  21. return cs.(*ContextService), nil
  22. }
  23. c = new(ContextService)
  24. c.Ctx = ctx
  25. // 获取租户码
  26. tenant, err := micro_srv.GetTenant(ctx)
  27. if err != nil {
  28. return nil, gerror.NewCode(myerrors.MicroCallErr, err.Error())
  29. }
  30. reqMethod, err := micro_srv.GetReqMethod(ctx)
  31. if err != nil {
  32. return nil, gerror.NewCode(myerrors.MicroCallErr, err.Error())
  33. }
  34. glog.Info("Received " + reqMethod + " request @ " + tenant)
  35. c.Tenant = tenant
  36. c.CxtUser = nil
  37. if !micro_srv.IsAuthExclude(ctx) {
  38. userInfo, err := micro_srv.GetUserInfo(ctx)
  39. if err != nil {
  40. return nil, gerror.NewCode(myerrors.MicroCallErr, err.Error())
  41. }
  42. c.CxtUser = &userInfo
  43. }
  44. c.Ctx = context.WithValue(ctx, "contextService", c)
  45. return c, nil
  46. }
  47. func (c *ContextService) GetCxtUserId() int {
  48. if c.CxtUser == nil {
  49. return -1
  50. }
  51. return c.CxtUser.Id
  52. }
  53. func (c *ContextService) GetCxtUserUuid() string {
  54. if c.CxtUser == nil {
  55. return "-1"
  56. }
  57. return c.CxtUser.Uuid
  58. }
  59. func (c *ContextService) GetCxtUserName() string {
  60. if c.CxtUser == nil {
  61. return "-1"
  62. }
  63. return c.CxtUser.NickName
  64. }
  65. func (c *ContextService) GetCxtUserDeptId() int {
  66. if c.CxtUser == nil {
  67. return -1
  68. }
  69. return c.CxtUser.DeptId
  70. }
  71. func (c *ContextService) GetCxtUserRoles() []string {
  72. if c.CxtUser == nil {
  73. return []string{}
  74. }
  75. return c.CxtUser.Roles
  76. }
  77. func (c *ContextService) GetCxtUserPosts() []string {
  78. if c.CxtUser == nil {
  79. return []string{}
  80. }
  81. return c.CxtUser.Posts
  82. }
  83. func (c *ContextService) GetCxtUserGroups() []string {
  84. if c.CxtUser == nil {
  85. return []string{}
  86. }
  87. return c.CxtUser.Groups
  88. }