SussBi.go 7.0 KB

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