SussBi.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. loginAddr string
  20. user string
  21. pwd string
  22. Url *url.URL
  23. cookiePath string
  24. jar *cookiejar.Jar
  25. succbiJar *cookiejar.Jar
  26. prm *ParamReplaceManager
  27. }
  28. // 参数替换
  29. type ParamReplace struct {
  30. Replace []ParamReplaceSetting
  31. Match []ParamReplaceSetting
  32. }
  33. type ParamReplaceSetting struct {
  34. Key, Value string
  35. }
  36. type ParamReplaceManager struct {
  37. eqRouters map[string]*ParamReplace
  38. regexRouter map[*regexp.Regexp]*ParamReplace
  39. }
  40. func InitSussBi(config map[string]interface{}) (*sussBi, error) {
  41. address := gconv.String(config["addr"])
  42. user := gconv.String(config["user"])
  43. password := gconv.String(config["password"])
  44. paramReplace := gconv.Map(config["paramReplace"])
  45. cookiePath := gconv.String(config["cookiePath"])
  46. loginAddr := gconv.String(config["loginAddr"])
  47. if address == "" {
  48. return nil, fmt.Errorf("配置异常")
  49. }
  50. sussCookie, err := cookiejar.New(&cookiejar.Options{
  51. PublicSuffixList: publicsuffix.List,
  52. })
  53. if err != nil {
  54. return nil, fmt.Errorf("初始化cookie异常")
  55. }
  56. sussCookie2, err2 := cookiejar.New(&cookiejar.Options{
  57. PublicSuffixList: publicsuffix.List,
  58. })
  59. if err2 != nil {
  60. return nil, fmt.Errorf("初始化cookie异常")
  61. }
  62. prManager := &ParamReplaceManager{
  63. eqRouters: map[string]*ParamReplace{},
  64. regexRouter: map[*regexp.Regexp]*ParamReplace{},
  65. }
  66. for url, setting := range paramReplace {
  67. pr := &ParamReplace{}
  68. settingMap := gconv.Map(setting)
  69. if settingMap == nil || len(settingMap) == 0 {
  70. continue
  71. }
  72. if replaceMap := gconv.Map(settingMap["replace"]); replaceMap != nil && len(replaceMap) > 0 {
  73. for k, v := range replaceMap {
  74. pr.Replace = append(pr.Replace, ParamReplaceSetting{
  75. Key: k,
  76. Value: gconv.String(v),
  77. })
  78. }
  79. }
  80. replaceMap := gconv.Map(settingMap["match"])
  81. if replaceMap != nil && len(replaceMap) > 0 {
  82. for k, v := range replaceMap {
  83. pr.Match = append(pr.Match, ParamReplaceSetting{
  84. Key: k,
  85. Value: gconv.String(v),
  86. })
  87. }
  88. }
  89. if len(pr.Match) == 0 && len(pr.Replace) == 0 {
  90. continue
  91. }
  92. if regexp.QuoteMeta(url) == url {
  93. prManager.eqRouters[url] = pr
  94. } else {
  95. if reg, err := regexp.Compile(url); err == nil {
  96. prManager.regexRouter[reg] = pr
  97. }
  98. }
  99. }
  100. u, _ := url.Parse(address)
  101. return &sussBi{
  102. addr: address,
  103. user: user,
  104. Url: u,
  105. pwd: password,
  106. loginAddr: loginAddr,
  107. cookiePath: cookiePath,
  108. jar: sussCookie,
  109. succbiJar: sussCookie2,
  110. prm: prManager,
  111. }, nil
  112. }
  113. // AutoLogin 自动登录
  114. func (s *sussBi) AutoLogin() error {
  115. client := &http.Client{
  116. Jar: s.jar,
  117. }
  118. resp, err := client.Get(fmt.Sprintf("%s/?:user=%s&:password=%s", s.addr, s.user, s.pwd))
  119. if err != nil {
  120. return err
  121. }
  122. if !(resp.StatusCode == 302 || resp.StatusCode == 200) {
  123. return fmt.Errorf("自动登录异常")
  124. }
  125. client.Jar = s.succbiJar
  126. resp, err = client.Get(fmt.Sprintf("%s/succbi/?:user=%s&:password=%s", s.addr, s.user, s.pwd))
  127. if err != nil {
  128. return err
  129. }
  130. if !(resp.StatusCode == 302 || resp.StatusCode == 200) {
  131. return fmt.Errorf("自动登录异常")
  132. }
  133. return nil
  134. }
  135. // RequestLogin 装配登录状态
  136. func (s *sussBi) RequestLogin(r *ghttp.Request) error {
  137. if strings.HasPrefix(r.URL.Path, "/succbi") {
  138. u, e := url.Parse(s.Url.String() + "/succbi")
  139. if e != nil {
  140. return e
  141. }
  142. cookies2 := s.succbiJar.Cookies(s.Url)
  143. fmt.Println(cookies2)
  144. if cookies := s.succbiJar.Cookies(u); len(cookies) > 0 {
  145. r.Request.AddCookie(cookies[0])
  146. }
  147. } else {
  148. if cookies := s.jar.Cookies(s.Url); len(cookies) > 0 {
  149. r.Request.AddCookie(cookies[0])
  150. }
  151. }
  152. return nil
  153. }
  154. // CheckLoginOut 检测登录状态是否过期
  155. func (s *sussBi) CheckLoginOut(r *ghttp.Request) bool {
  156. if r.Response.Status == 401 {
  157. return true
  158. }
  159. return false
  160. }
  161. func (s *sussBi) Filter(r *ghttp.Request) error {
  162. ctx := router.GetGContext(r.GetCtx())
  163. if ctx.Sess.NewUid != 0 {
  164. replaceMap := map[string]interface{}{
  165. "jyUserId": ctx.Sess.NewUid,
  166. // "jyUserPositionId": ctx.Sess.UserPositionId,
  167. // "jyUserAccountId": ctx.Sess.UserAccountId,
  168. // "jyEntPositionId": ctx.Sess.EntUserPositionId,
  169. // "jyEntAccountId": ctx.Sess.EntAccountId,
  170. "jyUserPositionId": ctx.Sess.PositionId,
  171. "jyUserAccountId": ctx.Sess.AccountId,
  172. "jyEntPositionId": ctx.Sess.PositionId,
  173. "jyEntAccountId": ctx.Sess.EntAccountId,
  174. "jyUserName": ctx.Sess.UserName,
  175. "jyEntName": ctx.Sess.EntName,
  176. "jyEntId": ctx.Sess.EntId,
  177. "jyEntUserName": ctx.Sess.EntUserName,
  178. }
  179. if r.Request.Method == http.MethodPost {
  180. bodyBytes, err := io.ReadAll(r.Request.Body)
  181. if err != nil {
  182. return err
  183. }
  184. if len(bodyBytes) > 0 {
  185. finalBytes := bodyBytes
  186. for k, v := range replaceMap {
  187. finalBytes = bytes.ReplaceAll(finalBytes, []byte(`"`+k+`"`), []byte(`"`+fmt.Sprint(v)+`"`))
  188. }
  189. r.ContentLength = gconv.Int64(len(finalBytes))
  190. r.Request.Header.Set("Content-Length", fmt.Sprintf("%d", len(finalBytes)))
  191. r.Request.Body = ioutil.NopCloser(bytes.NewReader(finalBytes))
  192. }
  193. } else if r.Request.Method == http.MethodGet {
  194. var prArr *ParamReplace
  195. if rule, ok := s.prm.eqRouters[r.URL.Path]; ok && rule != nil {
  196. prArr = rule
  197. } else {
  198. for reg, rule := range s.prm.regexRouter {
  199. if reg.MatchString(r.URL.Path) {
  200. prArr = rule
  201. break
  202. }
  203. }
  204. }
  205. if prArr != nil {
  206. if newValues, err := url.ParseQuery(r.URL.RawQuery); err == nil && len(newValues) > 0 {
  207. for _, replace := range prArr.Replace {
  208. if replace.Key != "" && replace.Value != "" && replaceMap[replace.Value] != nil {
  209. newValues[replace.Key] = []string{fmt.Sprintf("%v", replaceMap[replace.Value])}
  210. }
  211. }
  212. for _, match := range prArr.Match {
  213. if match.Key != "" && match.Value != "" {
  214. if arr := strings.Split(match.Key, "."); len(arr) == 2 && replaceMap[match.Value] != nil {
  215. if value, ok := newValues[arr[0]]; ok && len(value) > 0 {
  216. newValue := strings.ReplaceAll(value[0], arr[1], fmt.Sprintf("%v", replaceMap[match.Value]))
  217. newValues[arr[0]] = []string{newValue}
  218. }
  219. }
  220. }
  221. }
  222. r.URL.RawQuery = newValues.Encode()
  223. }
  224. }
  225. }
  226. }
  227. return nil
  228. }