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