Create & Init Project...

This commit is contained in:
2019-04-22 18:49:16 +08:00
commit fc4fa37393
25440 changed files with 4054998 additions and 0 deletions

View File

@@ -0,0 +1,44 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"captchaAnti.go",
"dao.go",
"gee.go",
"liveCaptcha.go",
"redis.go",
],
importpath = "go-common/app/service/live/xcaptcha/dao",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/live/captcha/api/liverpc:go_default_library",
"//app/service/live/captcha/api/liverpc/v0:go_default_library",
"//app/service/live/captcha/api/liverpc/v1:go_default_library",
"//app/service/live/xcaptcha/conf:go_default_library",
"//library/cache/redis:go_default_library",
"//library/log:go_default_library",
"//library/net/rpc/liverpc:go_default_library",
"//library/queue/databus: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,26 @@
package dao
import (
"context"
"go-common/library/log"
"strconv"
)
// PubMessage pub to databus struct
type PubMessage struct {
RoomId int64 `json:"room_id"`
Uid int64 `json:"uid"`
Ip string `json:"ip"`
Action int `json:"action"` // 1create 2verify
ReqType int64 `json:"req_type"` // request captcha type 0image 1geetest
ResType int64 `json:"res_type"` // response captcha type 0image 1geetest
ResCode int64 `json:"res_code"` // 0success 1 failed
}
// Pub databus publish
func (d *Dao) Pub(ctx context.Context, message PubMessage) (err error) {
if err = d.captchaAnti.Send(ctx, strconv.FormatInt(message.Uid, 10), message); err != nil {
log.Error("[XCaptcha][DataBus] call for publish error, err:%v, msg:%v", err, message)
}
return
}

View File

@@ -0,0 +1,50 @@
package dao
import (
"context"
livecaptchaApi "go-common/app/service/live/captcha/api/liverpc"
"go-common/app/service/live/xcaptcha/conf"
"go-common/library/cache/redis"
"go-common/library/net/rpc/liverpc"
"go-common/library/queue/databus"
)
// Dao dao
type Dao struct {
c *conf.Config
redis *redis.Pool
geeClient *GeeClient
liveCaptcha *livecaptchaApi.Client
captchaAnti *databus.Databus
}
// New init mysql db
func New(c *conf.Config) (dao *Dao) {
dao = &Dao{
c: c,
redis: redis.NewPool(c.Redis),
geeClient: NewGeeClient(c.GeeTest),
liveCaptcha: livecaptchaApi.New(getConf("captcha")),
captchaAnti: databus.New(c.DataBus.CaptchaAnti),
}
return
}
// getConf get liveRpc conf
func getConf(appName string) *liverpc.ClientConfig {
c := conf.Conf.LiveRpc
if c != nil {
return c[appName]
}
return nil
}
// Close close the resource.
func (d *Dao) Close() {
d.redis.Close()
}
// Ping dao ping
func (d *Dao) Ping(c context.Context) error {
return nil
}

View File

@@ -0,0 +1,166 @@
package dao
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"go-common/app/service/live/xcaptcha/conf"
"io/ioutil"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const (
_register = "http://api.geetest.com/register.php"
_validate = "http://api.geetest.com/validate.php"
)
//ValidateRes 验证返回值
type ValidateRes struct {
Seccode string `json:"seccode"`
}
// GeeClient ...
type GeeClient struct {
client *http.Client
clientPost *http.Client
}
// NewGeeClient new httpClient
func NewGeeClient(c *conf.GeeTestConfig) (client *GeeClient) {
client = &GeeClient{
client: NewHttpClient(c.Get.Timeout, c.Get.KeepAlive),
clientPost: NewHttpClient(c.Post.Timeout, c.Post.KeepAlive),
}
return client
}
// Register preprocessing the geetest and get to challenge
func (d *Dao) Register(c context.Context, ip, clientType string, newCaptcha int, captchaID string) (challenge string, err error) {
challenge = ""
var (
bs []byte
params url.Values
)
params = url.Values{}
params.Set("new_captcha", strconv.Itoa(newCaptcha))
params.Set("client_type", clientType)
params.Set("ip_address", ip)
params.Set("gt", captchaID)
if bs, err = d.Get(c, _register, params); err != nil {
return
}
if len(bs) != 32 {
return
}
challenge = string(bs)
return
}
// Validate recheck the challenge code and get to seccode
func (d *Dao) Validate(c context.Context, challenge string, seccode string, clientType string, ip string, mid int64, captchaID string) (res *ValidateRes, err error) {
var (
bs []byte
params url.Values
)
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))
res = &ValidateRes{}
if bs, err = d.Post(c, _validate, params); err != nil {
return
}
if err = json.Unmarshal(bs, &res); err != nil {
return
}
return
}
// NewRequest new a http request.
func NewRequest(method, uri string, params url.Values) (req *http.Request, err error) {
if method == "GET" {
req, err = http.NewRequest(method, uri+"?"+params.Encode(), nil)
} else {
req, err = http.NewRequest(method, uri, strings.NewReader(params.Encode()))
}
if err != nil {
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return
}
// Do handler request
func (d *Dao) Do(c context.Context, req *http.Request, client *http.Client) (body []byte, err error) {
var res *http.Response
req = req.WithContext(c)
if res, err = client.Do(req); err != nil {
return
}
defer res.Body.Close()
if res.StatusCode >= http.StatusInternalServerError {
err = errors.New("http status code 5xx")
return
}
if body, err = ioutil.ReadAll(res.Body); err != nil {
return
}
return
}
// Get client.Get send GET request
func (d *Dao) Get(c context.Context, uri string, params url.Values) (body []byte, err error) {
req, err := NewRequest("GET", uri, params)
if err != nil {
return
}
body, err = d.Do(c, req, d.geeClient.client)
return
}
// Post client.Get send POST request
func (d *Dao) Post(c context.Context, uri string, params url.Values) (body []byte, err error) {
req, err := NewRequest("POST", uri, params)
if err != nil {
return
}
body, err = d.Do(c, req, d.geeClient.clientPost)
return
}
// NewHttpClient new a http client.
func NewHttpClient(timeout int64, keepAlive int64) (client *http.Client) {
var (
transport *http.Transport
dialer *net.Dialer
)
dialer = &net.Dialer{
Timeout: time.Duration(time.Duration(timeout) * time.Millisecond),
KeepAlive: time.Duration(time.Duration(keepAlive) * time.Second),
}
transport = &http.Transport{
DialContext: dialer.DialContext,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client = &http.Client{
Transport: transport,
}
return
}

View File

@@ -0,0 +1,54 @@
package dao
import (
"context"
"go-common/app/service/live/captcha/api/liverpc/v0"
"go-common/app/service/live/captcha/api/liverpc/v1"
"go-common/library/log"
)
// LiveCreate call liveRpc for create captcha
func (d *Dao) LiveCreate(ctx context.Context, width int64, height int64) (resp *v1.CaptchaCreateResp_Data, err error) {
resp = &v1.CaptchaCreateResp_Data{}
rpcReq := &v1.CaptchaCreateReq{
Width: width,
Height: height,
}
rpcResp, err := d.liveCaptcha.V1Captcha.Create(ctx, rpcReq)
if err != nil {
log.Error("[XCaptcha][Create][call liveCaptcha] call error, error:%s", err.Error())
return
}
if rpcResp.Data == nil {
log.Error("[XCaptcha][create][call liveCaptcha] return error, response.data is nil")
return
}
code := rpcResp.Code
msg := rpcResp.Msg
if code != 0 {
log.Error("[XCaptcha][Create][call liveCaptcha] create error, code:%s, msg:%s, data:%s", code, msg, resp)
return
}
resp = rpcResp.Data
return
}
// LiveCheck liveCaptcha check
func (d *Dao) LiveCheck(ctx context.Context, token string, phrase string) (resp int64, err error) {
resp = -400
rpcReq := &v0.CaptchaCheckReq{
Token: token,
Phrase: phrase,
}
rpcResp, err := d.liveCaptcha.V0Captcha.Check(ctx, rpcReq)
if err != nil {
log.Error("[XCaptcha][verify][call liveCaptcha] call error, error:%s", err.Error())
return
}
if rpcResp == nil {
log.Error("[XCaptcha][verify][call liveCaptcha] return error, response is nil")
return
}
resp = rpcResp.Code
return
}

View File

@@ -0,0 +1,72 @@
package dao
import (
"context"
"go-common/library/cache/redis"
"go-common/library/log"
)
// RedisIncr incr a key
func (d *Dao) RedisIncr(ctx context.Context, key string) (num int64, err error) {
num = 0
conn := d.redis.Get(ctx)
defer conn.Close()
err = conn.Send("INCR", key)
if err != nil {
log.Error("[XCaptcha][Redis][error] conn.Send error(%v)", err)
return
}
err = conn.Send("EXPIRE", key, 3)
if err != nil {
log.Error("[XCaptcha][Redis][error] conn.Send error(%v)", err)
return
}
err = conn.Flush()
if err != nil {
log.Error("[XCaptcha][Redis][error] conn.Flush error(%v)", err)
return
}
if num, err = redis.Int64(conn.Receive()); err != nil {
log.Error("[XCaptcha][Redis][error] INCR conn.Receive error(%v)", key, err)
return
}
if _, err = conn.Receive(); err != nil {
log.Error("[XCaptcha][Redis][error] EXPIRE conn.Receive error(%v)", key, err)
return
}
return
}
// RedisGet get a string
func (d *Dao) RedisGet(ctx context.Context, key string) (value int64, err error) {
value = 0
conn := d.redis.Get(ctx)
defer conn.Close()
if value, err = redis.Int64(conn.Do("GET", key)); err != nil {
log.Error("[XCaptcha][Redis][error] GET conn.do error(%v)", key, err)
return
}
return
}
// RedisSet Set a string and expire
func (d *Dao) RedisSet(ctx context.Context, key string, value int64, timeout int64) (err error) {
conn := d.redis.Get(ctx)
defer conn.Close()
if _, err = conn.Do("SET", key, value, "EX", timeout); err != nil {
log.Error("[XCaptcha][Redis][error] SET conn.do error(%v)", key, err)
return
}
return
}
// RedisDel delete a key
func (d *Dao) RedisDel(ctx context.Context, key string) (err error) {
conn := d.redis.Get(ctx)
defer conn.Close()
if _, err = conn.Do("DEL", key); err != nil {
log.Error("[XCaptcha][Redis][error] Delete conn.do error(%v)", key, err)
return
}
return
}