|
| 1 | +// Copyright 2019 The OpenSDS Authors. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package validation |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "fmt" |
| 20 | + "net/http" |
| 21 | + "strings" |
| 22 | + |
| 23 | + "github.com/astaxie/beego" |
| 24 | + bctx "github.com/astaxie/beego/context" |
| 25 | + "github.com/getkin/kin-openapi/openapi3" |
| 26 | + "github.com/getkin/kin-openapi/openapi3filter" |
| 27 | + "github.com/golang/glog" |
| 28 | + myctx "github.com/opensds/opensds/pkg/context" |
| 29 | +) |
| 30 | + |
| 31 | +// Factory returns a fiter function of api request |
| 32 | +func Factory(filename string) beego.FilterFunc { |
| 33 | + swagger, err := openapi3.NewSwaggerLoader().LoadSwaggerFromFile(filename) |
| 34 | + if err != nil { |
| 35 | + glog.Warningf("error loading %s api swagger file: %s", filename, err) |
| 36 | + return func(httpCtx *bctx.Context) {} |
| 37 | + } |
| 38 | + |
| 39 | + // Server is not required for finding route |
| 40 | + swagger.Servers = nil |
| 41 | + router := openapi3filter.NewRouter().WithSwagger(swagger) |
| 42 | + return func(httpCtx *bctx.Context) { |
| 43 | + req := httpCtx.Request |
| 44 | + route, pathParams, err := router.FindRoute(req.Method, req.URL) |
| 45 | + if err != nil { |
| 46 | + glog.Errorf("failed to find route from swagger: %s", err) |
| 47 | + myctx.HttpError(httpCtx, http.StatusBadRequest, "failed to find route %s:%s from swagger: %s", req.Method, req.URL, err) |
| 48 | + } |
| 49 | + |
| 50 | + requestValidationInput := &openapi3filter.RequestValidationInput{ |
| 51 | + Request: req, |
| 52 | + PathParams: pathParams, |
| 53 | + Route: route, |
| 54 | + } |
| 55 | + if err := openapi3filter.ValidateRequest(context.Background(), requestValidationInput); err != nil { |
| 56 | + errMsg := "" |
| 57 | + switch e := err.(type) { |
| 58 | + case *openapi3filter.RequestError: |
| 59 | + // Retrieve first line of err message |
| 60 | + errMsg = strings.Split(e.Error(), "\n")[0] |
| 61 | + default: |
| 62 | + errMsg = fmt.Sprintf("%s", err) |
| 63 | + } |
| 64 | + glog.Errorf("invalid request: %s", errMsg) |
| 65 | + myctx.HttpError(httpCtx, http.StatusBadRequest, "%s", errMsg) |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments