loginstatuscheck_middleware.go
1.4 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
package middleware
import (
"github.com/zeromicro/go-zero/rest/httpx"
"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/interanl/pkg/gateway"
"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/interanl/pkg/gateway/authlib"
"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/pkg/result"
"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/pkg/xerr"
"net/http"
)
type LoginStatusCheckMiddleware struct {
apiAuth authlib.ApiAuthService
}
func NewLoginStatusCheckMiddleware(apiAuth authlib.ApiAuthService) *LoginStatusCheckMiddleware {
return &LoginStatusCheckMiddleware{
apiAuth: apiAuth,
}
}
func (m *LoginStatusCheckMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("x-mmm-accesstoken")
if len(token) > 0 {
_, err := m.apiAuth.LoginCheck(r.Context(), authlib.RequestLoginCheck{
Token: token,
})
if err != nil {
gatewayError, ok := err.(gateway.HttpError)
if ok {
unAuthResponse(w, gatewayError.Base.Code, gatewayError.Base.Msg)
return
}
result.HttpResult(r, w, struct{}{}, xerr.NewErr(err))
return
}
}
next(w, r)
}
}
func unAuthResponse(w http.ResponseWriter, code int, msg string) {
data := map[string]interface{}{
"msg": msg,
"code": code,
"data": struct{}{},
}
httpx.WriteJson(w, http.StatusUnauthorized, data)
}