package middleware import ( "baize_scaffold/gateway/gw/config" "net/http" "git.sxidc.com/go-framework/baize/framework/core/api/response" "git.sxidc.com/go-framework/baize/framework/gateway" "git.sxidc.com/service-supports/fslog" "github.com/dgrijalva/jwt-go/request" "github.com/pkg/errors" ) type AuthenticationResult struct { response.MsgResponse TenantID string `json:"tenantId"` TenantName string `json:"tenantName"` UserID string `json:"userId"` UserName string `json:"userName"` Roles []Role `json:"roles"` } type Role struct { ID string `json:"id"` Name string `json:"name"` } type TenantInfo struct { ID string Name string } func (t TenantInfo) GetID() string { return t.ID } func (t TenantInfo) GetName() string { return t.Name } type UserInfo struct { ID string UserName string Roles []Role } func (u UserInfo) GetID() string { return u.ID } func (u UserInfo) GetUserName() string { return u.UserName } func (u UserInfo) GetName() string { return u.UserName } func Authentication() gateway.Handler { return func(requestBuilder *gateway.RequestBuilder) { c := requestBuilder.ApiContext() respFunc := response.SendMapResponse token, err := request.AuthorizationHeaderExtractor.ExtractToken(c.Request) if err != nil { fslog.Error(err) respFunc(c, http.StatusUnauthorized, map[string]any{ "accessToken": "", }, err) c.Abort() return } var requestErr error authResult := new(AuthenticationResult) requestBuilder.Post(&gateway.PostRequest{ Url: config.GetGatewayConfig().ServicesConfig.UMBaseUrl + "/utm/api/v1/auth", Body: map[string]any{ "token": token, "resource": c.FullPath(), "action": c.Request.Method, }, }).ResponseErrorCallback(func(c *gateway.RequestBuilderContext, err error) { requestErr = err }).ResponseSuccessCallback(func(c *gateway.RequestBuilderContext) { err := c.HistoryRequests()[0].Response().Json(authResult) if err != nil { requestErr = err return } if !authResult.Success { requestErr = errors.New(authResult.Msg) return } return }).Request() if requestErr != nil { fslog.Error(err) respFunc(requestBuilder.ApiContext(), http.StatusUnauthorized, map[string]any{ "accessToken": "", }, requestErr) requestBuilder.ApiContext().Abort() return } c.SetUserInfo(&UserInfo{ ID: authResult.UserID, UserName: authResult.UserName, Roles: authResult.Roles, }) c.SetTenantInfo(&TenantInfo{ ID: authResult.TenantID, Name: authResult.TenantName, }) c.Next() } }