SussBi.go 6.7 KB

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