github.com/djarvur/go-swagger@v0.18.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 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 implemention 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 implemention 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 implemention 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, scheme := range schemes { 280 switch name { 281 282 case "hasRole": 283 284 result[name] = o.BearerAuthenticator(scheme.Name, func(token string, scopes []string) (interface{}, error) { 285 return o.HasRoleAuth(token, scopes) 286 }) 287 288 case "isRegistered": 289 _ = scheme 290 result[name] = o.BasicAuthenticator(func(username, password string) (interface{}, error) { 291 return o.IsRegisteredAuth(username, password) 292 }) 293 294 case "isReseller": 295 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 result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, func(token string) (interface{}, error) { 303 return o.IsResellerQueryAuth(token) 304 }) 305 306 } 307 } 308 return result 309 310 } 311 312 // Authorizer returns the registered authorizer 313 func (o *MultiAuthExampleAPI) Authorizer() runtime.Authorizer { 314 315 return o.APIAuthorizer 316 317 } 318 319 // ConsumersFor gets the consumers for the specified media types 320 func (o *MultiAuthExampleAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer { 321 322 result := make(map[string]runtime.Consumer) 323 for _, mt := range mediaTypes { 324 switch mt { 325 326 case "application/json": 327 result["application/json"] = o.JSONConsumer 328 329 } 330 331 if c, ok := o.customConsumers[mt]; ok { 332 result[mt] = c 333 } 334 } 335 return result 336 337 } 338 339 // ProducersFor gets the producers for the specified media types 340 func (o *MultiAuthExampleAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer { 341 342 result := make(map[string]runtime.Producer) 343 for _, mt := range mediaTypes { 344 switch mt { 345 346 case "application/json": 347 result["application/json"] = o.JSONProducer 348 349 } 350 351 if p, ok := o.customProducers[mt]; ok { 352 result[mt] = p 353 } 354 } 355 return result 356 357 } 358 359 // HandlerFor gets a http.Handler for the provided operation method and path 360 func (o *MultiAuthExampleAPI) HandlerFor(method, path string) (http.Handler, bool) { 361 if o.handlers == nil { 362 return nil, false 363 } 364 um := strings.ToUpper(method) 365 if _, ok := o.handlers[um]; !ok { 366 return nil, false 367 } 368 if path == "/" { 369 path = "" 370 } 371 h, ok := o.handlers[um][path] 372 return h, ok 373 } 374 375 // Context returns the middleware context for the multi auth example API 376 func (o *MultiAuthExampleAPI) Context() *middleware.Context { 377 if o.context == nil { 378 o.context = middleware.NewRoutableContext(o.spec, o, nil) 379 } 380 381 return o.context 382 } 383 384 func (o *MultiAuthExampleAPI) initHandlerCache() { 385 o.Context() // don't care about the result, just that the initialization happened 386 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 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 401 if o.handlers["GET"] == nil { 402 o.handlers["GET"] = make(map[string]http.Handler) 403 } 404 o.handlers["GET"]["/items"] = NewGetItems(o.context, o.GetItemsHandler) 405 406 if o.handlers["GET"] == nil { 407 o.handlers["GET"] = make(map[string]http.Handler) 408 } 409 o.handlers["GET"]["/order/{orderID}"] = NewGetOrder(o.context, o.GetOrderHandler) 410 411 if o.handlers["GET"] == nil { 412 o.handlers["GET"] = make(map[string]http.Handler) 413 } 414 o.handlers["GET"]["/orders/{itemID}"] = NewGetOrdersForItem(o.context, o.GetOrdersForItemHandler) 415 416 } 417 418 // Serve creates a http handler to serve the API over HTTP 419 // can be used directly in http.ListenAndServe(":8000", api.Serve(nil)) 420 func (o *MultiAuthExampleAPI) Serve(builder middleware.Builder) http.Handler { 421 o.Init() 422 423 if o.Middleware != nil { 424 return o.Middleware(builder) 425 } 426 return o.context.APIHandler(builder) 427 } 428 429 // Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit 430 func (o *MultiAuthExampleAPI) Init() { 431 if len(o.handlers) == 0 { 432 o.initHandlerCache() 433 } 434 } 435 436 // RegisterConsumer allows you to add (or override) a consumer for a media type. 437 func (o *MultiAuthExampleAPI) RegisterConsumer(mediaType string, consumer runtime.Consumer) { 438 o.customConsumers[mediaType] = consumer 439 } 440 441 // RegisterProducer allows you to add (or override) a producer for a media type. 442 func (o *MultiAuthExampleAPI) RegisterProducer(mediaType string, producer runtime.Producer) { 443 o.customProducers[mediaType] = producer 444 }