SussBi.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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.succbiJar,
  122. }
  123. resp, err := client.Get(fmt.Sprintf("%s/succbi/?: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. s.succbiJar = s.jar
  131. // client.Jar = s.succbiJar
  132. // resp, err = client.Get(fmt.Sprintf("%s/succbi/?:user=%s&:password=%s", s.addr, s.user, s.pwd))
  133. // if err != nil {
  134. // return err
  135. // }
  136. // if !(resp.StatusCode == 302 || resp.StatusCode == 200) {
  137. // return fmt.Errorf("自动登录异常")
  138. // }
  139. return nil
  140. }
  141. // RequestLogin 装配登录状态
  142. func (s *sussBi) RequestLogin(r *ghttp.Request) error {
  143. if s.singlePointUrl.MatchString(r.RequestURI) {
  144. ctx := router.GetGContext(r.GetCtx())
  145. 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))
  146. c := &http.Cookie{
  147. Name: "BITOKEN",
  148. Value: md5Val,
  149. Path: "/",
  150. HttpOnly: false,
  151. MaxAge: 604800,
  152. Expires: time.Now().AddDate(0, 0, 7),
  153. }
  154. r.Request.AddCookie(c)
  155. log.Println(ctx.Sess.PositionId, "BITOKEN====", md5Val)
  156. //http.SetCookie(r.Response.ResponseWriter, c)
  157. } else {
  158. if strings.HasPrefix(r.URL.Path, "/succbi") {
  159. u, e := url.Parse(s.Url.String() + "/succbi")
  160. if e != nil {
  161. log.Println("RequestLogin url.Parse error", e)
  162. return e
  163. }
  164. log.Println("succbiJar----", u.Path, u.RequestURI(), s.succbiJar.Cookies(u))
  165. if cookies := s.succbiJar.Cookies(u); len(cookies) > 0 {
  166. log.Println("RequestLogin AddCookie", cookies[0])
  167. r.Request.AddCookie(cookies[0])
  168. }
  169. } else {
  170. if cookies := s.jar.Cookies(s.Url); len(cookies) > 0 {
  171. r.Request.AddCookie(cookies[0])
  172. }
  173. }
  174. }
  175. return nil
  176. }
  177. // CheckLoginOut 检测登录状态是否过期
  178. func (s *sussBi) CheckLoginOut(r *ghttp.Request) bool {
  179. if r.Response.Status == 401 {
  180. return true
  181. }
  182. return false
  183. }
  184. func (s *sussBi) Filter(r *ghttp.Request) error {
  185. ctx := router.GetGContext(r.GetCtx())
  186. if ctx.Sess.NewUid != 0 {
  187. replaceMap := map[string]interface{}{
  188. "jyUserId": ctx.Sess.PositionId,
  189. "jyUserPositionId": ctx.Sess.PositionId,
  190. "jyUserAccountId": ctx.Sess.AccountId,
  191. "jyEntPositionId": ctx.Sess.PositionId,
  192. "jyEntAccountId": ctx.Sess.EntAccountId,
  193. "jyUserName": ctx.Sess.UserName,
  194. "jyEntName": ctx.Sess.EntName,
  195. "jyEntId": ctx.Sess.EntId,
  196. "jyEntUserName": ctx.Sess.EntUserName,
  197. "jyEntUserId": ctx.Sess.EntUserId,
  198. }
  199. if r.Request.Method == http.MethodPost {
  200. bodyBytes, err := io.ReadAll(r.Request.Body)
  201. if err != nil {
  202. return err
  203. }
  204. if len(bodyBytes) > 0 {
  205. finalBytes := bodyBytes
  206. for k, v := range replaceMap {
  207. finalBytes = bytes.ReplaceAll(finalBytes, []byte(`"`+k+`"`), []byte(`"`+fmt.Sprint(v)+`"`))
  208. }
  209. r.ContentLength = gconv.Int64(len(finalBytes))
  210. r.Request.Header.Set("Content-Length", fmt.Sprintf("%d", len(finalBytes)))
  211. r.Request.Body = ioutil.NopCloser(bytes.NewReader(finalBytes))
  212. }
  213. } else if r.Request.Method == http.MethodGet {
  214. var prArr *ParamReplace
  215. if rule, ok := s.prm.eqRouters[r.URL.Path]; ok && rule != nil {
  216. prArr = rule
  217. } else {
  218. for reg, rule := range s.prm.regexRouter {
  219. if reg.MatchString(r.URL.Path) {
  220. prArr = rule
  221. break
  222. }
  223. }
  224. }
  225. if prArr != nil {
  226. if newValues, err := url.ParseQuery(r.URL.RawQuery); err == nil && len(newValues) > 0 {
  227. for _, replace := range prArr.Replace {
  228. if replace.Key != "" && replace.Value != "" && replaceMap[replace.Value] != nil {
  229. newValues[replace.Key] = []string{fmt.Sprintf("%v", replaceMap[replace.Value])}
  230. }
  231. }
  232. for _, match := range prArr.Match {
  233. if match.Key != "" && match.Value != "" {
  234. if arr := strings.Split(match.Key, "."); len(arr) == 2 && replaceMap[match.Value] != nil {
  235. if value, ok := newValues[arr[0]]; ok && len(value) > 0 {
  236. newValue := strings.ReplaceAll(value[0], arr[1], fmt.Sprintf("%v", replaceMap[match.Value]))
  237. newValues[arr[0]] = []string{newValue}
  238. }
  239. }
  240. }
  241. }
  242. r.URL.RawQuery = newValues.Encode()
  243. }
  244. }
  245. }
  246. }
  247. return nil
  248. }