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