loginstatuscheck_middleware.go 1.2 KB
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)
}