github.com/rzurga/go-swagger@v0.28.1-0.20211109195225-5d1f453ffa3a/generator/templates/contrib/stratoscale/server/configureapi.gotmpl (about)

     1  // Code generated by go-swagger; DO NOT EDIT.
     2  
     3  
     4  {{ if .Copyright -}}// {{ comment .Copyright -}}{{ end }}
     5  
     6  
     7  package {{ .APIPackage }}
     8  
     9  import (
    10  	"context"
    11  	"crypto/tls"
    12  	"net/http"
    13  	"log"
    14  	"fmt"
    15  
    16  	"github.com/go-openapi/errors"
    17  	"github.com/go-openapi/loads"
    18  	"github.com/go-openapi/runtime"
    19  	"github.com/go-openapi/runtime/middleware"
    20  	"github.com/go-openapi/runtime/security"
    21  
    22    {{ imports .DefaultImports }}
    23    {{ imports .Imports }}
    24  )
    25  {{ $package := .Package }}
    26  
    27  type contextKey string
    28  
    29  const AuthKey contextKey = "Auth"
    30  
    31  {{ range .OperationGroups -}}
    32  //go:generate mockery -name {{ pascalize .Name}}API -inpkg
    33  
    34  /* {{ pascalize .Name }}API {{ .Description }} */
    35  type {{ pascalize .Name }}API interface {
    36  {{ range .Operations -}}
    37  	{{ if .Summary -}}
    38  	/* {{ pascalize .Name }} {{ .Summary }} */
    39  	{{ else if .Description -}}
    40  	/* {{ pascalize .Name }} {{ .Description }} */
    41  	{{ end -}}
    42  	{{ pascalize .Name }}(ctx context.Context, params {{.Package}}.{{ pascalize .Name }}Params) middleware.Responder
    43  
    44  {{ end -}}
    45  }
    46  {{ end }}
    47  
    48  // Config is configuration for Handler
    49  type Config struct {
    50  	{{ range .OperationGroups -}}
    51  	{{ pascalize .Name }}API
    52  	{{ end -}}
    53  	Logger func(string, ...interface{})
    54  	// InnerMiddleware is for the handler executors. These do not apply to the swagger.json document.
    55  	// The middleware executes after routing but before authentication, binding and validation
    56  	InnerMiddleware func(http.Handler) http.Handler
    57  
    58  	// Authorizer is used to authorize a request after the Auth function was called using the "Auth*" functions
    59  	// and the principal was stored in the context in the "AuthKey" context value.
    60  	Authorizer func(*http.Request) error
    61  
    62  	{{ range .SecurityDefinitions -}}
    63  	{{ if .IsBasicAuth -}}
    64  	// Auth{{ pascalize .ID }} for basic authentication
    65    Auth{{ pascalize .ID }} func(user string, pass string) ({{ if .PrincipalIsNullable }}*{{ end }}{{ .Principal }}, error)
    66  	{{ end -}}
    67  	{{ if .IsAPIKeyAuth -}}
    68  	// Auth{{ pascalize .ID }} Applies when the "{{ .Name }}" {{ .Source }} is set
    69    Auth{{ pascalize .ID }} func(token string) ({{ if .PrincipalIsNullable }}*{{ end }}{{ .Principal }}, error)
    70  	{{ end }}
    71  	{{ if .IsOAuth2 -}}
    72  	// Auth{{ pascalize .ID }} For OAuth2 authentication
    73    Auth{{ pascalize .ID }} func(token string, scopes []string) ({{ if .PrincipalIsNullable }}*{{ end }}{{ .Principal }}, error)
    74  	{{ end -}}
    75  	{{ end -}}
    76  
    77  	// Authenticator to use for all APIKey authentication
    78  	APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator
    79  	// Authenticator to use for all Bearer authentication
    80  	BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator
    81  	// Authenticator to use for all Basic authentication
    82  	BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator
    83  }
    84  
    85  // Handler returns an http.Handler given the handler configuration
    86  // It mounts all the business logic implementers in the right routing.
    87  func Handler(c Config) (http.Handler, error) {
    88  	h, _, err := HandlerAPI(c)
    89  	return h, err
    90  }
    91  
    92  // HandlerAPI returns an http.Handler given the handler configuration
    93  // and the corresponding *{{ pascalize .Name }} instance.
    94  // It mounts all the business logic implementers in the right routing.
    95  func HandlerAPI(c Config) (http.Handler, *{{.Package}}.{{ pascalize .Name }}API, error) {
    96  	spec, err := loads.Analyzed(swaggerCopy(SwaggerJSON), "")
    97  	if err != nil {
    98  		return nil, nil, fmt.Errorf("analyze swagger: %v", err)
    99  	}
   100  	api := {{.Package}}.New{{ pascalize .Name }}API(spec)
   101  	api.ServeError = errors.ServeError
   102  	api.Logger = c.Logger
   103  
   104  	if c.APIKeyAuthenticator != nil {
   105  		api.APIKeyAuthenticator = c.APIKeyAuthenticator
   106  	}
   107  	if c.BasicAuthenticator  != nil {
   108  		api.BasicAuthenticator  = c.BasicAuthenticator
   109  	}
   110  	if c.BearerAuthenticator  != nil {
   111  		api.BearerAuthenticator  = c.BearerAuthenticator
   112  	}
   113  
   114  	{{ range .Consumes -}}
   115  	{{ if .Implementation -}}
   116  	api.{{ pascalize .Name }}Consumer = {{ .Implementation }}
   117  	{{ else }}
   118  	api.{{ pascalize .Name }}Consumer = runtime.ConsumerFunc(func(r io.Reader, target interface{}) error {
   119  		return errors.NotImplemented("{{.Name}} consumer has not yet been implemented")
   120  	})
   121  	{{ end -}}
   122  	{{ end -}}
   123  	{{ range .Produces -}}
   124  	{{ if .Implementation -}}
   125  	api.{{ pascalize .Name }}Producer = {{ .Implementation }}
   126  	{{ else -}}
   127  	api.{{ pascalize .Name }}Producer = runtime.ProducerFunc(func(w io.Writer, data interface{}) error {
   128  		return errors.NotImplemented("{{.Name}} producer has not yet been implemented")
   129  	})
   130  	{{ end -}}
   131  	{{ end -}}
   132  
   133  	{{ range .SecurityDefinitions -}}
   134  	{{ if .IsBasicAuth -}}
   135  	api.{{ pascalize .ID }}Auth = func(user string, pass string) ({{if .PrincipalIsNullable }}*{{ end }}{{.Principal}}, error) {
   136      if c.Auth{{ pascalize .ID }} == nil {
   137       {{- if eq .Principal "interface{}" }}
   138          return "", nil
   139       {{- else }}
   140          panic("you specified a custom principal type, but did not provide the authenticator to provide this")
   141       {{- end }}
   142      }
   143  		return c.Auth{{ pascalize .ID }}(user, pass)
   144  	}
   145  	{{ end -}}
   146  	{{ if .IsAPIKeyAuth -}}
   147  	api.{{ pascalize .ID }}Auth = func(token string) ({{ if .PrincipalIsNullable }}*{{ end }}{{.Principal}}, error) {
   148  	  if c.Auth{{ pascalize .ID }} == nil {
   149       {{- if eq .Principal "interface{}" }}
   150  	      return token, nil
   151       {{- else }}
   152          panic("you specified a custom principal type, but did not provide the authenticator to provide this")
   153       {{- end }}
   154  	  }
   155  		return c.Auth{{ pascalize .ID }}(token)
   156  	}
   157  	{{ end }}
   158  	{{ if .IsOAuth2 -}}
   159  	api.{{ pascalize .ID }}Auth = func(token string, scopes []string) ({{ if .PrincipalIsNullable }}*{{ end }}{{.Principal}}, error) {
   160      if c.Auth{{ pascalize .ID }} == nil {
   161       {{- if eq .Principal "interface{}" }}
   162          return token, nil
   163       {{- else }}
   164          panic("you specified a custom principal type, but did not provide the authenticator to provide this")
   165       {{- end }}
   166      }
   167  		return c.Auth{{ pascalize .ID }}(token, scopes)
   168  	}
   169  	{{ end -}}
   170  	{{ end -}}
   171  
   172  	{{ if .SecurityDefinitions -}}
   173  	api.APIAuthorizer = authorizer(c.Authorizer)
   174  	{{ end -}}
   175  
   176  	{{ range .Operations -}}
   177  	api.{{if ne .Package $package}}{{pascalize .Package}}{{end}}{{ pascalize .Name }}Handler =
   178    {{- .PackageAlias }}.{{ pascalize .Name }}HandlerFunc(func(params {{.PackageAlias}}.{{ pascalize .Name }}Params{{if .Authorized}}, principal {{ if .PrincipalIsNullable }}*{{ end }}{{ .Principal }}{{end}}) middleware.Responder {
   179  		ctx := params.HTTPRequest.Context()
   180  		{{ if .Authorized -}}
   181  		ctx = storeAuth(ctx, principal)
   182  		{{ end -}}
   183  		return c.{{pascalize .Package}}API.{{pascalize .Name}}(ctx, params)
   184  	})
   185  	{{ end -}}
   186  
   187  	api.ServerShutdown = func() {  }
   188  	return api.Serve(c.InnerMiddleware), api, nil
   189  }
   190  
   191  // swaggerCopy copies the swagger json to prevent data races in runtime
   192  func swaggerCopy(orig json.RawMessage) json.RawMessage {
   193  	c := make(json.RawMessage, len(orig))
   194  	copy(c, orig)
   195  	return c
   196  }
   197  
   198  // authorizer is a helper function to implement the runtime.Authorizer interface.
   199  type authorizer func(*http.Request) error
   200  
   201  func (a authorizer) Authorize(req *http.Request, principal interface{}) error {
   202  	if a == nil {
   203  		return nil
   204  	}
   205  	ctx := storeAuth(req.Context(), principal)
   206  	return a(req.WithContext(ctx))
   207  }
   208  
   209  func storeAuth(ctx context.Context, principal interface{}) context.Context {
   210  	return context.WithValue(ctx, AuthKey, principal)
   211  }