SussBi.go 7.1 KB

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