github.com/circl-dev/go-swagger@v0.31.0/examples/authentication/restapi/operations/auth_sample_api.go (about)

     1  // Code generated by go-swagger; DO NOT EDIT.
     2  
     3  package operations
     4  
     5  // This file was generated by the swagger tool.
     6  // Editing this file might prove futile when you re-run the swagger generate command
     7  
     8  import (
     9  	"fmt"
    10  	"net/http"
    11  	"strings"
    12  
    13  	"github.com/go-openapi/errors"
    14  	"github.com/go-openapi/strfmt"
    15  	"github.com/go-openapi/swag"
    16  	"github.com/circl-dev/runtime"
    17  	"github.com/circl-dev/runtime/middleware"
    18  	"github.com/circl-dev/runtime/security"
    19  	"github.com/circl-dev/spec"
    20  	"github.com/circl-dev/loads"
    21  
    22  	"github.com/circl-dev/go-swagger/examples/authentication/models"
    23  	"github.com/circl-dev/go-swagger/examples/authentication/restapi/operations/customers"
    24  )
    25  
    26  // NewAuthSampleAPI creates a new AuthSample instance
    27  func NewAuthSampleAPI(spec *loads.Document) *AuthSampleAPI {
    28  	return &AuthSampleAPI{
    29  		handlers:            make(map[string]map[string]http.Handler),
    30  		formats:             strfmt.Default,
    31  		defaultConsumes:     "application/json",
    32  		defaultProduces:     "application/json",
    33  		customConsumers:     make(map[string]runtime.Consumer),
    34  		customProducers:     make(map[string]runtime.Producer),
    35  		PreServerShutdown:   func() {},
    36  		ServerShutdown:      func() {},
    37  		spec:                spec,
    38  		useSwaggerUI:        false,
    39  		ServeError:          errors.ServeError,
    40  		BasicAuthenticator:  security.BasicAuth,
    41  		APIKeyAuthenticator: security.APIKeyAuth,
    42  		BearerAuthenticator: security.BearerAuth,
    43  
    44  		JSONConsumer: runtime.JSONConsumer(),
    45  
    46  		JSONProducer: runtime.JSONProducer(),
    47  
    48  		CustomersCreateHandler: customers.CreateHandlerFunc(func(params customers.CreateParams, principal *models.Principal) middleware.Responder {
    49  			return middleware.NotImplemented("operation customers.Create has not yet been implemented")
    50  		}),
    51  		CustomersGetIDHandler: customers.GetIDHandlerFunc(func(params customers.GetIDParams, principal *models.Principal) middleware.Responder {
    52  			return middleware.NotImplemented("operation customers.GetID has not yet been implemented")
    53  		}),
    54  
    55  		// Applies when the "x-token" header is set
    56  		KeyAuth: func(token string) (*models.Principal, error) {
    57  			return nil, errors.NotImplemented("api key auth (key) x-token from header param [x-token] has not yet been implemented")
    58  		},
    59  		// default authorizer is authorized meaning no requests are blocked
    60  		APIAuthorizer: security.Authorized(),
    61  	}
    62  }
    63  
    64  /*AuthSampleAPI the auth sample API */
    65  type AuthSampleAPI struct {
    66  	spec            *loads.Document
    67  	context         *middleware.Context
    68  	handlers        map[string]map[string]http.Handler
    69  	formats         strfmt.Registry
    70  	customConsumers map[string]runtime.Consumer
    71  	customProducers map[string]runtime.Producer
    72  	defaultConsumes string
    73  	defaultProduces string
    74  	Middleware      func(middleware.Builder) http.Handler
    75  	useSwaggerUI    bool
    76  
    77  	// BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function.
    78  	// It has a default implementation in the security package, however you can replace it for your particular usage.
    79  	BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator
    80  
    81  	// APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function.
    82  	// It has a default implementation in the security package, however you can replace it for your particular usage.
    83  	APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator
    84  
    85  	// BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function.
    86  	// It has a default implementation in the security package, however you can replace it for your particular usage.
    87  	BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator
    88  
    89  	// JSONConsumer registers a consumer for the following mime types:
    90  	//   - application/keyauth.api.v1+json
    91  	JSONConsumer runtime.Consumer
    92  
    93  	// JSONProducer registers a producer for the following mime types:
    94  	//   - application/keyauth.api.v1+json
    95  	JSONProducer runtime.Producer
    96  
    97  	// KeyAuth registers a function that takes a token and returns a principal
    98  	// it performs authentication based on an api key x-token provided in the header
    99  	KeyAuth func(string) (*models.Principal, error)
   100  
   101  	// APIAuthorizer provides access control (ACL/RBAC/ABAC) by providing access to the request and authenticated principal
   102  	APIAuthorizer runtime.Authorizer
   103  
   104  	// CustomersCreateHandler sets the operation handler for the create operation
   105  	CustomersCreateHandler customers.CreateHandler
   106  	// CustomersGetIDHandler sets the operation handler for the get Id operation
   107  	CustomersGetIDHandler customers.GetIDHandler
   108  
   109  	// ServeError is called when an error is received, there is a default handler
   110  	// but you can set your own with this
   111  	ServeError func(http.ResponseWriter, *http.Request, error)
   112  
   113  	// PreServerShutdown is called before the HTTP(S) server is shutdown
   114  	// This allows for custom functions to get executed before the HTTP(S) server stops accepting traffic
   115  	PreServerShutdown func()
   116  
   117  	// ServerShutdown is called when the HTTP(S) server is shut down and done
   118  	// handling all active connections and does not accept connections any more
   119  	ServerShutdown func()
   120  
   121  	// Custom command line argument groups with their descriptions
   122  	CommandLineOptionsGroups []swag.CommandLineOptionsGroup
   123  
   124  	// User defined logger function.
   125  	Logger func(string, ...interface{})
   126  }
   127  
   128  // UseRedoc for documentation at /docs
   129  func (o *AuthSampleAPI) UseRedoc() {
   130  	o.useSwaggerUI = false
   131  }
   132  
   133  // UseSwaggerUI for documentation at /docs
   134  func (o *AuthSampleAPI) UseSwaggerUI() {
   135  	o.useSwaggerUI = true
   136  }
   137  
   138  // SetDefaultProduces sets the default produces media type
   139  func (o *AuthSampleAPI) SetDefaultProduces(mediaType string) {
   140  	o.defaultProduces = mediaType
   141  }
   142  
   143  // SetDefaultConsumes returns the default consumes media type
   144  func (o *AuthSampleAPI) SetDefaultConsumes(mediaType string) {
   145  	o.defaultConsumes = mediaType
   146  }
   147  
   148  // SetSpec sets a spec that will be served for the clients.
   149  func (o *AuthSampleAPI) SetSpec(spec *loads.Document) {
   150  	o.spec = spec
   151  }
   152  
   153  // DefaultProduces returns the default produces media type
   154  func (o *AuthSampleAPI) DefaultProduces() string {
   155  	return o.defaultProduces
   156  }
   157  
   158  // DefaultConsumes returns the default consumes media type
   159  func (o *AuthSampleAPI) DefaultConsumes() string {
   160  	return o.defaultConsumes
   161  }
   162  
   163  // Formats returns the registered string formats
   164  func (o *AuthSampleAPI) Formats() strfmt.Registry {
   165  	return o.formats
   166  }
   167  
   168  // RegisterFormat registers a custom format validator
   169  func (o *AuthSampleAPI) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) {
   170  	o.formats.Add(name, format, validator)
   171  }
   172  
   173  // Validate validates the registrations in the AuthSampleAPI
   174  func (o *AuthSampleAPI) Validate() error {
   175  	var unregistered []string
   176  
   177  	if o.JSONConsumer == nil {
   178  		unregistered = append(unregistered, "JSONConsumer")
   179  	}
   180  
   181  	if o.JSONProducer == nil {
   182  		unregistered = append(unregistered, "JSONProducer")
   183  	}
   184  
   185  	if o.KeyAuth == nil {
   186  		unregistered = append(unregistered, "XTokenAuth")
   187  	}
   188  
   189  	if o.CustomersCreateHandler == nil {
   190  		unregistered = append(unregistered, "customers.CreateHandler")
   191  	}
   192  	if o.CustomersGetIDHandler == nil {
   193  		unregistered = append(unregistered, "customers.GetIDHandler")
   194  	}
   195  
   196  	if len(unregistered) > 0 {
   197  		return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", "))
   198  	}
   199  
   200  	return nil
   201  }
   202  
   203  // ServeErrorFor gets a error handler for a given operation id
   204  func (o *AuthSampleAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) {
   205  	return o.ServeError
   206  }
   207  
   208  // AuthenticatorsFor gets the authenticators for the specified security schemes
   209  func (o *AuthSampleAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator {
   210  	result := make(map[string]runtime.Authenticator)
   211  	for name := range schemes {
   212  		switch name {
   213  		case "key":
   214  			scheme := schemes[name]
   215  			result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, func(token string) (interface{}, error) {
   216  				return o.KeyAuth(token)
   217  			})
   218  
   219  		}
   220  	}
   221  	return result
   222  }
   223  
   224  // Authorizer returns the registered authorizer
   225  func (o *AuthSampleAPI) Authorizer() runtime.Authorizer {
   226  	return o.APIAuthorizer
   227  }
   228  
   229  // ConsumersFor gets the consumers for the specified media types.
   230  // MIME type parameters are ignored here.
   231  func (o *AuthSampleAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer {
   232  	result := make(map[string]runtime.Consumer, len(mediaTypes))
   233  	for _, mt := range mediaTypes {
   234  		switch mt {
   235  		case "application/keyauth.api.v1+json":
   236  			result["application/keyauth.api.v1+json"] = o.JSONConsumer
   237  		}
   238  
   239  		if c, ok := o.customConsumers[mt]; ok {
   240  			result[mt] = c
   241  		}
   242  	}
   243  	return result
   244  }
   245  
   246  // ProducersFor gets the producers for the specified media types.
   247  // MIME type parameters are ignored here.
   248  func (o *AuthSampleAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer {
   249  	result := make(map[string]runtime.Producer, len(mediaTypes))
   250  	for _, mt := range mediaTypes {
   251  		switch mt {
   252  		case "application/keyauth.api.v1+json":
   253  			result["application/keyauth.api.v1+json"] = o.JSONProducer
   254  		}
   255  
   256  		if p, ok := o.customProducers[mt]; ok {
   257  			result[mt] = p
   258  		}
   259  	}
   260  	return result
   261  }
   262  
   263  // HandlerFor gets a http.Handler for the provided operation method and path
   264  func (o *AuthSampleAPI) HandlerFor(method, path string) (http.Handler, bool) {
   265  	if o.handlers == nil {
   266  		return nil, false
   267  	}
   268  	um := strings.ToUpper(method)
   269  	if _, ok := o.handlers[um]; !ok {
   270  		return nil, false
   271  	}
   272  	if path == "/" {
   273  		path = ""
   274  	}
   275  	h, ok := o.handlers[um][path]
   276  	return h, ok
   277  }
   278  
   279  // Context returns the middleware context for the auth sample API
   280  func (o *AuthSampleAPI) Context() *middleware.Context {
   281  	if o.context == nil {
   282  		o.context = middleware.NewRoutableContext(o.spec, o, nil)
   283  	}
   284  
   285  	return o.context
   286  }
   287  
   288  func (o *AuthSampleAPI) initHandlerCache() {
   289  	o.Context() // don't care about the result, just that the initialization happened
   290  	if o.handlers == nil {
   291  		o.handlers = make(map[string]map[string]http.Handler)
   292  	}
   293  
   294  	if o.handlers["POST"] == nil {
   295  		o.handlers["POST"] = make(map[string]http.Handler)
   296  	}
   297  	o.handlers["POST"]["/customers"] = customers.NewCreate(o.context, o.CustomersCreateHandler)
   298  	if o.handlers["GET"] == nil {
   299  		o.handlers["GET"] = make(map[string]http.Handler)
   300  	}
   301  	o.handlers["GET"]["/customers"] = customers.NewGetID(o.context, o.CustomersGetIDHandler)
   302  }
   303  
   304  // Serve creates a http handler to serve the API over HTTP
   305  // can be used directly in http.ListenAndServe(":8000", api.Serve(nil))
   306  func (o *AuthSampleAPI) Serve(builder middleware.Builder) http.Handler {
   307  	o.Init()
   308  
   309  	if o.Middleware != nil {
   310  		return o.Middleware(builder)
   311  	}
   312  	if o.useSwaggerUI {
   313  		return o.context.APIHandlerSwaggerUI(builder)
   314  	}
   315  	return o.context.APIHandler(builder)
   316  }
   317  
   318  // Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit
   319  func (o *AuthSampleAPI) Init() {
   320  	if len(o.handlers) == 0 {
   321  		o.initHandlerCache()
   322  	}
   323  }
   324  
   325  // RegisterConsumer allows you to add (or override) a consumer for a media type.
   326  func (o *AuthSampleAPI) RegisterConsumer(mediaType string, consumer runtime.Consumer) {
   327  	o.customConsumers[mediaType] = consumer
   328  }
   329  
   330  // RegisterProducer allows you to add (or override) a producer for a media type.
   331  func (o *AuthSampleAPI) RegisterProducer(mediaType string, producer runtime.Producer) {
   332  	o.customProducers[mediaType] = producer
   333  }
   334  
   335  // AddMiddlewareFor adds a http middleware to existing handler
   336  func (o *AuthSampleAPI) AddMiddlewareFor(method, path string, builder middleware.Builder) {
   337  	um := strings.ToUpper(method)
   338  	if path == "/" {
   339  		path = ""
   340  	}
   341  	o.Init()
   342  	if h, ok := o.handlers[um][path]; ok {
   343  		o.handlers[method][path] = builder(h)
   344  	}
   345  }