context.go 1.9 KB

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