loginstatuscheck_middleware.go 1.4 KB
package middleware

import (
	"github.com/zeromicro/go-zero/rest/httpx"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/gateway"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/gateway/authlib"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/result"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/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)
}