github.com/thetreep/go-swagger@v0.0.0-20240223100711-35af64f14f01/examples/oauth2/restapi/configure_oauth_sample.go (about) 1 // This file is safe to edit. Once it exists it will not be overwritten 2 3 package restapi 4 5 import ( 6 "context" 7 "crypto/tls" 8 "log" 9 "net/http" 10 11 errors "github.com/go-openapi/errors" 12 runtime "github.com/go-openapi/runtime" 13 middleware "github.com/go-openapi/runtime/middleware" 14 "github.com/go-openapi/swag" 15 16 "github.com/thetreep/go-swagger/examples/oauth2/restapi/operations" 17 "github.com/thetreep/go-swagger/examples/oauth2/restapi/operations/customers" 18 19 models "github.com/thetreep/go-swagger/examples/oauth2/models" 20 ) 21 22 //go:generate swagger generate server --target .. --name oauthSample --spec ../swagger.yml --principal models.Principal 23 24 func configureFlags(api *operations.OauthSampleAPI) { 25 // api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... } 26 } 27 28 func configureAPI(api *operations.OauthSampleAPI) http.Handler { 29 // configure the api here 30 api.ServeError = errors.ServeError 31 32 // Set your custom logger if needed. Default one is log.Printf 33 // Expected interface func(string, ...interface{}) 34 // 35 // Example: 36 api.Logger = log.Printf 37 38 api.JSONConsumer = runtime.JSONConsumer() 39 40 api.JSONProducer = runtime.JSONProducer() 41 42 api.OauthSecurityAuth = func(token string, scopes []string) (*models.Principal, error) { 43 ok, err := authenticated(token) 44 if err != nil { 45 return nil, errors.New(401, "error authenticate") 46 } 47 if !ok { 48 return nil, errors.New(401, "invalid token") 49 } 50 prin := models.Principal(token) 51 return &prin, nil 52 53 } 54 55 // Set your custom authorizer if needed. Default one is security.Authorized() 56 // Expected interface runtime.Authorizer 57 // 58 // Example: 59 // api.APIAuthorizer = security.Authorized() 60 api.GetAuthCallbackHandler = operations.GetAuthCallbackHandlerFunc( 61 func(params operations.GetAuthCallbackParams) middleware.Responder { 62 token, err := callback(params.HTTPRequest) 63 if err != nil { 64 return middleware.NotImplemented("operation .GetAuthCallback error") 65 } 66 log.Println("Token", token) 67 return operations.NewGetAuthCallbackDefault(500).WithPayload(&models.Error{Code: 500, Message: swag.String(token)}) 68 }, 69 ) 70 api.GetLoginHandler = operations.GetLoginHandlerFunc( 71 func(params operations.GetLoginParams) middleware.Responder { 72 return login(params.HTTPRequest) 73 }, 74 ) 75 api.CustomersCreateHandler = customers.CreateHandlerFunc( 76 func(params customers.CreateParams, principal *models.Principal) middleware.Responder { 77 return middleware.NotImplemented("operation customers.Create has not yet been implemented") 78 }, 79 ) 80 api.CustomersGetIDHandler = customers.GetIDHandlerFunc( 81 func(params customers.GetIDParams, principal *models.Principal) middleware.Responder { 82 log.Println("hit customer API") 83 return middleware.NotImplemented("operation customers.GetID has not yet been implemented") 84 }, 85 ) 86 87 api.ServerShutdown = func() {} 88 89 return setupGlobalMiddleware(api.Serve(setupMiddlewares)) 90 } 91 92 // The TLS configuration before HTTPS server starts. 93 func configureTLS(tlsConfig *tls.Config) { 94 // Make all necessary changes to the TLS configuration here. 95 } 96 97 // As soon as server is initialized but not run yet, this function will be called. 98 // If you need to modify a config, store server instance to stop it individually later, this is the place. 99 // This function can be called multiple times, depending on the number of serving schemes. 100 // scheme value will be set accordingly: "http", "https" or "unix". 101 func configureServer(s *http.Server, scheme, addr string) { 102 } 103 104 // This demonstrates how to enrich and pass custom context keys. 105 // In this case, we cache the current responseWriter in context. 106 type customContextKey int8 107 108 const ( 109 _ customContextKey = iota 110 ctxResponseWriter 111 ) 112 113 // The middleware configuration is for the handler executors. These do not apply to the swagger.json document. 114 // The middleware executes after routing but before authentication, binding and validation. 115 func setupMiddlewares(handler http.Handler) http.Handler { 116 ourFunc := func(w http.ResponseWriter, r *http.Request) { 117 rctx := context.WithValue(r.Context(), ctxResponseWriter, w) 118 handler.ServeHTTP(w, r.WithContext(rctx)) 119 } 120 return http.HandlerFunc(ourFunc) 121 122 } 123 124 // The middleware configuration happens before anything, this middleware also applies to serving the swagger.json document. 125 // So this is a good place to plug in a panic handling middleware, logging and metrics. 126 func setupGlobalMiddleware(handler http.Handler) http.Handler { 127 return handler 128 }