github.com/josephspurrier/go-swagger@v0.2.1-0.20221129144919-1f672a142a00/examples/composed-auth/restapi/operations/multi_auth_example_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/loads"
    15  	"github.com/go-openapi/runtime"
    16  	"github.com/go-openapi/runtime/middleware"
    17  	"github.com/go-openapi/runtime/security"
    18  	"github.com/go-openapi/spec"
    19  	"github.com/go-openapi/strfmt"
    20  	"github.com/go-openapi/swag"
    21  
    22  	"github.com/go-swagger/go-swagger/examples/composed-auth/models"
    23  )
    24  
    25  // NewMultiAuthExampleAPI creates a new MultiAuthExample instance
    26  func NewMultiAuthExampleAPI(spec *loads.Document) *MultiAuthExampleAPI {
    27  	return &MultiAuthExampleAPI{
    28  		handlers:            make(map[string]map[string]http.Handler),
    29  		formats:             strfmt.Default,
    30  		defaultConsumes:     "application/json",
    31  		defaultProduces:     "application/json",
    32  		customConsumers:     make(map[string]runtime.Consumer),
    33  		customProducers:     make(map[string]runtime.Producer),
    34  		PreServerShutdown:   func() {},
    35  		ServerShutdown:      func() {},
    36  		spec:                spec,
    37  		useSwaggerUI:        false,
    38  		ServeError:          errors.ServeError,
    39  		BasicAuthenticator:  security.BasicAuth,
    40  		APIKeyAuthenticator: security.APIKeyAuth,
    41  		BearerAuthenticator: security.BearerAuth,
    42  
    43  		JSONConsumer: runtime.JSONConsumer(),
    44  
    45  		JSONProducer: runtime.JSONProducer(),
    46  
    47  		AddOrderHandler: AddOrderHandlerFunc(func(params AddOrderParams, principal *models.Principal) middleware.Responder {
    48  			return middleware.NotImplemented("operation AddOrder has not yet been implemented")
    49  		}),
    50  		GetAccountHandler: GetAccountHandlerFunc(func(params GetAccountParams, principal *models.Principal) middleware.Responder {
    51  			return middleware.NotImplemented("operation GetAccount has not yet been implemented")
    52  		}),
    53  		GetItemsHandler: GetItemsHandlerFunc(func(params GetItemsParams) middleware.Responder {
    54  			return middleware.NotImplemented("operation GetItems has not yet been implemented")
    55  		}),
    56  		GetOrderHandler: GetOrderHandlerFunc(func(params GetOrderParams, principal *models.Principal) middleware.Responder {
    57  			return middleware.NotImplemented("operation GetOrder has not yet been implemented")
    58  		}),
    59  		GetOrdersForItemHandler: GetOrdersForItemHandlerFunc(func(params GetOrdersForItemParams, principal *models.Principal) middleware.Responder {
    60  			return middleware.NotImplemented("operation GetOrdersForItem has not yet been implemented")
    61  		}),
    62  
    63  		HasRoleAuth: func(token string, scopes []string) (*models.Principal, error) {
    64  			return nil, errors.NotImplemented("oauth2 bearer auth (hasRole) has not yet been implemented")
    65  		},
    66  		// Applies when the Authorization header is set with the Basic scheme
    67  		IsRegisteredAuth: func(user string, pass string) (*models.Principal, error) {
    68  			return nil, errors.NotImplemented("basic auth  (isRegistered) has not yet been implemented")
    69  		},
    70  		// Applies when the "X-Custom-Key" header is set
    71  		IsResellerAuth: func(token string) (*models.Principal, error) {
    72  			return nil, errors.NotImplemented("api key auth (isReseller) X-Custom-Key from header param [X-Custom-Key] has not yet been implemented")
    73  		},
    74  		// Applies when the "CustomKeyAsQuery" query is set
    75  		IsResellerQueryAuth: func(token string) (*models.Principal, error) {
    76  			return nil, errors.NotImplemented("api key auth (isResellerQuery) CustomKeyAsQuery from query param [CustomKeyAsQuery] has not yet been implemented")
    77  		},
    78  		// default authorizer is authorized meaning no requests are blocked
    79  		APIAuthorizer: security.Authorized(),
    80  	}
    81  }
    82  
    83  /*
    84  MultiAuthExampleAPI This sample API demonstrates how to compose several authentication schemes
    85  and configure complex security requirements for your operations.
    86  
    87  This API simulates a very simple market place with customers and resellers
    88  of items.
    89  
    90  Personas:
    91    - as a first time user, I want to see all items on sales
    92    - as a registered customer, I want to post orders for items and
    93      consult my past orders
    94    - as a registered reseller, I want to see all pending orders on the items
    95      I am selling on the market place
    96    - as a reseller managing my own inventories, I want to post replenishment orders for the items I provide
    97    - as a register user, I want to consult my personal account infos
    98  
    99  The situation we defined on the authentication side is as follows:
   100    - every known user is authenticated using a basic token
   101    - resellers are authenticated using API keys - we let the option to authenticate using a header or query param
   102    - any registered user (customer or reseller) will add a signed JWT to access more API endpoints
   103  
   104  Obviously, there are several ways to achieve the same result. We just wanted to demonstrate here how
   105  security requirements may compose several schemes.
   106  
   107  Note that we used the "OAuth2" declaration here but don't implement a real
   108  OAuth2 workflow: our intend here is just to be able to extract scopes from a passed JWT token (the
   109  only way to manipulate scoped authorizers with Swagger 2.0 is to declare them with type "oauth2").
   110  */
   111  type MultiAuthExampleAPI struct {
   112  	spec            *loads.Document
   113  	context         *middleware.Context
   114  	handlers        map[string]map[string]http.Handler
   115  	formats         strfmt.Registry
   116  	customConsumers map[string]runtime.Consumer
   117  	customProducers map[string]runtime.Producer
   118  	defaultConsumes string
   119  	defaultProduces string
   120  	Middleware      func(middleware.Builder) http.Handler
   121  	useSwaggerUI    bool
   122  
   123  	// BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function.
   124  	// It has a default implementation in the security package, however you can replace it for your particular usage.
   125  	BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator
   126  
   127  	// APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function.
   128  	// It has a default implementation in the security package, however you can replace it for your particular usage.
   129  	APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator
   130  
   131  	// BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function.
   132  	// It has a default implementation in the security package, however you can replace it for your particular usage.
   133  	BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator
   134  
   135  	// JSONConsumer registers a consumer for the following mime types:
   136  	//   - application/json
   137  	JSONConsumer runtime.Consumer
   138  
   139  	// JSONProducer registers a producer for the following mime types:
   140  	//   - application/json
   141  	JSONProducer runtime.Producer
   142  
   143  	// HasRoleAuth registers a function that takes an access token and a collection of required scopes and returns a principal
   144  	// it performs authentication based on an oauth2 bearer token provided in the request
   145  	HasRoleAuth func(string, []string) (*models.Principal, error)
   146  
   147  	// IsRegisteredAuth registers a function that takes username and password and returns a principal
   148  	// it performs authentication with basic auth
   149  	IsRegisteredAuth func(string, string) (*models.Principal, error)
   150  
   151  	// IsResellerAuth registers a function that takes a token and returns a principal
   152  	// it performs authentication based on an api key X-Custom-Key provided in the header
   153  	IsResellerAuth func(string) (*models.Principal, error)
   154  
   155  	// IsResellerQueryAuth registers a function that takes a token and returns a principal
   156  	// it performs authentication based on an api key CustomKeyAsQuery provided in the query
   157  	IsResellerQueryAuth func(string) (*models.Principal, error)
   158  
   159  	// APIAuthorizer provides access control (ACL/RBAC/ABAC) by providing access to the request and authenticated principal
   160  	APIAuthorizer runtime.Authorizer
   161  
   162  	// AddOrderHandler sets the operation handler for the add order operation
   163  	AddOrderHandler AddOrderHandler
   164  	// GetAccountHandler sets the operation handler for the get account operation
   165  	GetAccountHandler GetAccountHandler
   166  	// GetItemsHandler sets the operation handler for the get items operation
   167  	GetItemsHandler GetItemsHandler
   168  	// GetOrderHandler sets the operation handler for the get order operation
   169  	GetOrderHandler GetOrderHandler
   170  	// GetOrdersForItemHandler sets the operation handler for the get orders for item operation
   171  	GetOrdersForItemHandler GetOrdersForItemHandler
   172  
   173  	// ServeError is called when an error is received, there is a default handler
   174  	// but you can set your own with this
   175  	ServeError func(http.ResponseWriter, *http.Request, error)
   176  
   177  	// PreServerShutdown is called before the HTTP(S) server is shutdown
   178  	// This allows for custom functions to get executed before the HTTP(S) server stops accepting traffic
   179  	PreServerShutdown func()
   180  
   181  	// ServerShutdown is called when the HTTP(S) server is shut down and done
   182  	// handling all active connections and does not accept connections any more
   183  	ServerShutdown func()
   184  
   185  	// Custom command line argument groups with their descriptions
   186  	CommandLineOptionsGroups []swag.CommandLineOptionsGroup
   187  
   188  	// User defined logger function.
   189  	Logger func(string, ...interface{})
   190  }
   191  
   192  // UseRedoc for documentation at /docs
   193  func (o *MultiAuthExampleAPI) UseRedoc() {
   194  	o.useSwaggerUI = false
   195  }
   196  
   197  // UseSwaggerUI for documentation at /docs
   198  func (o *MultiAuthExampleAPI) UseSwaggerUI() {
   199  	o.useSwaggerUI = true
   200  }
   201  
   202  // SetDefaultProduces sets the default produces media type
   203  func (o *MultiAuthExampleAPI) SetDefaultProduces(mediaType string) {
   204  	o.defaultProduces = mediaType
   205  }
   206  
   207  // SetDefaultConsumes returns the default consumes media type
   208  func (o *MultiAuthExampleAPI) SetDefaultConsumes(mediaType string) {
   209  	o.defaultConsumes = mediaType
   210  }
   211  
   212  // SetSpec sets a spec that will be served for the clients.
   213  func (o *MultiAuthExampleAPI) SetSpec(spec *loads.Document) {
   214  	o.spec = spec
   215  }
   216  
   217  // DefaultProduces returns the default produces media type
   218  func (o *MultiAuthExampleAPI) DefaultProduces() string {
   219  	return o.defaultProduces
   220  }
   221  
   222  // DefaultConsumes returns the default consumes media type
   223  func (o *MultiAuthExampleAPI) DefaultConsumes() string {
   224  	return o.defaultConsumes
   225  }
   226  
   227  // Formats returns the registered string formats
   228  func (o *MultiAuthExampleAPI) Formats() strfmt.Registry {
   229  	return o.formats
   230  }
   231  
   232  // RegisterFormat registers a custom format validator
   233  func (o *MultiAuthExampleAPI) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) {
   234  	o.formats.Add(name, format, validator)
   235  }
   236  
   237  // Validate validates the registrations in the MultiAuthExampleAPI
   238  func (o *MultiAuthExampleAPI) Validate() error {
   239  	var unregistered []string
   240  
   241  	if o.JSONConsumer == nil {
   242  		unregistered = append(unregistered, "JSONConsumer")
   243  	}
   244  
   245  	if o.JSONProducer == nil {
   246  		unregistered = append(unregistered, "JSONProducer")
   247  	}
   248  
   249  	if o.HasRoleAuth == nil {
   250  		unregistered = append(unregistered, "HasRoleAuth")
   251  	}
   252  	if o.IsRegisteredAuth == nil {
   253  		unregistered = append(unregistered, "IsRegisteredAuth")
   254  	}
   255  	if o.IsResellerAuth == nil {
   256  		unregistered = append(unregistered, "XCustomKeyAuth")
   257  	}
   258  	if o.IsResellerQueryAuth == nil {
   259  		unregistered = append(unregistered, "CustomKeyAsQueryAuth")
   260  	}
   261  
   262  	if o.AddOrderHandler == nil {
   263  		unregistered = append(unregistered, "AddOrderHandler")
   264  	}
   265  	if o.GetAccountHandler == nil {
   266  		unregistered = append(unregistered, "GetAccountHandler")
   267  	}
   268  	if o.GetItemsHandler == nil {
   269  		unregistered = append(unregistered, "GetItemsHandler")
   270  	}
   271  	if o.GetOrderHandler == nil {
   272  		unregistered = append(unregistered, "GetOrderHandler")
   273  	}
   274  	if o.GetOrdersForItemHandler == nil {
   275  		unregistered = append(unregistered, "GetOrdersForItemHandler")
   276  	}
   277  
   278  	if len(unregistered) > 0 {
   279  		return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", "))
   280  	}
   281  
   282  	return nil
   283  }
   284  
   285  // ServeErrorFor gets a error handler for a given operation id
   286  func (o *MultiAuthExampleAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) {
   287  	return o.ServeError
   288  }
   289  
   290  // AuthenticatorsFor gets the authenticators for the specified security schemes
   291  func (o *MultiAuthExampleAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator {
   292  	result := make(map[string]runtime.Authenticator)
   293  	for name := range schemes {
   294  		switch name {
   295  		case "hasRole":
   296  			result[name] = o.BearerAuthenticator(name, func(token string, scopes []string) (interface{}, error) {
   297  				return o.HasRoleAuth(token, scopes)
   298  			})
   299  
   300  		case "isRegistered":
   301  			result[name] = o.BasicAuthenticator(func(username, password string) (interface{}, error) {
   302  				return o.IsRegisteredAuth(username, password)
   303  			})
   304  
   305  		case "isReseller":
   306  			scheme := schemes[name]
   307  			result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, func(token string) (interface{}, error) {
   308  				return o.IsResellerAuth(token)
   309  			})
   310  
   311  		case "isResellerQuery":
   312  			scheme := schemes[name]
   313  			result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, func(token string) (interface{}, error) {
   314  				return o.IsResellerQueryAuth(token)
   315  			})
   316  
   317  		}
   318  	}
   319  	return result
   320  }
   321  
   322  // Authorizer returns the registered authorizer
   323  func (o *MultiAuthExampleAPI) Authorizer() runtime.Authorizer {
   324  	return o.APIAuthorizer
   325  }
   326  
   327  // ConsumersFor gets the consumers for the specified media types.
   328  // MIME type parameters are ignored here.
   329  func (o *MultiAuthExampleAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer {
   330  	result := make(map[string]runtime.Consumer, len(mediaTypes))
   331  	for _, mt := range mediaTypes {
   332  		switch mt {
   333  		case "application/json":
   334  			result["application/json"] = o.JSONConsumer
   335  		}
   336  
   337  		if c, ok := o.customConsumers[mt]; ok {
   338  			result[mt] = c
   339  		}
   340  	}
   341  	return result
   342  }
   343  
   344  // ProducersFor gets the producers for the specified media types.
   345  // MIME type parameters are ignored here.
   346  func (o *MultiAuthExampleAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer {
   347  	result := make(map[string]runtime.Producer, len(mediaTypes))
   348  	for _, mt := range mediaTypes {
   349  		switch mt {
   350  		case "application/json":
   351  			result["application/json"] = o.JSONProducer
   352  		}
   353  
   354  		if p, ok := o.customProducers[mt]; ok {
   355  			result[mt] = p
   356  		}
   357  	}
   358  	return result
   359  }
   360  
   361  // HandlerFor gets a http.Handler for the provided operation method and path
   362  func (o *MultiAuthExampleAPI) HandlerFor(method, path string) (http.Handler, bool) {
   363  	if o.handlers == nil {
   364  		return nil, false
   365  	}
   366  	um := strings.ToUpper(method)
   367  	if _, ok := o.handlers[um]; !ok {
   368  		return nil, false
   369  	}
   370  	if path == "/" {
   371  		path = ""
   372  	}
   373  	h, ok := o.handlers[um][path]
   374  	return h, ok
   375  }
   376  
   377  // Context returns the middleware context for the multi auth example API
   378  func (o *MultiAuthExampleAPI) Context() *middleware.Context {
   379  	if o.context == nil {
   380  		o.context = middleware.NewRoutableContext(o.spec, o, nil)
   381  	}
   382  
   383  	return o.context
   384  }
   385  
   386  func (o *MultiAuthExampleAPI) initHandlerCache() {
   387  	o.Context() // don't care about the result, just that the initialization happened
   388  	if o.handlers == nil {
   389  		o.handlers = make(map[string]map[string]http.Handler)
   390  	}
   391  
   392  	if o.handlers["POST"] == nil {
   393  		o.handlers["POST"] = make(map[string]http.Handler)
   394  	}
   395  	o.handlers["POST"]["/order/add"] = NewAddOrder(o.context, o.AddOrderHandler)
   396  	if o.handlers["GET"] == nil {
   397  		o.handlers["GET"] = make(map[string]http.Handler)
   398  	}
   399  	o.handlers["GET"]["/account"] = NewGetAccount(o.context, o.GetAccountHandler)
   400  	if o.handlers["GET"] == nil {
   401  		o.handlers["GET"] = make(map[string]http.Handler)
   402  	}
   403  	o.handlers["GET"]["/items"] = NewGetItems(o.context, o.GetItemsHandler)
   404  	if o.handlers["GET"] == nil {
   405  		o.handlers["GET"] = make(map[string]http.Handler)
   406  	}
   407  	o.handlers["GET"]["/order/{orderID}"] = NewGetOrder(o.context, o.GetOrderHandler)
   408  	if o.handlers["GET"] == nil {
   409  		o.handlers["GET"] = make(map[string]http.Handler)
   410  	}
   411  	o.handlers["GET"]["/orders/{itemID}"] = NewGetOrdersForItem(o.context, o.GetOrdersForItemHandler)
   412  }
   413  
   414  // Serve creates a http handler to serve the API over HTTP
   415  // can be used directly in http.ListenAndServe(":8000", api.Serve(nil))
   416  func (o *MultiAuthExampleAPI) Serve(builder middleware.Builder) http.Handler {
   417  	o.Init()
   418  
   419  	if o.Middleware != nil {
   420  		return o.Middleware(builder)
   421  	}
   422  	if o.useSwaggerUI {
   423  		return o.context.APIHandlerSwaggerUI(builder)
   424  	}
   425  	return o.context.APIHandler(builder)
   426  }
   427  
   428  // Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit
   429  func (o *MultiAuthExampleAPI) Init() {
   430  	if len(o.handlers) == 0 {
   431  		o.initHandlerCache()
   432  	}
   433  }
   434  
   435  // RegisterConsumer allows you to add (or override) a consumer for a media type.
   436  func (o *MultiAuthExampleAPI) RegisterConsumer(mediaType string, consumer runtime.Consumer) {
   437  	o.customConsumers[mediaType] = consumer
   438  }
   439  
   440  // RegisterProducer allows you to add (or override) a producer for a media type.
   441  func (o *MultiAuthExampleAPI) RegisterProducer(mediaType string, producer runtime.Producer) {
   442  	o.customProducers[mediaType] = producer
   443  }
   444  
   445  // AddMiddlewareFor adds a http middleware to existing handler
   446  func (o *MultiAuthExampleAPI) AddMiddlewareFor(method, path string, builder middleware.Builder) {
   447  	um := strings.ToUpper(method)
   448  	if path == "/" {
   449  		path = ""
   450  	}
   451  	o.Init()
   452  	if h, ok := o.handlers[um][path]; ok {
   453  		o.handlers[method][path] = builder(h)
   454  	}
   455  }