SussBi.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. package outServer
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "net/http"
  8. "net/http/cookiejar"
  9. "net/url"
  10. "regexp"
  11. "strings"
  12. "bp.jydev.jianyu360.cn/BaseService/gateway/core/router"
  13. "github.com/gogf/gf/v2/net/ghttp"
  14. "github.com/gogf/gf/v2/util/gconv"
  15. "golang.org/x/net/publicsuffix"
  16. )
  17. type sussBi struct {
  18. addr string
  19. user string
  20. pwd string
  21. Url *url.URL
  22. jar *cookiejar.Jar
  23. prm *ParamReplaceManager
  24. }
  25. //参数替换
  26. type ParamReplace struct {
  27. Replace []ParamReplaceSetting
  28. Match []ParamReplaceSetting
  29. }
  30. type ParamReplaceSetting struct {
  31. Key, Value string
  32. }
  33. type ParamReplaceManager struct {
  34. eqRouters map[string]*ParamReplace
  35. regexRouter map[*regexp.Regexp]*ParamReplace
  36. }
  37. func InitSussBi(config map[string]interface{}) (*sussBi, error) {
  38. address := gconv.String(config["addr"])
  39. user := gconv.String(config["user"])
  40. password := gconv.String(config["password"])
  41. paramReplace := gconv.Map(config["paramReplace"])
  42. if address == "" {
  43. return nil, fmt.Errorf("配置异常")
  44. }
  45. sussCookie, err := cookiejar.New(&cookiejar.Options{
  46. PublicSuffixList: publicsuffix.List,
  47. })
  48. if err != nil {
  49. return nil, fmt.Errorf("初始化cookie异常")
  50. }
  51. prManager := &ParamReplaceManager{
  52. eqRouters: map[string]*ParamReplace{},
  53. regexRouter: map[*regexp.Regexp]*ParamReplace{},
  54. }
  55. for url, setting := range paramReplace {
  56. pr := &ParamReplace{}
  57. settingMap := gconv.Map(setting)
  58. if settingMap == nil || len(settingMap) == 0 {
  59. continue
  60. }
  61. if replaceMap := gconv.Map(settingMap["replace"]); replaceMap != nil && len(replaceMap) > 0 {
  62. for k, v := range replaceMap {
  63. pr.Replace = append(pr.Replace, ParamReplaceSetting{
  64. Key: k,
  65. Value: gconv.String(v),
  66. })
  67. }
  68. }
  69. if replaceMap := gconv.Map(settingMap["match"]); replaceMap != nil && len(replaceMap) > 0 {
  70. for k, v := range replaceMap {
  71. pr.Match = append(pr.Replace, ParamReplaceSetting{
  72. Key: k,
  73. Value: gconv.String(v),
  74. })
  75. }
  76. }
  77. if len(pr.Match) == 0 && len(pr.Replace) == 0 {
  78. continue
  79. }
  80. if regexp.QuoteMeta(url) == url {
  81. prManager.eqRouters[url] = pr
  82. } else {
  83. if reg, err := regexp.Compile(url); err == nil {
  84. prManager.regexRouter[reg] = pr
  85. }
  86. }
  87. }
  88. u, _ := url.Parse(address)
  89. return &sussBi{
  90. addr: address,
  91. user: user,
  92. Url: u,
  93. pwd: password,
  94. jar: sussCookie,
  95. prm: prManager,
  96. }, nil
  97. }
  98. // AutoLogin 自动登录
  99. func (s *sussBi) AutoLogin() error {
  100. client := &http.Client{
  101. Jar: s.jar,
  102. }
  103. resp, err := client.Get(fmt.Sprintf("%s/?:user=%s&:password=%s", s.addr, s.user, s.pwd))
  104. if err != nil {
  105. return err
  106. }
  107. if !(resp.StatusCode == 302 || resp.StatusCode == 200) {
  108. return fmt.Errorf("自动登录异常")
  109. }
  110. return nil
  111. }
  112. // RequestLogin 装配登录状态
  113. func (s *sussBi) RequestLogin(r *ghttp.Request) error {
  114. if cookies := s.jar.Cookies(s.Url); len(cookies) > 0 {
  115. r.Request.AddCookie(cookies[0])
  116. }
  117. return nil
  118. }
  119. // CheckLoginOut 检测登录状态是否过期
  120. func (s *sussBi) CheckLoginOut(r *ghttp.Request) bool {
  121. if r.Response.Status == 401 {
  122. return true
  123. }
  124. return false
  125. }
  126. func (s *sussBi) Filter(r *ghttp.Request) error {
  127. ctx := router.GetGContext(r.GetCtx())
  128. if ctx.Sess.NewUid != 0 {
  129. replaceMap := map[string]interface{}{
  130. "jyUserPositionId": ctx.Sess.UserPositionId,
  131. "jyUserAccountId": ctx.Sess.UserAccountId,
  132. "jyEntPositionId": ctx.Sess.EntPositionId,
  133. "jyEntAccountId": ctx.Sess.EntAccountId,
  134. "jyUserName": ctx.Sess.UserName,
  135. "jyEntName": ctx.Sess.EntName,
  136. "jyEntId": ctx.Sess.EntId,
  137. "jyEntUserName": ctx.Sess.EntUserName,
  138. }
  139. if r.Request.Method == http.MethodPost {
  140. bodyBytes, err := io.ReadAll(r.Request.Body)
  141. if err != nil {
  142. return err
  143. }
  144. if len(bodyBytes) > 0 {
  145. finalBytes := bodyBytes
  146. for k, v := range replaceMap {
  147. finalBytes = bytes.ReplaceAll(finalBytes, []byte(`"`+k+`"`), []byte(`"`+fmt.Sprint(v)+`"`))
  148. }
  149. r.ContentLength = gconv.Int64(len(finalBytes))
  150. r.Request.Header.Set("Content-Length", fmt.Sprintf("%d", len(finalBytes)))
  151. r.Request.Body = ioutil.NopCloser(bytes.NewReader(finalBytes))
  152. }
  153. } else if r.Request.Method == http.MethodGet {
  154. var prArr *ParamReplace
  155. if rule, ok := s.prm.eqRouters[r.URL.Path]; ok && rule != nil {
  156. prArr = rule
  157. } else {
  158. for reg, rule := range s.prm.regexRouter {
  159. if reg.MatchString(r.URL.Path) {
  160. prArr = rule
  161. break
  162. }
  163. }
  164. }
  165. if prArr != nil {
  166. if newValues, err := url.ParseQuery(r.URL.RawQuery); err == nil && len(newValues) > 0 {
  167. for _, replace := range prArr.Replace {
  168. if replace.Key != "" && replace.Value != "" && replaceMap[replace.Value] != nil {
  169. newValues[replace.Key] = []string{fmt.Sprintf("%v", replaceMap[replace.Value])}
  170. }
  171. }
  172. for _, match := range prArr.Match {
  173. if match.Key != "" && match.Value != "" {
  174. if arr := strings.Split(match.Key, "."); len(arr) == 2 && replaceMap[match.Value] != nil {
  175. if value, ok := newValues[arr[0]]; ok && len(value) > 0 {
  176. newValue := strings.ReplaceAll(value[0], arr[1], fmt.Sprintf("%v", replaceMap[match.Value]))
  177. newValues[arr[0]] = []string{newValue}
  178. }
  179. }
  180. }
  181. }
  182. r.URL.RawQuery = newValues.Encode()
  183. }
  184. }
  185. }
  186. }
  187. return nil
  188. }