SussBi.go 7.3 KB

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