SussBi.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. return true
  159. if r.Response.Status == 401 {
  160. return true
  161. }
  162. return false
  163. }
  164. func (s *sussBi) Filter(r *ghttp.Request) error {
  165. ctx := router.GetGContext(r.GetCtx())
  166. http.SetCookie(r.Response.ResponseWriter, &http.Cookie{
  167. Name: "BITOKEN",
  168. 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)),
  169. Path: "/",
  170. HttpOnly: false,
  171. MaxAge: 604800,
  172. Expires: time.Now().AddDate(0, 0, 7),
  173. })
  174. if ctx.Sess.NewUid != 0 {
  175. replaceMap := map[string]interface{}{
  176. "jyUserId": ctx.Sess.PositionId,
  177. "jyUserPositionId": ctx.Sess.PositionId,
  178. "jyUserAccountId": ctx.Sess.AccountId,
  179. "jyEntPositionId": ctx.Sess.PositionId,
  180. "jyEntAccountId": ctx.Sess.EntAccountId,
  181. "jyUserName": ctx.Sess.UserName,
  182. "jyEntName": ctx.Sess.EntName,
  183. "jyEntId": ctx.Sess.EntId,
  184. "jyEntUserName": ctx.Sess.EntUserName,
  185. "jyEntUserId": ctx.Sess.EntUserId,
  186. }
  187. if r.Request.Method == http.MethodPost {
  188. bodyBytes, err := io.ReadAll(r.Request.Body)
  189. if err != nil {
  190. return err
  191. }
  192. if len(bodyBytes) > 0 {
  193. finalBytes := bodyBytes
  194. for k, v := range replaceMap {
  195. finalBytes = bytes.ReplaceAll(finalBytes, []byte(`"`+k+`"`), []byte(`"`+fmt.Sprint(v)+`"`))
  196. }
  197. r.ContentLength = gconv.Int64(len(finalBytes))
  198. r.Request.Header.Set("Content-Length", fmt.Sprintf("%d", len(finalBytes)))
  199. r.Request.Body = ioutil.NopCloser(bytes.NewReader(finalBytes))
  200. }
  201. } else if r.Request.Method == http.MethodGet {
  202. var prArr *ParamReplace
  203. if rule, ok := s.prm.eqRouters[r.URL.Path]; ok && rule != nil {
  204. prArr = rule
  205. } else {
  206. for reg, rule := range s.prm.regexRouter {
  207. if reg.MatchString(r.URL.Path) {
  208. prArr = rule
  209. break
  210. }
  211. }
  212. }
  213. if prArr != nil {
  214. if newValues, err := url.ParseQuery(r.URL.RawQuery); err == nil && len(newValues) > 0 {
  215. for _, replace := range prArr.Replace {
  216. if replace.Key != "" && replace.Value != "" && replaceMap[replace.Value] != nil {
  217. newValues[replace.Key] = []string{fmt.Sprintf("%v", replaceMap[replace.Value])}
  218. }
  219. }
  220. for _, match := range prArr.Match {
  221. if match.Key != "" && match.Value != "" {
  222. if arr := strings.Split(match.Key, "."); len(arr) == 2 && replaceMap[match.Value] != nil {
  223. if value, ok := newValues[arr[0]]; ok && len(value) > 0 {
  224. newValue := strings.ReplaceAll(value[0], arr[1], fmt.Sprintf("%v", replaceMap[match.Value]))
  225. newValues[arr[0]] = []string{newValue}
  226. }
  227. }
  228. }
  229. }
  230. r.URL.RawQuery = newValues.Encode()
  231. }
  232. }
  233. }
  234. }
  235. return nil
  236. }