package controllers
import (
"crypto/md5"
"encoding/json"
"errors"
"fmt"
"github.com/beego/beego/v2/server/web"
"github.com/shopspring/decimal"
"math"
"net/http"
"net/url"
"reflect"
"sort"
"strconv"
"strings"
"time"
"eta/eta_data_push/models"
"eta/eta_data_push/utils"
)
type BaseAuthController struct {
web.Controller
}
func (this *BaseAuthController) Prepare() {
fmt.Println("enter prepare")
method := this.Ctx.Input.Method()
uri := this.Ctx.Input.URI()
fmt.Println("Url:", uri)
if method != "HEAD" {
if method == "POST" {
ok, errMsg := checkSign(this)
if !ok {
this.JSON(models.BaseResponse{Ret: 408, Msg: "签名错误!", ErrMsg: errMsg}, false, false)
this.StopRun()
return
}
} else {
this.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
this.StopRun()
return
}
} else {
this.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "method:" + method}, false, false)
this.StopRun()
return
}
}
func checkSign(c *BaseAuthController) (ok bool, errMsg string) {
method := c.Ctx.Input.Method()
signData := make(map[string]string)
switch method {
case "GET":
//requestBody = c.Ctx.Request.RequestURI
params := c.Ctx.Request.URL.Query()
signData = convertParam(params)
case "POST":
//requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
//请求类型
contentType := c.Ctx.Request.Header.Get("content-type")
//fmt.Println("contentType:", contentType)
//fmt.Println("c.Ctx.Input.RequestBody:", string(c.Ctx.Input.RequestBody))
switch contentType {
case "multipart/form-data":
//文件最大5M
err := c.Ctx.Request.ParseMultipartForm(-int64(5 << 20))
if err != nil {
errMsg = fmt.Sprintf("获取参数失败,%v", err)
return
}
params := c.Ctx.Request.Form
signData = convertParam(params)
case "application/x-www-form-urlencoded":
err := c.Ctx.Request.ParseForm()
if err != nil {
errMsg = fmt.Sprintf("获取参数失败,%v", err)
return
}
params := c.Ctx.Request.Form
signData = convertParam(params)
case "application/json":
//var v interface{}
params := make(map[string]interface{})
err := json.Unmarshal(c.Ctx.Input.RequestBody, ¶ms)
if err != nil {
errMsg = fmt.Sprintf("获取参数失败,%v", err)
return
}
//fmt.Println("params:", params)
signData = convertParamInterface(params)
//tmpV := v.(map[string]string)
//fmt.Println("tmpV:", tmpV)
//fmt.Sprintln("list type is v%", tmpV["list"])
default: //正常应该是其他方式获取解析的,暂时这么处理吧
err := c.Ctx.Request.ParseForm()
if err != nil {
errMsg = fmt.Sprintf("获取参数失败,%v", err)
return
}
params := c.Ctx.Request.Form
signData = convertParam(params)
}
}
// 开始校验数据
ip := c.Ctx.Input.IP()
err := checkSignData(signData, ip)
if err != nil {
errMsg = fmt.Sprintf("签名校验失败,%v", err)
return
}
ok = true
return
}
func (c *BaseAuthController) ServeJSON(encoding ...bool) {
// 方法处理完后,需要后置处理的业务逻辑
//if handlerList, ok := AfterHandlerUrlMap[c.Ctx.Request.URL.Path]; ok {
// for _, handler := range handlerList {
// handler(c.Ctx.Input.RequestBody)
// }
//}
//所有请求都做这么个处理吧,目前这边都是做编辑、刷新逻辑处理(新增的话,并没有指标id,不会有影响)
var (
hasIndent = false
hasEncoding = false
)
if web.BConfig.RunMode == web.PROD {
hasIndent = false
}
if len(encoding) > 0 && encoding[0] == true {
hasEncoding = true
}
if c.Data["json"] == nil {
go utils.SendEmail("异常提醒:", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值", utils.EmailSendToUsers)
return
}
baseRes := c.Data["json"].(*models.BaseResponse)
if baseRes != nil && baseRes.Ret != 408 {
body, _ := json.Marshal(baseRes)
var requestBody string
method := c.Ctx.Input.Method()
if method == "GET" {
requestBody = c.Ctx.Request.RequestURI
} else {
requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
}
if baseRes.Ret != 200 && baseRes.IsSendEmail {
go utils.SendEmail(utils.APP_NAME_CN+"【"+utils.RunMode+"】"+"失败提醒", "URI:"+c.Ctx.Input.URI()+"
"+"Params"+requestBody+"
"+"ErrMsg:"+baseRes.ErrMsg+";
Msg:"+baseRes.Msg+";
Body:"+string(body)+"
", utils.EmailSendToUsers)
}
}
c.JSON(c.Data["json"], hasIndent, hasEncoding)
}
func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool) error {
c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
var content []byte
var err error
if hasIndent {
content, err = json.MarshalIndent(data, "", " ")
} else {
content, err = json.Marshal(data)
}
if err != nil {
http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
return err
}
ip := c.Ctx.Input.IP()
requestBody, err := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
if err != nil {
requestBody = string(c.Ctx.Input.RequestBody)
}
if requestBody == "" {
requestBody = c.Ctx.Input.URI()
}
c.logUri(content, requestBody, ip)
if coding {
content = []byte(utils.StringsToJSON(string(content)))
}
return c.Ctx.Output.Body(content)
}
// 将请求传入的数据格式转换成签名需要的格式
func convertParam(params map[string][]string) (signData map[string]string) {
signData = make(map[string]string)
for key := range params {
signData[key] = params[key][0]
}
return signData
}
// 将请求传入的数据格式转换成签名需要的格式(目前只能处理简单的类型,数组、对象暂不支持)
func convertParamInterface(params map[string]interface{}) (signData map[string]string) {
signData = make(map[string]string)
for key := range params {
val := ``
//fmt.Println("key", key, ";val:", params[key], ";type:", reflect.TypeOf(params[key]))
//signData[key] = params[key][0]
tmpVal := params[key]
switch reflect.TypeOf(tmpVal).Kind() {
case reflect.String:
val = fmt.Sprint(tmpVal)
case reflect.Int, reflect.Int16, reflect.Int64, reflect.Int32, reflect.Int8:
val = fmt.Sprint(tmpVal)
case reflect.Uint, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint64:
val = fmt.Sprint(tmpVal)
case reflect.Bool:
val = fmt.Sprint(tmpVal)
case reflect.Float64:
decimalNum := decimal.NewFromFloat(tmpVal.(float64))
val = decimalNum.String()
//val = strconv.FormatFloat(tmpVal.(float64), 'E', -1, 64) //float64
case reflect.Float32:
decimalNum := decimal.NewFromFloat32(tmpVal.(float32))
val = decimalNum.String()
}
signData[key] = val
}
return signData
}
// checkSignData 请求参数签名校验
func checkSignData(postData map[string]string, ip string) (err error) {
isSandbox := postData["is_sandbox"]
//如果是测试环境,且是沙箱环境的话,那么绕过测试
if utils.RunMode == "debug" && isSandbox != "" {
return
}
appid := postData["appid"]
if appid == "" {
err = errors.New("参数异常,缺少appid")
return
}
openApiUserInfo, tmpErr := models.GetByAppid(appid)
if tmpErr != nil {
if tmpErr.Error() == utils.ErrNoRow() {
err = errors.New("appid异常,请联系管理员")
} else {
err = errors.New("系统异常,请联系管理员")
}
return
}
if openApiUserInfo == nil {
err = errors.New("系统异常,请联系管理员")
return
}
//如果有ip限制,那么就添加ip
if openApiUserInfo.Ip != "" {
if !strings.Contains(openApiUserInfo.Ip, ip) {
err = errors.New(fmt.Sprintf("无权限访问该接口,ip:%v,请联系管理员", ip))
return
}
}
//接口提交的签名字符串
ownSign := postData["sign"]
if ownSign == "" {
err = errors.New("参数异常,缺少签名字符串")
return
}
if postData["nonce_str"] == "" {
err = errors.New("参数异常,缺少随机字符串")
return
}
if postData["timestamp"] == "" {
err = errors.New("参数异常,缺少时间戳")
return
} else {
timeUnix := time.Now().Unix() //当前格林威治时间,int64类型
//将接口传入的时间做转换
timestamp, timeErr := strconv.ParseInt(postData["timestamp"], 10, 64)
if timeErr != nil {
err = errors.New("参数异常,时间戳格式异常")
return
}
if math.Abs(float64(timeUnix-timestamp)) > 300 {
err = errors.New("当前时间异常,请调整设备时间与北京时间一致")
return
}
}
//先取出除sign外的所有的提交的参数key
var keys []string
for k := range postData {
if k != "sign" {
keys = append(keys, k)
}
}
//1,根据参数名称的ASCII码表的顺序排序
sort.Strings(keys)
//2 根据排序后的参数名称,取出对应的值,并拼接字符串
var signStr string
for _, v := range keys {
signStr += v + "=" + postData[v] + "&"
}
//3,全转小写(md5(拼装的字符串后+分配给你的app_secret))
//sign := strings.ToLower(fmt.Sprintf("%x", md5.Sum([]byte(strings.Trim(signStr, "&")+key))))
//md5.Sum([]byte(signStr+"key="+key)) 这是md5加密出来后的每个字符的ascall码,需要再转换成对应的字符
//3,全转大写(md5(拼装的字符串后+分配给你的app_secret))
sign := strings.ToUpper(fmt.Sprintf("%x", md5.Sum([]byte(signStr+"secret="+openApiUserInfo.Secret))))
if sign != ownSign {
utils.FileLog.Info(fmt.Sprintf("签名校验异常,签名字符串:%v;服务端签名值:%v", signStr, sign))
return errors.New("签名校验异常,请核实签名")
}
return nil
}
func (c *BaseAuthController) logUri(content []byte, requestBody, ip string) {
utils.ApiLog.Info("uri:%s, requestBody:%s, responseBody:%s, ip:%s", c.Ctx.Input.URI(), requestBody, content, ip)
return
}