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