context.go 2.1 KB

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