Initial commit

This commit is contained in:
Donny
2019-04-22 20:46:32 +08:00
commit 49ab8aadd1
25441 changed files with 4055000 additions and 0 deletions

View File

@@ -0,0 +1,49 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = ["dao_test.go"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/answer/conf:go_default_library",
"//vendor/github.com/bouk/monkey:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = ["dao.go"],
importpath = "go-common/app/interface/main/answer/dao/geetest",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/answer/conf:go_default_library",
"//app/interface/main/answer/model:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,151 @@
package geetest
import (
"context"
"crypto/tls"
"errors"
"io/ioutil"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"go-common/app/interface/main/answer/conf"
"go-common/app/interface/main/answer/model"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
const (
_register = "/register.php"
_validate = "/validate.php"
)
// Dao is account dao.
type Dao struct {
c *conf.Config
// url
registerURI string
validateURI string
// http client
client *http.Client
clientx *bm.Client
}
// New new a dao.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
registerURI: c.Host.Geetest + _register,
validateURI: c.Host.Geetest + _validate,
// http client
client: NewClient(c.HTTPClient),
clientx: bm.NewClient(c.HTTPClient.Slow),
}
return
}
// PreProcess preprocessing the geetest and get to challenge
func (d *Dao) PreProcess(c context.Context, mid int64, ip, geeType string, gc conf.GeetestConfig, newCaptcha int) (challenge string, err error) {
var (
req *http.Request
res *http.Response
bs []byte
params url.Values
)
params = url.Values{}
params.Set("user_id", strconv.FormatInt(mid, 10))
params.Set("new_captcha", strconv.Itoa(newCaptcha))
params.Set("ip_address", ip)
params.Set("client_type", geeType)
params.Set("gt", gc.CaptchaID)
if req, err = http.NewRequest("GET", d.registerURI+"?"+params.Encode(), nil); err != nil {
log.Error("d.preprocess uri(%s) params(%s) error(%v)", d.validateURI, params.Encode(), err)
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if res, err = d.client.Do(req); err != nil {
log.Error("client.Do(%s) error(%v)", d.validateURI+"?"+params.Encode(), err)
return
}
defer res.Body.Close()
if res.StatusCode >= http.StatusInternalServerError {
err = errors.New("http status code 5xx")
log.Error("gtServerErr uri(%s) error(%v)", d.validateURI+"?"+params.Encode(), err)
return
}
if bs, err = ioutil.ReadAll(res.Body); err != nil {
log.Error("ioutil.ReadAll(%s) uri(%s) error(%v)", bs, d.validateURI+"?"+params.Encode(), err)
return
}
if len(bs) != 32 {
log.Error("d.preprocess len(%s) the length not equate 32byte", string(bs))
return
}
challenge = string(bs)
return
}
// Validate recheck the challenge code and get to seccode
func (d *Dao) Validate(c context.Context, challenge, seccode, clientType, ip, captchaID string, mid int64) (res *model.ValidateRes, err error) {
params := url.Values{}
params.Set("seccode", seccode)
params.Set("challenge", challenge)
params.Set("captchaid", captchaID)
params.Set("client_type", clientType)
params.Set("ip_address", ip)
params.Set("json_format", "1")
params.Set("sdk", "golang_3.0.0")
params.Set("user_id", strconv.FormatInt(mid, 10))
params.Set("timestamp", strconv.FormatInt(time.Now().Unix(), 10))
req, err := http.NewRequest("POST", d.validateURI, strings.NewReader(params.Encode()))
if err != nil {
log.Error("http.NewRequest error(%v) | uri(%s) params(%s)", err, d.validateURI, params.Encode())
return
}
log.Info("Validate(%v) start", params)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if err = d.clientx.Do(c, req, &res); err != nil {
log.Error("d.client.Do error(%v) | uri(%s) params(%s) res(%v)", err, d.validateURI, params.Encode(), res)
return
}
log.Info("Validate(%v) suc", res)
return
}
// NewClient new a http client.
func NewClient(c *conf.HTTPClient) (client *http.Client) {
var (
transport *http.Transport
dialer *net.Dialer
)
dialer = &net.Dialer{
Timeout: time.Duration(c.Slow.Dial),
KeepAlive: time.Duration(c.Slow.KeepAlive),
}
transport = &http.Transport{
DialContext: dialer.DialContext,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client = &http.Client{
Transport: transport,
}
return
}
// GeeConfig get geetest config.
func (d *Dao) GeeConfig(t string, c *conf.Geetest) (gc conf.GeetestConfig, geetype string) {
switch t {
case "pc":
gc = c.PC
case "h5":
gc = c.H5
default:
gc = c.PC
}
geetype = "web"
return
}

View File

@@ -0,0 +1,237 @@
package geetest
import (
"context"
"flag"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"reflect"
"strconv"
"strings"
"testing"
"time"
"go-common/app/interface/main/answer/conf"
"github.com/bouk/monkey"
"github.com/smartystreets/goconvey/convey"
gock "gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.account-law.answer")
flag.Set("conf_appid", "main.account-law.answer")
flag.Set("conf_token", "ba3ee255695e8d7b46782268ddc9c8a3")
flag.Set("tree_id", "25260")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_env", "10")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../../cmd/answer-test.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
os.Exit(m.Run())
}
func httpMock(method, url string) *gock.Request {
r := gock.New(url)
r.Method = strings.ToUpper(method)
return r
}
func TestDaoPreProcess(t *testing.T) {
var (
c = context.Background()
mid = int64(2205)
ip = "127.0.0,1"
geeType = "1222"
gc = conf.GeetestConfig{CaptchaID: "22"}
newCaptcha = 1
)
convey.Convey("PreProcess", t, func(ctx convey.C) {
ctx.Convey("req, err = http.NewRequest;err!=nil", func(ctx convey.C) {
monkey.Patch(http.NewRequest, func(_ string, _ string, _ io.Reader) (_ *http.Request, _ error) {
return nil, fmt.Errorf("Error")
})
_, err := d.PreProcess(c, mid, ip, geeType, gc, newCaptcha)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
ctx.Convey("req, err = http.NewRequest;err==nil", func(ctx convey.C) {
ctx.Convey("res, err = d.client.Do; err != nil", func(ctx convey.C) {
monkey.PatchInstanceMethod(reflect.TypeOf(d.client), "Do", func(_ *http.Client, _ *http.Request) (_ *http.Response, _ error) {
return nil, fmt.Errorf("Error")
})
_, err := d.PreProcess(c, mid, ip, geeType, gc, newCaptcha)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
ctx.Convey("res, err = d.client.Do; err == nil", func(ctx convey.C) {
params := url.Values{}
params.Set("user_id", strconv.FormatInt(mid, 10))
params.Set("new_captcha", strconv.Itoa(newCaptcha))
params.Set("ip_address", ip)
params.Set("client_type", geeType)
params.Set("gt", gc.CaptchaID)
d.client.Transport = gock.DefaultTransport
ctx.Convey("res.StatusCode >= http.StatusInternalServerError", func(ctx convey.C) {
httpMock("GET", d.registerURI+"?"+params.Encode()).Reply(501)
_, err := d.PreProcess(c, mid, ip, geeType, gc, newCaptcha)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
ctx.Convey("res.StatusCode < http.StatusInternalServerError", func(ctx convey.C) {
httpMock("GET", d.registerURI+"?"+params.Encode()).Reply(200).SetHeaders(map[string]string{
"StatusCode": "200",
})
ctx.Convey("bs, err = ioutil.ReadAll(res.Body); err != nil ", func(ctx convey.C) {
monkey.Patch(ioutil.ReadAll, func(_ io.Reader) (_ []byte, _ error) {
return nil, fmt.Errorf("Error")
})
_, err := d.PreProcess(c, mid, ip, geeType, gc, newCaptcha)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
ctx.Convey("bs, err = ioutil.ReadAll(res.Body); err == nil ", func(ctx convey.C) {
ctx.Convey("len(bs) != 32 ", func(ctx convey.C) {
challenge, err := d.PreProcess(c, mid, ip, geeType, gc, newCaptcha)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(challenge, convey.ShouldBeEmpty)
ctx.So(err, convey.ShouldBeNil)
})
})
ctx.Convey("len(bs) == 32 ", func(ctx convey.C) {
var (
str = "testeeeeeeeeeeyyyyyyyyyyyyrrrrrr"
bs = []byte(str)
)
monkey.Patch(ioutil.ReadAll, func(_ io.Reader) (_ []byte, _ error) {
return bs, nil
})
challenge, err := d.PreProcess(c, mid, ip, geeType, gc, newCaptcha)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(challenge, convey.ShouldNotBeNil)
ctx.So(err, convey.ShouldBeNil)
})
})
})
})
})
})
ctx.Reset(func() {
gock.OffAll()
d.client.Transport = http.DefaultClient.Transport
monkey.UnpatchAll()
})
})
}
func TestDaoValidate(t *testing.T) {
var (
c = context.Background()
challenge = "1"
seccode = "127.0.0,1"
clientType = ""
ip = "1222"
captchaID = "22"
mid = int64(14771787)
)
convey.Convey("Validate", t, func(ctx convey.C) {
ctx.Convey("req, err = http.NewRequest;err!=nil", func(ctx convey.C) {
monkey.Patch(http.NewRequest, func(_ string, _ string, _ io.Reader) (_ *http.Request, _ error) {
return nil, fmt.Errorf("Error")
})
_, err := d.Validate(c, challenge, seccode, clientType, ip, captchaID, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
ctx.Convey("req, err = http.NewRequest;err==nil", func(ctx convey.C) {
ctx.Convey("res, err = d.client.Do; err != nil", func(ctx convey.C) {
monkey.PatchInstanceMethod(reflect.TypeOf(d.client), "Do", func(_ *http.Client, _ *http.Request) (_ *http.Response, _ error) {
return nil, fmt.Errorf("Error")
})
_, err := d.Validate(c, challenge, seccode, clientType, ip, captchaID, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
ctx.Convey("res, err = d.client.Do; err == nil", func(ctx convey.C) {
params := url.Values{}
params.Set("seccode", seccode)
params.Set("challenge", challenge)
params.Set("captchaid", captchaID)
params.Set("client_type", clientType)
params.Set("ip_address", ip)
params.Set("json_format", "1")
params.Set("sdk", "golang_3.0.0")
params.Set("user_id", strconv.FormatInt(mid, 10))
params.Set("timestamp", strconv.FormatInt(time.Now().Unix(), 10))
// *bm.Client
d.clientx.SetTransport(gock.DefaultTransport)
httpMock("POST", d.validateURI).Reply(200).JSON(`{"code":0}`)
_, err := d.Validate(c, challenge, seccode, clientType, ip, captchaID, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
ctx.Reset(func() {
gock.OffAll()
d.clientx.SetTransport(http.DefaultClient.Transport)
monkey.UnpatchAll()
})
})
}
func TestDaoGeeConfig(t *testing.T) {
var gtc = &conf.Geetest{PC: conf.GeetestConfig{CaptchaID: "22", PrivateKEY: "123"}, H5: conf.GeetestConfig{CaptchaID: "22", PrivateKEY: "456"}}
convey.Convey("GeeConfi", t, func(ctx convey.C) {
ctx.Convey("t=pc", func(ctx convey.C) {
var t = "pc"
gc, geetype := d.GeeConfig(t, gtc)
ctx.Convey("gc=gtc.PC,geetype =web", func(ctx convey.C) {
ctx.So(gc, convey.ShouldResemble, gtc.PC)
ctx.So(geetype, convey.ShouldResemble, "web")
})
})
ctx.Convey("t=h5", func(ctx convey.C) {
var t = "h5"
gc, geetype := d.GeeConfig(t, gtc)
ctx.Convey("gc=gtc.H5,geetype =web", func(ctx convey.C) {
ctx.So(gc, convey.ShouldResemble, gtc.H5)
ctx.So(geetype, convey.ShouldResemble, "web")
})
})
ctx.Convey("t=", func(ctx convey.C) {
var t = ""
gc, geetype := d.GeeConfig(t, gtc)
ctx.Convey("gc=gtc.PC,geetype =web", func(ctx convey.C) {
ctx.So(gc, convey.ShouldResemble, gtc.PC)
ctx.So(geetype, convey.ShouldResemble, "web")
})
})
})
}