base.go
8.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package controllers
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/astaxie/beego/plugins/cors"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/time"
"strconv"
"strings"
"opp/protocol"
"opp/services/auth"
"github.com/astaxie/beego/context"
"github.com/astaxie/beego/validation"
"github.com/prometheus/client_golang/prometheus"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/common"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
)
var (
//prometheus 监控endpoint
HTTPReqTotal *prometheus.CounterVec
)
type BaseController struct {
Header *protocol.RequestHeader
mybeego.BaseController
}
func init() {
// HistogramVec 是一组Histogram
HTTPReqTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "request_count_vec", //http_requests_total
Help: "total number of http requests made.",
}, []string{"method", "path"})
// 这里的"method"、"path"、"status" 都是label , "status"
prometheus.MustRegister(
HTTPReqTotal,
)
//if err:=prometheus.Register(HTTPReqTotal);err!=nil{
// log.Error(err)
//}
}
var DefaultController *BaseController = &BaseController{}
//Valid valid struct
func (this *BaseController) Valid(obj interface{}) (result bool, msg *protocol.ResponseMessage) {
/*校验*/
var err error
valid := validation.Validation{}
result, err = valid.Valid(obj)
if err != nil {
msg = protocol.BadRequestParam(1)
return
}
if !result {
for _, err := range valid.Errors {
if strings.HasSuffix(err.Key, ".Mobile") {
msg = protocol.BadRequestParam(2001)
return
}
log.Error(err.Key, err.Message)
}
msg = protocol.BadRequestParam(2)
return
}
return
}
func (this *BaseController) Resp(msg *protocol.ResponseMessage) {
this.Data["json"] = msg
this.ServeJSON()
}
//获取请求头信息
func GetRequestHeader(ctx *context.Context) *protocol.RequestHeader {
h := &protocol.RequestHeader{}
h.AccessToken = ctx.Input.Header("x-mmm-accesstoken")
h.AppProject = ctx.Input.Header("x-mmm-appproject")
h.DeviceType, _ = strconv.Atoi(ctx.Input.Header("x-mmm-devicetype"))
h.Sign = ctx.Input.Header("x-mmm-sign")
h.Uuid = ctx.Input.Header("x-mmm-uuid")
h.TimeStamp = ctx.Input.Header("x-mmm-timestamp")
h.Uid, _ = strconv.ParseInt(ctx.Input.Header("uid"), 10, 64) //需要uid写入到header里面
if h.Uid == 0 {
h.Uid, _ = strconv.ParseInt(ctx.Input.Header("x-mmm-uid"), 10, 64)
}
h.CompanyId, _ = strconv.ParseInt(ctx.Input.Header("x-mmm-cid"), 10, 64)
h.UserId, _ = strconv.ParseInt(ctx.Input.Header("x-mmm-id"), 10, 64)
return h
}
//过滤器
func FilterComm(ctx *context.Context) {
//if strings.HasSuffix(ctx.Request.RequestURI,"login"){
// return
//}
//统计
MetricCounter(ctx)
//if beego.BConfig.RunMode == "dev" && (ctx.Input.Header("x-mmm-uid") != "" || ctx.Input.Header("uid") != "") {
// return
//}
//TODO:注入账号,后期移除掉
//if ctx.Input.Header("x-mmm-accesstoken") == "" {
// ctx.Request.Header.Set("x-mmm-accesstoken", "6839602f1d8211eabd85000c29ad8d6d")
// if ctx.Input.Header("x-mmm-accesstoken") == "" {
// ctx.Request.Header.Add("x-mmm-accesstoken", "6839602f1d8211eabd85000c29ad8d6d")
// }
//} else {
// //1.检查签名
// if !CheckSign(ctx) {
// return
// }
//}
//if !CheckToken(ctx) {
// return
//}
//if !CheckSign(ctx) {
// return
//}
//2.检查token是否有效
if !CheckToken(ctx) {
return
}
//3.查重uuid
//if !CheckUuid(ctx) {
// return
//}
return
}
func MetricCounter(ctx *context.Context) {
// 请求数加1
HTTPReqTotal.With(prometheus.Labels{
"method": ctx.Request.Method,
"path": ctx.Request.RequestURI,
//"status": strconv.Itoa(c.Writer.Status()),
}).Inc()
}
//检查签名
func CheckSign(ctx *context.Context) (result bool) {
var (
h *protocol.RequestHeader
sign string
signHex string
)
result = true
h = GetRequestHeader(ctx)
//1.检查签名
sign = fmt.Sprintf("v!(MmM%v%v%vMmM)i^", h.TimeStamp, h.Uuid, h.AccessToken)
sha256 := sha256.New()
sha256.Write([]byte(sign))
signHex = hex.EncodeToString(sha256.Sum(nil))
if strings.Compare(signHex, h.Sign) != 0 {
msg := protocol.BadRequestParam(113)
log.Error(fmt.Sprintf("%v req:%v resp:%v %v", ctx.Request.RequestURI, common.AssertJson(h), common.AssertJson(msg), signHex))
ctx.Output.JSON(msg, false, false)
result = false
return
}
return
}
//检查access_token
func CheckToken(ctx *context.Context) (result bool) {
var (
msg *protocol.ResponseMessage
)
token := ctx.Input.Header("x-mmm-accesstoken")
if strings.HasSuffix(ctx.Request.RequestURI, "loginModule") ||
strings.HasSuffix(ctx.Request.RequestURI, "accessToken") ||
strings.HasSuffix(ctx.Request.RequestURI, "refreshToken") ||
strings.HasSuffix(ctx.Request.RequestURI, "smsCode") {
return true
}
result = true
defer func() {
if msg != nil {
result = false
ctx.Output.JSON(msg, false, false)
}
}()
if rsp, err := auth.CheckToken(&protocol.CheckTokenRequest{Token: token}); err != nil || rsp.UserInfo == nil {
msg = protocol.NewReturnResponse(rsp, err)
log.Error(fmt.Sprintf("%v req:%v resp:%v", ctx.Request.RequestURI, token, common.AssertJson(msg)))
return
} else {
if rsp.UserInfo != nil {
//设置附加数据
ctx.Request.Header.Set("x-mmm-uid", fmt.Sprintf("%v", rsp.UserInfo.UserId))
ctx.Request.Header.Set("x-mmm-cid", fmt.Sprintf("%v", rsp.UserInfo.CurrentCompanyId))
ctx.Request.Header.Set("x-mmm-id", fmt.Sprintf("%v", rsp.UserInfo.CurrentUserCompanyId))
}
}
return
}
//检查Uuid
func CheckUuid(ctx *context.Context) (result bool) {
var (
msg *protocol.ResponseMessage
)
result = true
defer func() {
if msg != nil {
result = false
ctx.Output.JSON(msg, false, false)
}
}()
uuid := ctx.Input.Header("x-mmm-uuid")
msg = protocol.NewReturnResponse(auth.CheckUuid(&protocol.CheckUuidRequest{Uuid: uuid}))
if msg != nil {
log.Error(fmt.Sprintf("%v req:%v resp:%v", ctx.Request.RequestURI, uuid, common.AssertJson(msg)))
}
return
}
//AllowOption 允许跨域请求
var AllowOption = func(ctx *context.Context) {
if ctx.Request.Method != "OPTIONS" {
return
}
f := cors.Allow(&cors.Options{
AllowMethods: []string{"POST", "GET", "OPTIONS", "PUT", "DELETE"}, //允许的请求类型
AllowHeaders: []string{"Origin", "Accept", "Content-Type", "Authorization",
"x-mmm-cid", "x-mmm-uid", "x-mmm-accesstoken", "x-mmm-refreshtoken", "x-requested-with"}, //允许的头部信息
ExposeHeaders: []string{"Content-Length"}, //允许暴露的头信息
AllowCredentials: false, //不允许共享AuthTuffic证书
AllowAllOrigins: true, //允许的请求来源
})
f(ctx)
ctx.Output.Body([]byte("{}"))
ctx.Output.SetStatus(204)
return
}
//LogRequestData Before Router
var LogRequestData = func(ctx *context.Context) {
log.Info("====>Recv Request:%s", ctx.Input.URI())
hmap := map[string]string{
//protocol.HeaderAccessToken: ctx.Input.Header(protocol.HeaderAccessToken),
//protocol.HeaderRefreshToken: ctx.Input.Header(protocol.HeaderRefreshToken),
}
if ctx.Input.RequestBody != nil {
log.Info("====>Recv data from client:\nHeadData: %v \nBodyData: %s", hmap, string(ctx.Input.RequestBody))
} else {
log.Info("====>Recv data from client:\nHeadData: %v ", hmap)
}
}
func (this *BaseController) Prepare() {
this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "*")
if this.Ctx.Input.Method() == "OPTIONS" {
this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
return
}
this.Query = map[string]string{}
input := this.Input()
for k := range input {
this.Query[k] = input.Get(k)
}
if this.Ctx.Input.RequestBody != nil {
this.ByteBody = this.Ctx.Input.RequestBody[:]
if len(this.ByteBody) < 1 {
this.ByteBody = []byte("{}")
}
this.RequestHead = this.GetRequestHead()
this.Header = GetRequestHeader(this.Ctx)
this.Header.SetRequestId(fmt.Sprintf("%v.%v.%s", this.Header.Uid, time.GetTimeByYyyymmddhhmmss(), this.Ctx.Request.URL))
log.Debug(fmt.Sprintf("====>Recv data from uid(%d) ucid(%v) client:\nHeadData: %s\nRequestId:%s BodyData: %s", this.Header.Uid, this.Header.UserId, common.AssertJson(this.Header), this.Header.GetRequestId(), string(this.ByteBody)))
}
}
func (this *BaseController) Finish() {
if this.Ctx.Input.Method() == "OPTIONS" {
return
}
strByte, _ := json.Marshal(this.Data["json"])
length := len(strByte)
if length > 5000 {
log.Debug(fmt.Sprintf("<====Send to uid(%d) ucid(%v) client: %d byte\nRequestId:%s RspBodyData: %s......", this.Header.Uid, this.Header.UserId, length, this.Header.GetRequestId(), string(strByte[:5000])))
} else {
log.Debug(fmt.Sprintf("<====Send to uid(%d) ucid(%v) client: %d byte\nRequestId:%s RspBodyData: %s", this.Header.Uid, this.Header.UserId, length, this.Header.GetRequestId(), string(strByte)))
}
}