package middleware import ( "baize_scaffold/gateway/gw/config" "fmt" "net/http" "github.com/pkg/errors" "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" ) 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": "", }, errors.New("token错误")) c.Abort() return } requestBuilder.Post(&gateway.PostRequest{ Url: config.GetGatewayConfig().ServicesConfig.UMBaseUrl + "/utm/api/v1/checkToken", Body: map[string]any{ "token": token, "resource": c.FullPath(), "action": c.Request.Method, }, }).ResponseSuccessCallback(func(c *gateway.RequestBuilderContext) { userID, ok := c.GetResultMapValue("userId").(string) if !ok { fslog.Error(err) respFunc(c.ApiContext(), http.StatusUnauthorized, map[string]any{ "accessToken": "", }, errors.New("用户ID获取错误")) c.ApiContext().Abort() } }).Request() c.SetUserInfo(&UserInfoWithRoles{ ID: umCheckResult.UserID, UserName: umCheckResult.UserName, Updated: umCheckResult.Updated, ProfileName: tangentSimpleUserInfo.Name, OrgInfo: currentTenant, RoleInfos: roles, TangentUserProfile: tangentSimpleUserInfo, }) c.SetTenantInfo(currentTenant) c.Next() } }