SussBi.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. "time"
  13. "app.yhyue.com/moapp/jybase/common"
  14. "bp.jydev.jianyu360.cn/BaseService/gateway/core/router"
  15. "github.com/gogf/gf/v2/net/ghttp"
  16. "github.com/gogf/gf/v2/util/gconv"
  17. "golang.org/x/net/publicsuffix"
  18. )
  19. type sussBi struct {
  20. addr string
  21. loginAddr string
  22. user string
  23. pwd string
  24. Url *url.URL
  25. cookiePath string
  26. jar *cookiejar.Jar
  27. succbiJar *cookiejar.Jar
  28. prm *ParamReplaceManager
  29. }
  30. // 参数替换
  31. type ParamReplace struct {
  32. Replace []ParamReplaceSetting
  33. Match []ParamReplaceSetting
  34. }
  35. type ParamReplaceSetting struct {
  36. Key, Value string
  37. }
  38. type ParamReplaceManager struct {
  39. eqRouters map[string]*ParamReplace
  40. regexRouter map[*regexp.Regexp]*ParamReplace
  41. }
  42. func InitSussBi(config map[string]interface{}) (*sussBi, error) {
  43. address := gconv.String(config["addr"])
  44. user := gconv.String(config["user"])
  45. password := gconv.String(config["password"])
  46. paramReplace := gconv.Map(config["paramReplace"])
  47. cookiePath := gconv.String(config["cookiePath"])
  48. loginAddr := gconv.String(config["loginAddr"])
  49. if address == "" {
  50. return nil, fmt.Errorf("配置异常")
  51. }
  52. sussCookie, err := cookiejar.New(&cookiejar.Options{
  53. PublicSuffixList: publicsuffix.List,
  54. })
  55. if err != nil {
  56. return nil, fmt.Errorf("初始化cookie异常")
  57. }
  58. sussCookie2, err2 := cookiejar.New(&cookiejar.Options{
  59. PublicSuffixList: publicsuffix.List,
  60. })
  61. if err2 != nil {
  62. return nil, fmt.Errorf("初始化cookie异常")
  63. }
  64. prManager := &ParamReplaceManager{
  65. eqRouters: map[string]*ParamReplace{},
  66. regexRouter: map[*regexp.Regexp]*ParamReplace{},
  67. }
  68. for url, setting := range paramReplace {
  69. pr := &ParamReplace{}
  70. settingMap := gconv.Map(setting)
  71. if settingMap == nil || len(settingMap) == 0 {
  72. continue
  73. }
  74. if replaceMap := gconv.Map(settingMap["replace"]); replaceMap != nil && len(replaceMap) > 0 {
  75. for k, v := range replaceMap {
  76. pr.Replace = append(pr.Replace, ParamReplaceSetting{
  77. Key: k,
  78. Value: gconv.String(v),
  79. })
  80. }
  81. }
  82. replaceMap := gconv.Map(settingMap["match"])
  83. if replaceMap != nil && len(replaceMap) > 0 {
  84. for k, v := range replaceMap {
  85. pr.Match = append(pr.Match, ParamReplaceSetting{
  86. Key: k,
  87. Value: gconv.String(v),
  88. })
  89. }
  90. }
  91. if len(pr.Match) == 0 && len(pr.Replace) == 0 {
  92. continue
  93. }
  94. if regexp.QuoteMeta(url) == url {
  95. prManager.eqRouters[url] = pr
  96. } else {
  97. if reg, err := regexp.Compile(url); err == nil {
  98. prManager.regexRouter[reg] = pr
  99. }
  100. }
  101. }
  102. u, _ := url.Parse(address)
  103. return &sussBi{
  104. addr: address,
  105. user: user,
  106. Url: u,
  107. pwd: password,
  108. loginAddr: loginAddr,
  109. cookiePath: cookiePath,
  110. jar: sussCookie,
  111. succbiJar: sussCookie2,
  112. prm: prManager,
  113. }, nil
  114. }
  115. // AutoLogin 自动登录
  116. func (s *sussBi) AutoLogin() error {
  117. client := &http.Client{
  118. Jar: s.jar,
  119. }
  120. resp, err := client.Get(fmt.Sprintf("%s/?:user=%s&:password=%s", s.addr, s.user, s.pwd))
  121. if err != nil {
  122. return err
  123. }
  124. if !(resp.StatusCode == 302 || resp.StatusCode == 200) {
  125. return fmt.Errorf("自动登录异常")
  126. }
  127. client.Jar = s.succbiJar
  128. resp, err = client.Get(fmt.Sprintf("%s/succbi/?:user=%s&:password=%s", s.addr, s.user, s.pwd))
  129. if err != nil {
  130. return err
  131. }
  132. if !(resp.StatusCode == 302 || resp.StatusCode == 200) {
  133. return fmt.Errorf("自动登录异常")
  134. }
  135. return nil
  136. }
  137. // RequestLogin 装配登录状态
  138. func (s *sussBi) RequestLogin(r *ghttp.Request) error {
  139. if strings.HasPrefix(r.URL.Path, "/succbi") {
  140. u, e := url.Parse(s.Url.String() + "/succbi")
  141. if e != nil {
  142. return e
  143. }
  144. //cookies2 := s.succbiJar.Cookies(s.Url)
  145. //fmt.Println(cookies2)
  146. if cookies := s.succbiJar.Cookies(u); len(cookies) > 0 {
  147. r.Request.AddCookie(cookies[0])
  148. }
  149. } else {
  150. if cookies := s.jar.Cookies(s.Url); len(cookies) > 0 {
  151. r.Request.AddCookie(cookies[0])
  152. }
  153. }
  154. return nil
  155. }
  156. // CheckLoginOut 检测登录状态是否过期
  157. func (s *sussBi) CheckLoginOut(r *ghttp.Request) bool {
  158. if r.Response.Status == 401 {
  159. return true
  160. }
  161. return false
  162. }
  163. func (s *sussBi) Filter(r *ghttp.Request) error {
  164. ctx := router.GetGContext(r.GetCtx())
  165. 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))
  166. if j_cookie, j_error := r.Request.Cookie("JSESSIONID"); j_error == nil && j_cookie != nil && j_cookie.Value != md5Val {
  167. http.SetCookie(r.Response.ResponseWriter, &http.Cookie{
  168. Name: "JSESSIONID",
  169. MaxAge: -1,
  170. })
  171. }
  172. http.SetCookie(r.Response.ResponseWriter, &http.Cookie{
  173. Name: "BITOKEN",
  174. Value: md5Val,
  175. Path: "/",
  176. HttpOnly: false,
  177. MaxAge: 604800,
  178. Expires: time.Now().AddDate(0, 0, 7),
  179. })
  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. }