From a8c76b28776b3c962284331ad6bfebdd31e1a614 Mon Sep 17 00:00:00 2001 From: Cam Otts Date: Wed, 22 Feb 2023 09:37:07 -0600 Subject: [PATCH] initial testing for oauth protecting shares --- cmd/zrok/sharePublic.go | 22 ++- controller/controller.go | 14 +- controller/oauth.go | 83 ++++++++ controller/sharePrivate.go | 2 +- controller/sharePublic.go | 2 +- controller/zrokEdgeSdk/config.go | 10 +- endpoints/publicProxy/http.go | 23 ++- go.mod | 13 ++ go.sum | 28 +++ model/config.go | 9 + .../share/oauth_authenticate_parameters.go | 177 ++++++++++++++++++ .../share/oauth_authenticate_responses.go | 83 ++++++++ rest_client_zrok/share/share_client.go | 40 ++++ rest_client_zrok/share/share_responses.go | 57 ++++++ rest_model_zrok/share_request.go | 50 +++++ rest_server_zrok/embedded_spec.go | 84 +++++++++ .../operations/share/oauth_authenticate.go | 56 ++++++ .../share/oauth_authenticate_parameters.go | 113 +++++++++++ .../share/oauth_authenticate_responses.go | 37 ++++ .../share/oauth_authenticate_urlbuilder.go | 106 +++++++++++ .../operations/share/share_responses.go | 25 +++ rest_server_zrok/operations/zrok_api.go | 12 ++ specs/zrok.yml | 28 +++ ui/src/api/share.js | 20 ++ ui/src/api/types.js | 2 + 25 files changed, 1078 insertions(+), 18 deletions(-) create mode 100644 controller/oauth.go create mode 100644 rest_client_zrok/share/oauth_authenticate_parameters.go create mode 100644 rest_client_zrok/share/oauth_authenticate_responses.go create mode 100644 rest_server_zrok/operations/share/oauth_authenticate.go create mode 100644 rest_server_zrok/operations/share/oauth_authenticate_parameters.go create mode 100644 rest_server_zrok/operations/share/oauth_authenticate_responses.go create mode 100644 rest_server_zrok/operations/share/oauth_authenticate_urlbuilder.go diff --git a/cmd/zrok/sharePublic.go b/cmd/zrok/sharePublic.go index 336c51b7..bf08e69f 100644 --- a/cmd/zrok/sharePublic.go +++ b/cmd/zrok/sharePublic.go @@ -2,6 +2,11 @@ package main import ( "fmt" + "os" + "os/signal" + "strings" + "syscall" + tea "github.com/charmbracelet/bubbletea" "github.com/go-openapi/runtime" httptransport "github.com/go-openapi/runtime/client" @@ -16,10 +21,6 @@ import ( "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/spf13/cobra" - "os" - "os/signal" - "strings" - "syscall" ) func init() { @@ -32,6 +33,8 @@ type sharePublicCommand struct { backendMode string headless bool insecure bool + oauthProvider string + oauthEmailDomains []string cmd *cobra.Command } @@ -47,6 +50,10 @@ func newSharePublicCommand() *sharePublicCommand { cmd.Flags().StringVar(&command.backendMode, "backend-mode", "proxy", "The backend mode {proxy, web}") cmd.Flags().BoolVar(&command.headless, "headless", false, "Disable TUI and run headless") cmd.Flags().BoolVar(&command.insecure, "insecure", false, "Enable insecure TLS certificate validation for ") + + cmd.Flags().StringVar(&command.oauthProvider, "provider", "", "Provider to authenticate against with oauth") + cmd.Flags().StringArrayVar(&command.oauthEmailDomains, "oauth-domains", []string{}, "Valid email domains for oauth authentication") + cmd.MarkFlagsMutuallyExclusive("basic-auth", "provider") cmd.Run = command.run return command } @@ -122,6 +129,13 @@ func (cmd *sharePublicCommand) run(_ *cobra.Command, args []string) { } } } + if cmd.oauthProvider != "" { + req.Body.AuthScheme = string(model.Oauth) + req.Body.OauthProvider = cmd.oauthProvider + } + if len(cmd.oauthEmailDomains) > 0 { + req.Body.OauthEmailDomains = cmd.oauthEmailDomains + } resp, err := zrok.Share.Share(req, auth) if err != nil { if !panicInstead { diff --git a/controller/controller.go b/controller/controller.go index a5974e7f..79ae24a4 100644 --- a/controller/controller.go +++ b/controller/controller.go @@ -20,10 +20,13 @@ import ( "github.com/pkg/errors" ) -var cfg *config.Config -var str *store.Store -var idb influxdb2.Client -var limitsAgent *limits.Agent +var ( + cfg *Config + str *store.Store + mtr *metricsAgent + idb influxdb2.Client + limitsAgent *limits.Agent +) func Run(inCfg *config.Config) error { cfg = inCfg @@ -68,7 +71,8 @@ func Run(inCfg *config.Config) error { api.MetadataOverviewHandler = newOverviewHandler() api.MetadataVersionHandler = metadata.VersionHandlerFunc(versionHandler) api.ShareAccessHandler = newAccessHandler() - api.ShareShareHandler = newShareHandler() + api.ShareOauthAuthenticateHandler = newOauthHandler() + api.ShareShareHandler = newShareHandler(cfg.Limits) api.ShareUnaccessHandler = newUnaccessHandler() api.ShareUnshareHandler = newUnshareHandler() api.ShareUpdateShareHandler = newUpdateShareHandler() diff --git a/controller/oauth.go b/controller/oauth.go new file mode 100644 index 00000000..ded13627 --- /dev/null +++ b/controller/oauth.go @@ -0,0 +1,83 @@ +package controller + +import ( + "context" + "encoding/base64" + "fmt" + "io" + "io/ioutil" + "net/http" + "net/url" + "strings" + + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider" + "github.com/go-openapi/runtime/middleware" + "github.com/openziti/zrok/rest_server_zrok/operations/share" + "github.com/sirupsen/logrus" +) + +type oauthHandler struct{} + +func newOauthHandler() *oauthHandler { + return &oauthHandler{} +} + +func (h *oauthHandler) Handle(params share.OauthAuthenticateParams) middleware.Responder { + awsUrl := "https:///oauth2/token" // COGNITO URL OR WHATEVER OAUTH PROVIDER URL + clientId := "" // PROVIDER CLIENT ID + secret := "" // PROVIDER CLIENT SECRET + auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", clientId, secret))) + grant := "authorization_code" + redirectUri := "http://localhost:18080/api/v1/oauth/authorize" + // scope := "email" + data := url.Values{} + data.Set("client_id", clientId) + data.Set("grant_type", grant) + // data.Set("scope", scope) + data.Set("code", params.Code) + data.Set("redirect_uri", redirectUri) + encodedData := data.Encode() + + c := http.Client{} + req := &http.Request{} + req.Method = http.MethodPost + req.URL, _ = url.Parse(awsUrl) + req.Body = io.NopCloser(strings.NewReader(encodedData)) + req.Header = http.Header{} + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + req.Header.Add("Authorization", fmt.Sprintf("Basic %s", auth)) + resp, err := c.Do(req) + // resp, err := http.Post(awsUrl, "application/x-www-form-urlencoded", strings.NewReader(encodedData)) + logrus.Error(err) + logrus.Error(resp) + b, err := ioutil.ReadAll(resp.Body) + logrus.Error(err) + logrus.Error(string(b)) + //user, err := cog.GetUser(&cognitoidentityprovider.GetUserInput{ + // AccessToken: aws.String(params.Code), + //}) + //if err != nil { + // logrus.Error(err) + //} + //logrus.Error(user) + logrus.Error("--------------") + return share.NewOauthAuthenticateOK() +} + +func old(params share.OauthAuthenticateParams) { + sdkConfig, err := config.LoadDefaultConfig(context.TODO()) + sdkConfig.Region = "us-east-1" + if err != nil { + fmt.Println("Couldn't load default configuration. Have you set up your AWS account?") + fmt.Println(err) + // return share.NewOauthAuthenticateOK() + } + + cog := cognitoidentityprovider.NewFromConfig(sdkConfig) + user, err := cog.GetUser(context.TODO(), &cognitoidentityprovider.GetUserInput{ + AccessToken: ¶ms.Code, + }) + logrus.Error(err) + logrus.Error(user) +} diff --git a/controller/sharePrivate.go b/controller/sharePrivate.go index 52853515..4ae27943 100644 --- a/controller/sharePrivate.go +++ b/controller/sharePrivate.go @@ -18,7 +18,7 @@ func (a *privateResourceAllocator) allocate(envZId, shrToken string, params shar for _, authUser := range params.Body.AuthUsers { authUsers = append(authUsers, &model.AuthUser{authUser.Username, authUser.Password}) } - cfgZId, err := zrokEdgeSdk.CreateConfig(zrokProxyConfigId, envZId, shrToken, params.Body.AuthScheme, authUsers, edge) + cfgZId, err := zrokEdgeSdk.CreateConfig(zrokProxyConfigId, envZId, shrToken, params.Body.AuthScheme, authUsers, params.Body.OauthProvider, params.Body.OauthEmailDomains, edge) if err != nil { return "", nil, err } diff --git a/controller/sharePublic.go b/controller/sharePublic.go index cb63ace6..77b8c23f 100644 --- a/controller/sharePublic.go +++ b/controller/sharePublic.go @@ -18,7 +18,7 @@ func (a *publicResourceAllocator) allocate(envZId, shrToken string, frontendZIds for _, authUser := range params.Body.AuthUsers { authUsers = append(authUsers, &model.AuthUser{authUser.Username, authUser.Password}) } - cfgId, err := zrokEdgeSdk.CreateConfig(zrokProxyConfigId, envZId, shrToken, params.Body.AuthScheme, authUsers, edge) + cfgId, err := zrokEdgeSdk.CreateConfig(zrokProxyConfigId, envZId, shrToken, params.Body.AuthScheme, authUsers, params.Body.OauthProvider, params.Body.OauthEmailDomains, edge) if err != nil { return "", nil, err } diff --git a/controller/zrokEdgeSdk/config.go b/controller/zrokEdgeSdk/config.go index 46a67ba7..cde825ed 100644 --- a/controller/zrokEdgeSdk/config.go +++ b/controller/zrokEdgeSdk/config.go @@ -8,10 +8,10 @@ import ( "github.com/openziti/edge-api/rest_model" "github.com/openziti/zrok/model" "github.com/sirupsen/logrus" - "time" ) -func CreateConfig(cfgTypeZId, envZId, shrToken string, authSchemeStr string, authUsers []*model.AuthUser, edge *rest_management_api_client.ZitiEdgeManagement) (cfgZId string, err error) { +// TODO: Create options struct +func CreateConfig(cfgTypeZId, envZId, shrToken string, authSchemeStr string, authUsers []*model.AuthUser, oauthProvider string, oauthEmailDomains []string, edge *rest_management_api_client.ZitiEdgeManagement) (cfgZId string, err error) { authScheme, err := model.ParseAuthScheme(authSchemeStr) if err != nil { return "", err @@ -25,6 +25,12 @@ func CreateConfig(cfgTypeZId, envZId, shrToken string, authSchemeStr string, aut cfg.BasicAuth.Users = append(cfg.BasicAuth.Users, &model.AuthUser{Username: authUser.Username, Password: authUser.Password}) } } + if cfg.AuthScheme == model.Oauth { + cfg.OauthAuth = &model.OauthAuth{ + Provider: oauthProvider, + EmailDomains: oauthEmailDomains, + } + } cfgCrt := &rest_model.ConfigCreate{ ConfigTypeID: &cfgTypeZId, Data: cfg, diff --git a/endpoints/publicProxy/http.go b/endpoints/publicProxy/http.go index e9aab21b..6fd6b977 100644 --- a/endpoints/publicProxy/http.go +++ b/endpoints/publicProxy/http.go @@ -3,6 +3,12 @@ package publicProxy import ( "context" "fmt" + "net" + "net/http" + "net/http/httputil" + "net/url" + "strings" + "github.com/openziti/sdk-golang/ziti" "github.com/openziti/zrok/endpoints" "github.com/openziti/zrok/endpoints/publicProxy/healthUi" @@ -12,11 +18,6 @@ import ( "github.com/openziti/zrok/zrokdir" "github.com/pkg/errors" "github.com/sirupsen/logrus" - "net" - "net/http" - "net/http/httputil" - "net/url" - "strings" ) type httpFrontend struct { @@ -181,6 +182,18 @@ func authHandler(handler http.Handler, realm string, cfg *Config, ctx ziti.Conte handler.ServeHTTP(w, r) + case string(model.Oauth): + logrus.Debugf("auth scheme oauth '%v'", shrToken) + awsUrl := "https://oauth2/authorize" // COGNITO URL OR WHATEVER OAUTH PROVIDER URL + responseType := "code" + clientId := "" // PROVIDER CLIENT ID + scope := "email" + redirectUri := "http://localhost:18080/api/v1/oauth/authorize" + redirectUrl := fmt.Sprintf("%s?response_type=%s&client_id=%s&redirect_uri=%s&state=STATE&scope=%s", awsUrl, responseType, clientId, redirectUri, scope) + http.Redirect(w, r, redirectUrl, http.StatusFound) + handler.ServeHTTP(w, r) + return + default: logrus.Infof("invalid auth scheme '%v'", scheme) writeUnauthorizedResponse(w, realm) diff --git a/go.mod b/go.mod index 514288b5..6cc7277c 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,8 @@ module github.com/openziti/zrok go 1.20 require ( + github.com/aws/aws-sdk-go-v2/config v1.18.13 + github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider v1.22.2 github.com/charmbracelet/bubbles v0.14.0 github.com/charmbracelet/bubbletea v0.23.1 github.com/charmbracelet/lipgloss v0.6.0 @@ -51,6 +53,17 @@ require ( github.com/antlr/antlr4/runtime/Go/antlr v0.0.0-20211106181442-e4c1a74c66bd // indirect github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect github.com/atotto/clipboard v0.1.4 // indirect + github.com/aws/aws-sdk-go-v2 v1.17.4 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.13.13 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.22 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.28 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.22 // indirect + github.com/aws/aws-sdk-go-v2/internal/ini v1.3.29 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.22 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.12.2 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.2 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.18.3 // indirect + github.com/aws/smithy-go v1.13.5 // indirect github.com/aymanbagabas/go-osc52 v1.0.3 // indirect github.com/biogo/store v0.0.0-20200525035639-8c94ae1e7c9c // indirect github.com/cenkalti/backoff/v4 v4.2.1 // indirect diff --git a/go.sum b/go.sum index b6531169..8096cff3 100644 --- a/go.sum +++ b/go.sum @@ -57,6 +57,32 @@ github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3d github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= +github.com/aws/aws-sdk-go-v2 v1.17.4 h1:wyC6p9Yfq6V2y98wfDsj6OnNQa4w2BLGCLIxzNhwOGY= +github.com/aws/aws-sdk-go-v2 v1.17.4/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= +github.com/aws/aws-sdk-go-v2/config v1.18.13 h1:v0xlYqbO6/EVlM8tUn2QEOA7btQxcgidEq2JRDBPTho= +github.com/aws/aws-sdk-go-v2/config v1.18.13/go.mod h1:r39wGSZB7wPDW1i54JyQXUpc5KsWjh5z/3S5D9eCqDg= +github.com/aws/aws-sdk-go-v2/credentials v1.13.13 h1:zw1KAc1kl00NYd3ofVmFrb09qnYlSQMeh+fmlQRAihI= +github.com/aws/aws-sdk-go-v2/credentials v1.13.13/go.mod h1:DW9nbIIF9MrIja0cBQrUpeWYQMSlNmP8fevLUyF9W38= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.22 h1:3aMfcTmoXtTZnaT86QlVaYh+BRMbvrrmZwIQ5jWqCZQ= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.22/go.mod h1:YGSIJyQ6D6FjKMQh16hVFSIUD54L4F7zTGePqYMYYJU= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.28 h1:r+XwaCLpIvCKjBIYy/HVZujQS9tsz5ohHG3ZIe0wKoE= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.28/go.mod h1:3lwChorpIM/BhImY/hy+Z6jekmN92cXGPI1QJasVPYY= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.22 h1:7AwGYXDdqRQYsluvKFmWoqpcOQJ4bH634SkYf3FNj/A= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.22/go.mod h1:EqK7gVrIGAHyZItrD1D8B0ilgwMD1GiWAmbU4u/JHNk= +github.com/aws/aws-sdk-go-v2/internal/ini v1.3.29 h1:J4xhFd6zHhdF9jPP0FQJ6WknzBboGMBNjKOv4iTuw4A= +github.com/aws/aws-sdk-go-v2/internal/ini v1.3.29/go.mod h1:TwuqRBGzxjQJIwH16/fOZodwXt2Zxa9/cwJC5ke4j7s= +github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider v1.22.2 h1:XJZ5vZlGyHeDDQ3hfFzPpTSTkOfxbcmFJQ8TVn0jPC4= +github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider v1.22.2/go.mod h1:SbWXSrT+zM2C8uZzZ8fLEsE3VNar9rg77PdgbGspyHQ= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.22 h1:LjFQf8hFuMO22HkV5VWGLBvmCLBCLPivUAmpdpnp4Vs= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.22/go.mod h1:xt0Au8yPIwYXf/GYPy/vl4K3CgwhfQMYbrH7DlUUIws= +github.com/aws/aws-sdk-go-v2/service/sso v1.12.2 h1:EN102fWY7hI5u/2FPheTrwwMHkSXfl49RYkeEnJsrCU= +github.com/aws/aws-sdk-go-v2/service/sso v1.12.2/go.mod h1:IgV8l3sj22nQDd5qcAGY0WenwCzCphqdbFOpfktZPrI= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.2 h1:f1lmlce7r13CX1BPyPqt9oh/H+uqOWc9367lDoGGwNQ= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.2/go.mod h1:O1YSOg3aekZibh2SngvCRRG+cRHKKlYgxf/JBF/Kr/k= +github.com/aws/aws-sdk-go-v2/service/sts v1.18.3 h1:s49mSnsBZEXjfGBkRfmK+nPqzT7Lt3+t2SmAKNyHblw= +github.com/aws/aws-sdk-go-v2/service/sts v1.18.3/go.mod h1:b+psTJn33Q4qGoDaM7ZiOVVG8uVjGI6HaZ8WBHdgDgU= +github.com/aws/smithy-go v1.13.5 h1:hgz0X/DX0dGqTYpGALqXJoRKRj5oQ7150i5FdTePzO8= +github.com/aws/smithy-go v1.13.5/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= github.com/aymanbagabas/go-osc52 v1.0.3 h1:DTwqENW7X9arYimJrPeGZcV0ln14sGMt3pHZspWD+Mg= github.com/aymanbagabas/go-osc52 v1.0.3/go.mod h1:zT8H+Rk4VSabYN90pWyugflM3ZhpTZNC7cASDfUCdT4= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= @@ -343,6 +369,8 @@ github.com/jedib0t/go-pretty/v6 v6.4.3 h1:2n9BZ0YQiXGESUSR+6FLg0WWWE80u+mIz35f0u github.com/jedib0t/go-pretty/v6 v6.4.3/go.mod h1:MgmISkTWDSFu0xOqiZ0mKNntMQ2mDgOcwOkwBEkMDJI= github.com/jessevdk/go-flags v1.5.0 h1:1jKYvbxEjfUl0fmqTCOfonvskHHXMjBySTLW4y9LFvc= github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4= +github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= +github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g= github.com/jmoiron/sqlx v1.3.5/go.mod h1:nRVWtLre0KfCLJvgxzCsLVMogSvQ1zNJtpYr2Ccp0mQ= github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= diff --git a/model/config.go b/model/config.go index b6c03e4e..85208785 100644 --- a/model/config.go +++ b/model/config.go @@ -9,11 +9,13 @@ type AuthScheme string const ( None AuthScheme = "none" Basic AuthScheme = "basic" + Oauth AuthScheme = "oauth" ) type ProxyConfig struct { AuthScheme AuthScheme `json:"auth_scheme"` BasicAuth *BasicAuth `json:"basic_auth"` + OauthAuth *OauthAuth `json:"oauth"` } type BasicAuth struct { @@ -25,12 +27,19 @@ type AuthUser struct { Password string `json:"password"` } +type OauthAuth struct { + Provider string `json:"provider"` + EmailDomains []string `json:"email_domains"` +} + func ParseAuthScheme(authScheme string) (AuthScheme, error) { switch authScheme { case string(None): return None, nil case string(Basic): return Basic, nil + case string(Oauth): + return Oauth, nil default: return None, errors.Errorf("unknown auth scheme '%v'", authScheme) } diff --git a/rest_client_zrok/share/oauth_authenticate_parameters.go b/rest_client_zrok/share/oauth_authenticate_parameters.go new file mode 100644 index 00000000..284d9007 --- /dev/null +++ b/rest_client_zrok/share/oauth_authenticate_parameters.go @@ -0,0 +1,177 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package share + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewOauthAuthenticateParams creates a new OauthAuthenticateParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewOauthAuthenticateParams() *OauthAuthenticateParams { + return &OauthAuthenticateParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewOauthAuthenticateParamsWithTimeout creates a new OauthAuthenticateParams object +// with the ability to set a timeout on a request. +func NewOauthAuthenticateParamsWithTimeout(timeout time.Duration) *OauthAuthenticateParams { + return &OauthAuthenticateParams{ + timeout: timeout, + } +} + +// NewOauthAuthenticateParamsWithContext creates a new OauthAuthenticateParams object +// with the ability to set a context for a request. +func NewOauthAuthenticateParamsWithContext(ctx context.Context) *OauthAuthenticateParams { + return &OauthAuthenticateParams{ + Context: ctx, + } +} + +// NewOauthAuthenticateParamsWithHTTPClient creates a new OauthAuthenticateParams object +// with the ability to set a custom HTTPClient for a request. +func NewOauthAuthenticateParamsWithHTTPClient(client *http.Client) *OauthAuthenticateParams { + return &OauthAuthenticateParams{ + HTTPClient: client, + } +} + +/* +OauthAuthenticateParams contains all the parameters to send to the API endpoint + + for the oauth authenticate operation. + + Typically these are written to a http.Request. +*/ +type OauthAuthenticateParams struct { + + // Code. + Code string + + // State. + State string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the oauth authenticate params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *OauthAuthenticateParams) WithDefaults() *OauthAuthenticateParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the oauth authenticate params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *OauthAuthenticateParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the oauth authenticate params +func (o *OauthAuthenticateParams) WithTimeout(timeout time.Duration) *OauthAuthenticateParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the oauth authenticate params +func (o *OauthAuthenticateParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the oauth authenticate params +func (o *OauthAuthenticateParams) WithContext(ctx context.Context) *OauthAuthenticateParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the oauth authenticate params +func (o *OauthAuthenticateParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the oauth authenticate params +func (o *OauthAuthenticateParams) WithHTTPClient(client *http.Client) *OauthAuthenticateParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the oauth authenticate params +func (o *OauthAuthenticateParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithCode adds the code to the oauth authenticate params +func (o *OauthAuthenticateParams) WithCode(code string) *OauthAuthenticateParams { + o.SetCode(code) + return o +} + +// SetCode adds the code to the oauth authenticate params +func (o *OauthAuthenticateParams) SetCode(code string) { + o.Code = code +} + +// WithState adds the state to the oauth authenticate params +func (o *OauthAuthenticateParams) WithState(state string) *OauthAuthenticateParams { + o.SetState(state) + return o +} + +// SetState adds the state to the oauth authenticate params +func (o *OauthAuthenticateParams) SetState(state string) { + o.State = state +} + +// WriteToRequest writes these params to a swagger request +func (o *OauthAuthenticateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // query param code + qrCode := o.Code + qCode := qrCode + if qCode != "" { + + if err := r.SetQueryParam("code", qCode); err != nil { + return err + } + } + + // query param state + qrState := o.State + qState := qrState + if qState != "" { + + if err := r.SetQueryParam("state", qState); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/rest_client_zrok/share/oauth_authenticate_responses.go b/rest_client_zrok/share/oauth_authenticate_responses.go new file mode 100644 index 00000000..8d89219b --- /dev/null +++ b/rest_client_zrok/share/oauth_authenticate_responses.go @@ -0,0 +1,83 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package share + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// OauthAuthenticateReader is a Reader for the OauthAuthenticate structure. +type OauthAuthenticateReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *OauthAuthenticateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewOauthAuthenticateOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewOauthAuthenticateOK creates a OauthAuthenticateOK with default headers values +func NewOauthAuthenticateOK() *OauthAuthenticateOK { + return &OauthAuthenticateOK{} +} + +/* +OauthAuthenticateOK describes a response with status code 200, with default header values. + +testing +*/ +type OauthAuthenticateOK struct { +} + +// IsSuccess returns true when this oauth authenticate o k response has a 2xx status code +func (o *OauthAuthenticateOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this oauth authenticate o k response has a 3xx status code +func (o *OauthAuthenticateOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this oauth authenticate o k response has a 4xx status code +func (o *OauthAuthenticateOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this oauth authenticate o k response has a 5xx status code +func (o *OauthAuthenticateOK) IsServerError() bool { + return false +} + +// IsCode returns true when this oauth authenticate o k response a status code equal to that given +func (o *OauthAuthenticateOK) IsCode(code int) bool { + return code == 200 +} + +func (o *OauthAuthenticateOK) Error() string { + return fmt.Sprintf("[GET /oauth/authorize][%d] oauthAuthenticateOK ", 200) +} + +func (o *OauthAuthenticateOK) String() string { + return fmt.Sprintf("[GET /oauth/authorize][%d] oauthAuthenticateOK ", 200) +} + +func (o *OauthAuthenticateOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/rest_client_zrok/share/share_client.go b/rest_client_zrok/share/share_client.go index 1f992f99..96683a93 100644 --- a/rest_client_zrok/share/share_client.go +++ b/rest_client_zrok/share/share_client.go @@ -32,6 +32,8 @@ type ClientOption func(*runtime.ClientOperation) type ClientService interface { Access(params *AccessParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*AccessCreated, error) + OauthAuthenticate(params *OauthAuthenticateParams, opts ...ClientOption) (*OauthAuthenticateOK, error) + Share(params *ShareParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ShareCreated, error) Unaccess(params *UnaccessParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UnaccessOK, error) @@ -82,6 +84,44 @@ func (a *Client) Access(params *AccessParams, authInfo runtime.ClientAuthInfoWri panic(msg) } +/* +OauthAuthenticate oauth authenticate API +*/ +func (a *Client) OauthAuthenticate(params *OauthAuthenticateParams, opts ...ClientOption) (*OauthAuthenticateOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewOauthAuthenticateParams() + } + op := &runtime.ClientOperation{ + ID: "oauthAuthenticate", + Method: "GET", + PathPattern: "/oauth/authorize", + ProducesMediaTypes: []string{"application/zrok.v1+json"}, + ConsumesMediaTypes: []string{"application/zrok.v1+json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &OauthAuthenticateReader{formats: a.formats}, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*OauthAuthenticateOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for oauthAuthenticate: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + /* Share share API */ diff --git a/rest_client_zrok/share/share_responses.go b/rest_client_zrok/share/share_responses.go index 23b4b180..58e2b889 100644 --- a/rest_client_zrok/share/share_responses.go +++ b/rest_client_zrok/share/share_responses.go @@ -41,6 +41,12 @@ func (o *ShareReader) ReadResponse(response runtime.ClientResponse, consumer run return nil, err } return nil, result + case 422: + result := NewShareUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result case 500: result := NewShareInternalServerError() if err := result.readResponse(response, consumer, o.formats); err != nil { @@ -217,6 +223,57 @@ func (o *ShareNotFound) readResponse(response runtime.ClientResponse, consumer r return nil } +// NewShareUnprocessableEntity creates a ShareUnprocessableEntity with default headers values +func NewShareUnprocessableEntity() *ShareUnprocessableEntity { + return &ShareUnprocessableEntity{} +} + +/* +ShareUnprocessableEntity describes a response with status code 422, with default header values. + +Unprocessable entity. Incorrect enum? +*/ +type ShareUnprocessableEntity struct { +} + +// IsSuccess returns true when this share unprocessable entity response has a 2xx status code +func (o *ShareUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this share unprocessable entity response has a 3xx status code +func (o *ShareUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this share unprocessable entity response has a 4xx status code +func (o *ShareUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this share unprocessable entity response has a 5xx status code +func (o *ShareUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this share unprocessable entity response a status code equal to that given +func (o *ShareUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +func (o *ShareUnprocessableEntity) Error() string { + return fmt.Sprintf("[POST /share][%d] shareUnprocessableEntity ", 422) +} + +func (o *ShareUnprocessableEntity) String() string { + return fmt.Sprintf("[POST /share][%d] shareUnprocessableEntity ", 422) +} + +func (o *ShareUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + // NewShareInternalServerError creates a ShareInternalServerError with default headers values func NewShareInternalServerError() *ShareInternalServerError { return &ShareInternalServerError{} diff --git a/rest_model_zrok/share_request.go b/rest_model_zrok/share_request.go index 657fe3e1..d935697d 100644 --- a/rest_model_zrok/share_request.go +++ b/rest_model_zrok/share_request.go @@ -40,6 +40,13 @@ type ShareRequest struct { // frontend selection FrontendSelection []string `json:"frontendSelection"` + // oauth email domains + OauthEmailDomains []string `json:"oauthEmailDomains"` + + // oauth provider + // Enum: [amazon] + OauthProvider string `json:"oauthProvider,omitempty"` + // reserved Reserved bool `json:"reserved,omitempty"` @@ -60,6 +67,10 @@ func (m *ShareRequest) Validate(formats strfmt.Registry) error { res = append(res, err) } + if err := m.validateOauthProvider(formats); err != nil { + res = append(res, err) + } + if err := m.validateShareMode(formats); err != nil { res = append(res, err) } @@ -144,6 +155,45 @@ func (m *ShareRequest) validateBackendMode(formats strfmt.Registry) error { return nil } +var shareRequestTypeOauthProviderPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["amazon"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + shareRequestTypeOauthProviderPropEnum = append(shareRequestTypeOauthProviderPropEnum, v) + } +} + +const ( + + // ShareRequestOauthProviderAmazon captures enum value "amazon" + ShareRequestOauthProviderAmazon string = "amazon" +) + +// prop value enum +func (m *ShareRequest) validateOauthProviderEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, shareRequestTypeOauthProviderPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *ShareRequest) validateOauthProvider(formats strfmt.Registry) error { + if swag.IsZero(m.OauthProvider) { // not required + return nil + } + + // value enum + if err := m.validateOauthProviderEnum("oauthProvider", "body", m.OauthProvider); err != nil { + return err + } + + return nil +} + var shareRequestTypeShareModePropEnum []interface{} func init() { diff --git a/rest_server_zrok/embedded_spec.go b/rest_server_zrok/embedded_spec.go index 05879de2..ec5411ea 100644 --- a/rest_server_zrok/embedded_spec.go +++ b/rest_server_zrok/embedded_spec.go @@ -702,6 +702,33 @@ func init() { } } }, + "/oauth/authorize": { + "get": { + "tags": [ + "share" + ], + "operationId": "oauthAuthenticate", + "parameters": [ + { + "type": "string", + "name": "state", + "in": "query", + "required": true + }, + { + "type": "string", + "name": "code", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "testing" + } + } + } + }, "/overview": { "get": { "security": [ @@ -865,6 +892,9 @@ func init() { "404": { "description": "not found" }, + "422": { + "description": "Unprocessable entity. Incorrect enum?" + }, "500": { "description": "internal server error", "schema": { @@ -1483,6 +1513,18 @@ func init() { "type": "string" } }, + "oauthEmailDomains": { + "type": "array", + "items": { + "type": "string" + } + }, + "oauthProvider": { + "type": "string", + "enum": [ + "amazon" + ] + }, "reserved": { "type": "boolean" }, @@ -2298,6 +2340,33 @@ func init() { } } }, + "/oauth/authorize": { + "get": { + "tags": [ + "share" + ], + "operationId": "oauthAuthenticate", + "parameters": [ + { + "type": "string", + "name": "state", + "in": "query", + "required": true + }, + { + "type": "string", + "name": "code", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "testing" + } + } + } + }, "/overview": { "get": { "security": [ @@ -2461,6 +2530,9 @@ func init() { "404": { "description": "not found" }, + "422": { + "description": "Unprocessable entity. Incorrect enum?" + }, "500": { "description": "internal server error", "schema": { @@ -3079,6 +3151,18 @@ func init() { "type": "string" } }, + "oauthEmailDomains": { + "type": "array", + "items": { + "type": "string" + } + }, + "oauthProvider": { + "type": "string", + "enum": [ + "amazon" + ] + }, "reserved": { "type": "boolean" }, diff --git a/rest_server_zrok/operations/share/oauth_authenticate.go b/rest_server_zrok/operations/share/oauth_authenticate.go new file mode 100644 index 00000000..8384df4b --- /dev/null +++ b/rest_server_zrok/operations/share/oauth_authenticate.go @@ -0,0 +1,56 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package share + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// OauthAuthenticateHandlerFunc turns a function with the right signature into a oauth authenticate handler +type OauthAuthenticateHandlerFunc func(OauthAuthenticateParams) middleware.Responder + +// Handle executing the request and returning a response +func (fn OauthAuthenticateHandlerFunc) Handle(params OauthAuthenticateParams) middleware.Responder { + return fn(params) +} + +// OauthAuthenticateHandler interface for that can handle valid oauth authenticate params +type OauthAuthenticateHandler interface { + Handle(OauthAuthenticateParams) middleware.Responder +} + +// NewOauthAuthenticate creates a new http.Handler for the oauth authenticate operation +func NewOauthAuthenticate(ctx *middleware.Context, handler OauthAuthenticateHandler) *OauthAuthenticate { + return &OauthAuthenticate{Context: ctx, Handler: handler} +} + +/* + OauthAuthenticate swagger:route GET /oauth/authorize share oauthAuthenticate + +OauthAuthenticate oauth authenticate API +*/ +type OauthAuthenticate struct { + Context *middleware.Context + Handler OauthAuthenticateHandler +} + +func (o *OauthAuthenticate) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + *r = *rCtx + } + var Params = NewOauthAuthenticateParams() + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params) // actually handle the request + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/rest_server_zrok/operations/share/oauth_authenticate_parameters.go b/rest_server_zrok/operations/share/oauth_authenticate_parameters.go new file mode 100644 index 00000000..ff9bb2b5 --- /dev/null +++ b/rest_server_zrok/operations/share/oauth_authenticate_parameters.go @@ -0,0 +1,113 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package share + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewOauthAuthenticateParams creates a new OauthAuthenticateParams object +// +// There are no default values defined in the spec. +func NewOauthAuthenticateParams() OauthAuthenticateParams { + + return OauthAuthenticateParams{} +} + +// OauthAuthenticateParams contains all the bound params for the oauth authenticate operation +// typically these are obtained from a http.Request +// +// swagger:parameters oauthAuthenticate +type OauthAuthenticateParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /* + Required: true + In: query + */ + Code string + /* + Required: true + In: query + */ + State string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewOauthAuthenticateParams() beforehand. +func (o *OauthAuthenticateParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qCode, qhkCode, _ := qs.GetOK("code") + if err := o.bindCode(qCode, qhkCode, route.Formats); err != nil { + res = append(res, err) + } + + qState, qhkState, _ := qs.GetOK("state") + if err := o.bindState(qState, qhkState, route.Formats); err != nil { + res = append(res, err) + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindCode binds and validates parameter Code from query. +func (o *OauthAuthenticateParams) bindCode(rawData []string, hasKey bool, formats strfmt.Registry) error { + if !hasKey { + return errors.Required("code", "query", rawData) + } + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // AllowEmptyValue: false + + if err := validate.RequiredString("code", "query", raw); err != nil { + return err + } + o.Code = raw + + return nil +} + +// bindState binds and validates parameter State from query. +func (o *OauthAuthenticateParams) bindState(rawData []string, hasKey bool, formats strfmt.Registry) error { + if !hasKey { + return errors.Required("state", "query", rawData) + } + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // AllowEmptyValue: false + + if err := validate.RequiredString("state", "query", raw); err != nil { + return err + } + o.State = raw + + return nil +} diff --git a/rest_server_zrok/operations/share/oauth_authenticate_responses.go b/rest_server_zrok/operations/share/oauth_authenticate_responses.go new file mode 100644 index 00000000..f0f9cc7e --- /dev/null +++ b/rest_server_zrok/operations/share/oauth_authenticate_responses.go @@ -0,0 +1,37 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package share + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" +) + +// OauthAuthenticateOKCode is the HTTP code returned for type OauthAuthenticateOK +const OauthAuthenticateOKCode int = 200 + +/* +OauthAuthenticateOK testing + +swagger:response oauthAuthenticateOK +*/ +type OauthAuthenticateOK struct { +} + +// NewOauthAuthenticateOK creates OauthAuthenticateOK with default headers values +func NewOauthAuthenticateOK() *OauthAuthenticateOK { + + return &OauthAuthenticateOK{} +} + +// WriteResponse to the client +func (o *OauthAuthenticateOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(200) +} diff --git a/rest_server_zrok/operations/share/oauth_authenticate_urlbuilder.go b/rest_server_zrok/operations/share/oauth_authenticate_urlbuilder.go new file mode 100644 index 00000000..0bb5335b --- /dev/null +++ b/rest_server_zrok/operations/share/oauth_authenticate_urlbuilder.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package share + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// OauthAuthenticateURL generates an URL for the oauth authenticate operation +type OauthAuthenticateURL struct { + Code string + State string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *OauthAuthenticateURL) WithBasePath(bp string) *OauthAuthenticateURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *OauthAuthenticateURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *OauthAuthenticateURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/oauth/authorize" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + codeQ := o.Code + if codeQ != "" { + qs.Set("code", codeQ) + } + + stateQ := o.State + if stateQ != "" { + qs.Set("state", stateQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *OauthAuthenticateURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *OauthAuthenticateURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *OauthAuthenticateURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on OauthAuthenticateURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on OauthAuthenticateURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *OauthAuthenticateURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/rest_server_zrok/operations/share/share_responses.go b/rest_server_zrok/operations/share/share_responses.go index 556210b6..0dc208fa 100644 --- a/rest_server_zrok/operations/share/share_responses.go +++ b/rest_server_zrok/operations/share/share_responses.go @@ -108,6 +108,31 @@ func (o *ShareNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.P rw.WriteHeader(404) } +// ShareUnprocessableEntityCode is the HTTP code returned for type ShareUnprocessableEntity +const ShareUnprocessableEntityCode int = 422 + +/* +ShareUnprocessableEntity Unprocessable entity. Incorrect enum? + +swagger:response shareUnprocessableEntity +*/ +type ShareUnprocessableEntity struct { +} + +// NewShareUnprocessableEntity creates ShareUnprocessableEntity with default headers values +func NewShareUnprocessableEntity() *ShareUnprocessableEntity { + + return &ShareUnprocessableEntity{} +} + +// WriteResponse to the client +func (o *ShareUnprocessableEntity) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(422) +} + // ShareInternalServerErrorCode is the HTTP code returned for type ShareInternalServerError const ShareInternalServerErrorCode int = 500 diff --git a/rest_server_zrok/operations/zrok_api.go b/rest_server_zrok/operations/zrok_api.go index 158e03c3..3ac58e9d 100644 --- a/rest_server_zrok/operations/zrok_api.go +++ b/rest_server_zrok/operations/zrok_api.go @@ -103,6 +103,9 @@ func NewZrokAPI(spec *loads.Document) *ZrokAPI { AccountLoginHandler: account.LoginHandlerFunc(func(params account.LoginParams) middleware.Responder { return middleware.NotImplemented("operation account.Login has not yet been implemented") }), + ShareOauthAuthenticateHandler: share.OauthAuthenticateHandlerFunc(func(params share.OauthAuthenticateParams) middleware.Responder { + return middleware.NotImplemented("operation share.OauthAuthenticate has not yet been implemented") + }), MetadataOverviewHandler: metadata.OverviewHandlerFunc(func(params metadata.OverviewParams, principal *rest_model_zrok.Principal) middleware.Responder { return middleware.NotImplemented("operation metadata.Overview has not yet been implemented") }), @@ -222,6 +225,8 @@ type ZrokAPI struct { AdminListFrontendsHandler admin.ListFrontendsHandler // AccountLoginHandler sets the operation handler for the login operation AccountLoginHandler account.LoginHandler + // ShareOauthAuthenticateHandler sets the operation handler for the oauth authenticate operation + ShareOauthAuthenticateHandler share.OauthAuthenticateHandler // MetadataOverviewHandler sets the operation handler for the overview operation MetadataOverviewHandler metadata.OverviewHandler // AccountRegisterHandler sets the operation handler for the register operation @@ -379,6 +384,9 @@ func (o *ZrokAPI) Validate() error { if o.AccountLoginHandler == nil { unregistered = append(unregistered, "account.LoginHandler") } + if o.ShareOauthAuthenticateHandler == nil { + unregistered = append(unregistered, "share.OauthAuthenticateHandler") + } if o.MetadataOverviewHandler == nil { unregistered = append(unregistered, "metadata.OverviewHandler") } @@ -586,6 +594,10 @@ func (o *ZrokAPI) initHandlerCache() { if o.handlers["GET"] == nil { o.handlers["GET"] = make(map[string]http.Handler) } + o.handlers["GET"]["/oauth/authorize"] = share.NewOauthAuthenticate(o.context, o.ShareOauthAuthenticateHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } o.handlers["GET"]["/overview"] = metadata.NewOverview(o.context, o.MetadataOverviewHandler) if o.handlers["POST"] == nil { o.handlers["POST"] = make(map[string]http.Handler) diff --git a/specs/zrok.yml b/specs/zrok.yml index c71462ab..9accf12d 100644 --- a/specs/zrok.yml +++ b/specs/zrok.yml @@ -556,6 +556,25 @@ paths: 500: description: internal server error + /oauth/authorize: + get: + tags: + - share + operationId: oauthAuthenticate + parameters: + - name: state + in: query + type: string + required: true + - name: code + in: query + type: string + required: true + responses: + 200: + description: testing + + /share: post: tags: @@ -577,6 +596,8 @@ paths: description: unauthorized 404: description: not found + 422: + description: Unprocessable entity. Incorrect enum? 500: description: internal server error schema: @@ -978,6 +999,13 @@ definitions: type: array items: $ref: "#/definitions/authUser" + oauthProvider: + type: string + enum: [amazon] + oauthEmailDomains: + type: array + items: + type: string reserved: type: boolean diff --git a/ui/src/api/share.js b/ui/src/api/share.js index 3bf46930..021355ef 100644 --- a/ui/src/api/share.js +++ b/ui/src/api/share.js @@ -17,6 +17,21 @@ export function access(options) { return gateway.request(accessOperation, parameters) } +/** + * @param {string} state + * @param {string} code + * @return {Promise} testing + */ +export function oauthAuthenticate(state, code) { + const parameters = { + query: { + state, + code + } + } + return gateway.request(oauthAuthenticateOperation, parameters) +} + /** * @param {object} options Optional options * @param {module:types.shareRequest} [options.body] @@ -88,6 +103,11 @@ const accessOperation = { ] } +const oauthAuthenticateOperation = { + path: '/oauth/authorize', + method: 'get' +} + const shareOperation = { path: '/share', contentTypes: ['application/zrok.v1+json'], diff --git a/ui/src/api/types.js b/ui/src/api/types.js index c4e6b95b..d3276391 100644 --- a/ui/src/api/types.js +++ b/ui/src/api/types.js @@ -253,6 +253,8 @@ * @property {string} backendProxyEndpoint * @property {string} authScheme * @property {module:types.authUser[]} authUsers + * @property {string} oauthProvider + * @property {string[]} oauthEmailDomains * @property {boolean} reserved */