package outServer import ( "bytes" "fmt" "io" "io/ioutil" "net/http" "net/http/cookiejar" "net/url" "bp.jydev.jianyu360.cn/BaseService/gateway/core/router" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/util/gconv" "golang.org/x/net/publicsuffix" ) type sussBi struct { addr string user string pwd string Url *url.URL jar *cookiejar.Jar } func InitSussBi(address, user, password string) *sussBi { sussCookie, _ := cookiejar.New(&cookiejar.Options{ PublicSuffixList: publicsuffix.List, }) u, _ := url.Parse(address) return &sussBi{ addr: address, user: user, Url: u, pwd: password, jar: sussCookie, } } // AutoLogin 自动登录 func (s *sussBi) AutoLogin() error { client := &http.Client{ Jar: s.jar, } resp, err := client.Get(fmt.Sprintf("%s/?:user=%s&:password=%s", s.addr, s.user, s.pwd)) if err != nil { return err } if !(resp.StatusCode == 302 || resp.StatusCode == 200) { return fmt.Errorf("自动登录异常") } return nil } // RequestLogin 装配登录状态 func (s *sussBi) RequestLogin(r *ghttp.Request) error { if cookies := s.jar.Cookies(s.Url); len(cookies) > 0 { r.Request.AddCookie(cookies[0]) } return nil } // CheckLoginOut 检测登录状态是否过期 func (s *sussBi) CheckLoginOut(r *ghttp.Request) bool { if r.Response.Status == 401 { return true } return false } func (s *sussBi) Filter(r *ghttp.Request) error { ctx := router.GetGContext(r.GetCtx()) if ctx.Sess.NewUid != 0 && r.Request.Method == http.MethodPost { bodyBytes, err := io.ReadAll(r.Request.Body) if err != nil { return err } if len(bodyBytes) > 0 { replaceMap := map[string]interface{}{ "jyUserPositionId": ctx.Sess.UserPositionId, "jyUserAccountId": ctx.Sess.UserAccountId, "jyEntPositionId": ctx.Sess.EntPositionId, "jyEntAccountId": ctx.Sess.EntAccountId, "jyUserName": ctx.Sess.UserName, "jyEntName": ctx.Sess.EntName, "jyEntId": ctx.Sess.EntId, "jyEntUserName": ctx.Sess.EntUserName, } finalBytes := bytes.ReplaceAll(bodyBytes, []byte(`"jyUserId"`), []byte(fmt.Sprintf(`"%d"`, ctx.Sess.NewUid))) for k, v := range replaceMap { finalBytes = bytes.ReplaceAll(finalBytes, []byte(`"`+k+`"`), []byte(`"`+fmt.Sprint(v)+`"`)) } r.ContentLength = gconv.Int64(len(finalBytes)) r.Request.Header.Set("Content-Length", fmt.Sprintf("%d", len(finalBytes))) //fmt.Printf("before len:%d value:%s\nafter: len:%d value:%s\n", len(bodyBytes), string(bodyBytes), len(finalBytes), string(finalBytes)) //fmt.Printf("header %+v\n", r.Request.Header) r.Request.Body = ioutil.NopCloser(bytes.NewReader(finalBytes)) } } return nil }