loginstatuscheck_middleware.go
1.2 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
package middleware
import (
"github.com/zeromicro/go-zero/rest/httpx"
"gitlab.fjmaimaimai.com/allied-creation/sumifcc/pkg/gateway"
"gitlab.fjmaimaimai.com/allied-creation/sumifcc/pkg/gateway/authlib"
"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
}
httpx.ErrorCtx(r.Context(), w, 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)
}