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