diff --git a/Makefile b/Makefile index 1765fead..5b1f0289 100644 --- a/Makefile +++ b/Makefile @@ -4,26 +4,23 @@ ROOT=$(realpath $(dir $(lastword $(MAKEFILE_LIST)))) OS := $(shell uname -s) -lint: +lint: ## Lint check project which golangci-lint || (go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.54.0) golangci-lint run --config=$(ROOT)/.golangci.yml $(ROOT)/... -test: +test: ## Test check project go test ./... -docker-test-up: +docker-test-up: ## Start docker test environment docker compose -f $(ROOT)/deployment/test/docker-compose.yml up -d -docker-test-down: +docker-test-down: ## Stop docker test environment docker compose -f $(ROOT)/deployment/test/docker-compose.yml down -docker-local-up: +docker-local-up: ## Start docker local environment sh -c "$(ROOT)/deployment/local/docker-compose.bash up -d" -logs: - docker compose -f $(ROOT)/deployment/test/docker-compose.yml logs - -format: +format: ## Format project @which gofumpt || (go install mvdan.cc/gofumpt@latest) @gofumpt -l -w $(ROOT) @which gci || (go install github.com/daixiang0/gci@latest) @@ -31,7 +28,7 @@ format: @which golangci-lint || (go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.54.0) @golangci-lint run --fix -protobuf: +protobuf: ## Generate protobuf ifneq (,$(findstring NT,$(OS))) protoc --go-grpc_out=contract/go/ --go-grpc_opt=paths=source_relative --go_out=contract/go --go_opt=paths=source_relative --proto_path=./contract/protobuf/ contract/protobuf/event/event.proto protoc --go-grpc_out=contract/go/ --go-grpc_opt=paths=source_relative --go_out=contract/go --go_opt=paths=source_relative --proto_path=./contract/protobuf/ contract/protobuf/task/task.proto @@ -44,12 +41,16 @@ else find contract/protobuf/ -name '*.proto' | xargs -I {} protoc --go-grpc_out=contract/go/ --go-grpc_opt=paths=source_relative --go_out=contract/go --go_opt=paths=source_relative --proto_path=contract/protobuf/ {} endif -swagger-gen: +swagger-gen: ## Generate swagger @which swag || (go install github.com/swaggo/swag/cmd/swag@latest) swag fmt swag init -g ../cmd/manager/main.go -d manager/ --parseDependency --output doc/swagger --instanceName manager swag init -g ../cmd/source/main.go -d source/ --parseDependency --output doc/swagger --instanceName source docker compose --env-file ./deployment/local/.env -f ./deployment/local/services/swagger.yml restart swagger -drop-manager-db: - docker compose --env-file ./deployment/local/.env -f ./deployment/local/services/scylladb.yml exec scylladb cqlsh -e "DROP KEYSPACE manager;" \ No newline at end of file +drop-manager-db: ## Drop manager db + docker compose --env-file ./deployment/local/.env -f ./deployment/local/services/scylladb.yml exec scylladb cqlsh -e "DROP KEYSPACE manager;" + + +help: ## Display this help + @awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m\033[0m\n"} /^[.a-zA-Z_-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST) \ No newline at end of file diff --git a/cli/api/source/create.go b/cli/api/source/create.go new file mode 100644 index 00000000..a4bd4b1d --- /dev/null +++ b/cli/api/source/create.go @@ -0,0 +1,21 @@ +package source + +import ( + "net/http" + + "github.com/ormushq/ormus/cli/api/types" +) + +func (c Client) Create(name, description, projectID string) types.Request { + return types.Request{ + Path: "sources", + Method: http.MethodPost, + AuthorizationRequired: true, + Header: nil, + Body: map[string]string{ + "name": name, + "description": description, + "project_id": projectID, + }, + } +} diff --git a/cli/api/source/delete.go b/cli/api/source/delete.go new file mode 100644 index 00000000..3c46d2a6 --- /dev/null +++ b/cli/api/source/delete.go @@ -0,0 +1,18 @@ +package source + +import ( + "net/http" + + "github.com/ormushq/ormus/cli/api/types" +) + +func (c Client) Delete(sourceID string) types.Request { + return types.Request{ + Path: "sources/%s", + Method: http.MethodDelete, + AuthorizationRequired: true, + URLParams: []any{ + sourceID, + }, + } +} diff --git a/cli/api/source/disable.go b/cli/api/source/disable.go new file mode 100644 index 00000000..1a994450 --- /dev/null +++ b/cli/api/source/disable.go @@ -0,0 +1,19 @@ +package source + +import ( + "net/http" + + "github.com/ormushq/ormus/cli/api/types" +) + +func (c Client) Disable(sourceID string) types.Request { + return types.Request{ + Path: "sources/%s/disable", + Method: http.MethodGet, + AuthorizationRequired: true, + Header: nil, + URLParams: []any{ + sourceID, + }, + } +} diff --git a/cli/api/source/enable.go b/cli/api/source/enable.go new file mode 100644 index 00000000..63ea0bf0 --- /dev/null +++ b/cli/api/source/enable.go @@ -0,0 +1,19 @@ +package source + +import ( + "net/http" + + "github.com/ormushq/ormus/cli/api/types" +) + +func (c Client) Enable(sourceID string) types.Request { + return types.Request{ + Path: "sources/%s/enable", + Method: http.MethodGet, + AuthorizationRequired: true, + Header: nil, + URLParams: []any{ + sourceID, + }, + } +} diff --git a/cli/api/source/list.go b/cli/api/source/list.go new file mode 100644 index 00000000..80854767 --- /dev/null +++ b/cli/api/source/list.go @@ -0,0 +1,19 @@ +package source + +import ( + "net/http" + + "github.com/ormushq/ormus/cli/api/types" +) + +func (c Client) List(perPage, lastTokenID string) types.Request { + return types.Request{ + Path: "sources", + Method: http.MethodGet, + AuthorizationRequired: true, + QueryParams: map[string]string{ + "last_token_id": lastTokenID, + "per_page": perPage, + }, + } +} diff --git a/cli/api/source/rotatewritekey.go b/cli/api/source/rotatewritekey.go new file mode 100644 index 00000000..b27ba0f4 --- /dev/null +++ b/cli/api/source/rotatewritekey.go @@ -0,0 +1,19 @@ +package source + +import ( + "net/http" + + "github.com/ormushq/ormus/cli/api/types" +) + +func (c Client) RotateWriteKey(sourceID string) types.Request { + return types.Request{ + Path: "sources/%s/rotate-write-key", + Method: http.MethodGet, + AuthorizationRequired: true, + Header: nil, + URLParams: []any{ + sourceID, + }, + } +} diff --git a/cli/api/source/show.go b/cli/api/source/show.go new file mode 100644 index 00000000..3300fd27 --- /dev/null +++ b/cli/api/source/show.go @@ -0,0 +1,19 @@ +package source + +import ( + "net/http" + + "github.com/ormushq/ormus/cli/api/types" +) + +func (c Client) Show(sourceID string) types.Request { + return types.Request{ + Path: "sources/%s", + Method: http.MethodGet, + AuthorizationRequired: true, + Header: nil, + URLParams: []any{ + sourceID, + }, + } +} diff --git a/cli/api/source/update.go b/cli/api/source/update.go new file mode 100644 index 00000000..8e9e54af --- /dev/null +++ b/cli/api/source/update.go @@ -0,0 +1,23 @@ +package source + +import ( + "net/http" + + "github.com/ormushq/ormus/cli/api/types" +) + +func (c Client) Update(sourceID, name, description string) types.Request { + return types.Request{ + Path: "sources/%s", + Method: http.MethodPost, + AuthorizationRequired: true, + Header: nil, + URLParams: []any{ + sourceID, + }, + Body: map[string]string{ + "name": name, + "description": description, + }, + } +} diff --git a/cli/cmd/source/create.go b/cli/cmd/source/create.go index 5a176a5f..44a19aa1 100644 --- a/cli/cmd/source/create.go +++ b/cli/cmd/source/create.go @@ -5,7 +5,11 @@ package source import ( "fmt" + "io" + "log" + "net/http" + "github.com/ormushq/ormus/cli/cmd" "github.com/spf13/cobra" ) @@ -13,15 +17,57 @@ import ( var createCmd = &cobra.Command{ Use: "create", Short: "Create a new source within a project.", - Long: `ormus source create --project-id --name --type `, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("create called") + Long: `ormus source create --project-id --name --description `, + Run: func(cmdCobra *cobra.Command, args []string) { + projectID, err := cmdCobra.Flags().GetString("project-id") + if err != nil { + fmt.Println("error on get project-id flag", err) + + return + } + name, err := cmdCobra.Flags().GetString("name") + if err != nil { + fmt.Println("error on get name flag", err) + + return + } + + description, err := cmdCobra.Flags().GetString("description") + if err != nil { + fmt.Println("error on get description flag", err) + + return + } + + if name == "" || description == "" || projectID == "" { + fmt.Println("name and description and project id is required") + + return + } + + resp, err := cmd.Client.SendRequest(cmd.Client.Source.Create(name, description, projectID)) + if err != nil { + log.Fatal(err) + } + j, err := io.ReadAll(resp.Body) + if err != nil { + log.Fatal(err) + } + + if resp.StatusCode != http.StatusCreated { + log.Fatal(fmt.Errorf("status not Created ,status code %d, body: %s", resp.StatusCode, j)) + } + + fmt.Printf("success response : \n%s\n", j) }, } func init() { sourceCmd.AddCommand(createCmd) + createCmd.Flags().String("name", "", "name") + createCmd.Flags().String("description", "", "description") + createCmd.Flags().String("project-id", "", "project-id") // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command diff --git a/cli/cmd/source/delete.go b/cli/cmd/source/delete.go index 89009065..38c3ab9a 100644 --- a/cli/cmd/source/delete.go +++ b/cli/cmd/source/delete.go @@ -5,7 +5,11 @@ package source import ( "fmt" + "io" + "log" + "net/http" + "github.com/ormushq/ormus/cli/cmd" "github.com/spf13/cobra" ) @@ -13,15 +17,42 @@ import ( var deleteCmd = &cobra.Command{ Use: "delete", Short: "Delete a source.", - Long: `ormus source delete --project-id --source-id `, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("delete called") + Long: `ormus source delete --source-id `, + Run: func(cmdCobra *cobra.Command, args []string) { + sourceID, err := cmdCobra.Flags().GetString("source-id") + if err != nil { + fmt.Println("error on get source id flag", err) + + return + } + + if sourceID == "" { + fmt.Println("source id is required") + + return + } + resp, err := cmd.Client.SendRequest(cmd.Client.Source.Delete(sourceID)) + if err != nil { + log.Fatal(err) + } + j, err := io.ReadAll(resp.Body) + if err != nil { + log.Fatal(err) + } + + if resp.StatusCode != http.StatusOK { + log.Fatal(fmt.Errorf("status not Ok ,status code %d, body: %s", resp.StatusCode, j)) + } + + fmt.Printf("success response : \n%s\n", j) }, } func init() { sourceCmd.AddCommand(deleteCmd) + deleteCmd.Flags().String("source-id", "", "source-id") + // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command diff --git a/cli/cmd/source/disable.go b/cli/cmd/source/disable.go index 84e61f9d..a29f2d79 100644 --- a/cli/cmd/source/disable.go +++ b/cli/cmd/source/disable.go @@ -5,7 +5,11 @@ package source import ( "fmt" + "io" + "log" + "net/http" + "github.com/ormushq/ormus/cli/cmd" "github.com/spf13/cobra" ) @@ -13,15 +17,42 @@ import ( var disableCmd = &cobra.Command{ Use: "disable", Short: "Disable a source", - Long: `ormus source disable --project-id --source-id `, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("disable called") + Long: `ormus source disable --source-id `, + Run: func(cmdCobra *cobra.Command, args []string) { + sourceID, err := cmdCobra.Flags().GetString("source-id") + if err != nil { + fmt.Println("error on get source id flag", err) + + return + } + + if sourceID == "" { + fmt.Println("source id is required") + + return + } + resp, err := cmd.Client.SendRequest(cmd.Client.Source.Disable(sourceID)) + if err != nil { + log.Fatal(err) + } + j, err := io.ReadAll(resp.Body) + if err != nil { + log.Fatal(err) + } + + if resp.StatusCode != http.StatusOK { + log.Fatal(fmt.Errorf("status not Ok ,status code %d, body: %s", resp.StatusCode, j)) + } + + fmt.Printf("success response : \n%s\n", j) }, } func init() { sourceCmd.AddCommand(disableCmd) + disableCmd.Flags().String("source-id", "", "source-id") + // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command diff --git a/cli/cmd/source/enable.go b/cli/cmd/source/enable.go index 22846fb5..78f184a3 100644 --- a/cli/cmd/source/enable.go +++ b/cli/cmd/source/enable.go @@ -5,7 +5,11 @@ package source import ( "fmt" + "io" + "log" + "net/http" + "github.com/ormushq/ormus/cli/cmd" "github.com/spf13/cobra" ) @@ -14,14 +18,41 @@ var enableCmd = &cobra.Command{ Use: "enable", Short: "Enable a source", Long: `ormus source enable --project-id --source-id `, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("enable called") + Run: func(cmdCobra *cobra.Command, args []string) { + sourceID, err := cmdCobra.Flags().GetString("source-id") + if err != nil { + fmt.Println("error on get source id flag", err) + + return + } + + if sourceID == "" { + fmt.Println("source id is required") + + return + } + resp, err := cmd.Client.SendRequest(cmd.Client.Source.Enable(sourceID)) + if err != nil { + log.Fatal(err) + } + j, err := io.ReadAll(resp.Body) + if err != nil { + log.Fatal(err) + } + + if resp.StatusCode != http.StatusOK { + log.Fatal(fmt.Errorf("status not Ok ,status code %d, body: %s", resp.StatusCode, j)) + } + + fmt.Printf("success response : \n%s\n", j) }, } func init() { sourceCmd.AddCommand(enableCmd) + enableCmd.Flags().String("source-id", "", "source-id") + // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command diff --git a/cli/cmd/source/getWriteKey.go b/cli/cmd/source/getWriteKey.go deleted file mode 100644 index 3ab96958..00000000 --- a/cli/cmd/source/getWriteKey.go +++ /dev/null @@ -1,34 +0,0 @@ -/* -Copyright © 2024 NAME HERE -*/ -package source - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -// getWriteKeyCmd represents the getWriteKey command. -var getWriteKeyCmd = &cobra.Command{ - Use: "getWriteKey", - Short: "Get write-key of a source", - Long: `ormus source get-write-key --project-id --source-id `, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("getWriteKey called") - }, -} - -func init() { - sourceCmd.AddCommand(getWriteKeyCmd) - - // Here you will define your flags and configuration settings. - - // Cobra supports Persistent Flags which will work for this command - // and all subcommands, e.g.: - // getWriteKeyCmd.PersistentFlags().String("foo", "", "A help for foo") - - // Cobra supports local flags which will only run when this command - // is called directly, e.g.: - // getWriteKeyCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") -} diff --git a/cli/cmd/source/list.go b/cli/cmd/source/list.go index 177acff7..231bcae7 100644 --- a/cli/cmd/source/list.go +++ b/cli/cmd/source/list.go @@ -5,7 +5,11 @@ package source import ( "fmt" + "io" + "log" + "net/http" + "github.com/ormushq/ormus/cli/cmd" "github.com/spf13/cobra" ) @@ -13,15 +17,45 @@ import ( var listCmd = &cobra.Command{ Use: "list", Short: "List all sources for a specific project.", - Long: `ormus source list --project-id `, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("list called") + Long: `ormus source list --last-token-id --per-page `, + Run: func(cmdCobra *cobra.Command, args []string) { + perPage, err := cmdCobra.Flags().GetString("per-page") + if err != nil { + fmt.Println("error on get per-page flag", err) + + return + } + + lastTokenID, err := cmdCobra.Flags().GetString("last-token-id") + if err != nil { + fmt.Println("error on get last-token-id flag", err) + + return + } + + resp, err := cmd.Client.SendRequest(cmd.Client.Source.List(perPage, lastTokenID)) + if err != nil { + log.Fatal(err) + } + j, err := io.ReadAll(resp.Body) + if err != nil { + log.Fatal(err) + } + + if resp.StatusCode != http.StatusOK { + log.Fatal(fmt.Errorf("status not OK ,status code %d, body: %s", resp.StatusCode, j)) + } + + fmt.Printf("success response : \n%s\n", j) }, } func init() { sourceCmd.AddCommand(listCmd) + listCmd.Flags().String("per-page", "10", "per-page") + listCmd.Flags().String("last-token-id", "", "last-token-id") + // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command diff --git a/cli/cmd/source/rotateWriteKey.go b/cli/cmd/source/rotateWriteKey.go deleted file mode 100644 index 860966c7..00000000 --- a/cli/cmd/source/rotateWriteKey.go +++ /dev/null @@ -1,34 +0,0 @@ -/* -Copyright © 2024 NAME HERE -*/ -package source - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -// rotateWriteKeyCmd represents the rotateWriteKey command. -var rotateWriteKeyCmd = &cobra.Command{ - Use: "rotateWriteKey", - Short: "Rotate write-key for a source", - Long: `ormus source rotate-write-key --project-id --source-id `, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("rotateWriteKey called") - }, -} - -func init() { - sourceCmd.AddCommand(rotateWriteKeyCmd) - - // Here you will define your flags and configuration settings. - - // Cobra supports Persistent Flags which will work for this command - // and all subcommands, e.g.: - // rotateWriteKeyCmd.PersistentFlags().String("foo", "", "A help for foo") - - // Cobra supports local flags which will only run when this command - // is called directly, e.g.: - // rotateWriteKeyCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") -} diff --git a/cli/cmd/source/rotatewritekey.go b/cli/cmd/source/rotatewritekey.go new file mode 100644 index 00000000..28793231 --- /dev/null +++ b/cli/cmd/source/rotatewritekey.go @@ -0,0 +1,64 @@ +/* +Copyright © 2024 NAME HERE +*/ +package source + +import ( + "fmt" + "io" + "log" + "net/http" + + "github.com/ormushq/ormus/cli/cmd" + "github.com/spf13/cobra" +) + +// rotateWriteKeyCmd represents the rotateWriteKey command. +var rotatewritekeyCmd = &cobra.Command{ + Use: "rotate-write-key", + Short: "Rotate write-key for a source", + Long: `ormus source rotate-write-key --source-id `, + Run: func(cmdCobra *cobra.Command, args []string) { + sourceID, err := cmdCobra.Flags().GetString("source-id") + if err != nil { + fmt.Println("error on get source id flag", err) + + return + } + + if sourceID == "" { + fmt.Println("source id is required") + + return + } + resp, err := cmd.Client.SendRequest(cmd.Client.Source.RotateWriteKey(sourceID)) + if err != nil { + log.Fatal(err) + } + j, err := io.ReadAll(resp.Body) + if err != nil { + log.Fatal(err) + } + + if resp.StatusCode != http.StatusOK { + log.Fatal(fmt.Errorf("status not Ok ,status code %d, body: %s", resp.StatusCode, j)) + } + + fmt.Printf("success response : \n%s\n", j) + }, +} + +func init() { + sourceCmd.AddCommand(rotatewritekeyCmd) + rotatewritekeyCmd.Flags().String("source-id", "", "source-id") + + // Here you will define your flags and configuration settings. + + // Cobra supports Persistent Flags which will work for this command + // and all subcommands, e.g.: + // rotateWriteKeyCmd.PersistentFlags().String("foo", "", "A help for foo") + + // Cobra supports local flags which will only run when this command + // is called directly, e.g.: + // rotateWriteKeyCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") +} diff --git a/cli/cmd/source/show.go b/cli/cmd/source/show.go index 684ccf5e..a98f0111 100644 --- a/cli/cmd/source/show.go +++ b/cli/cmd/source/show.go @@ -5,7 +5,11 @@ package source import ( "fmt" + "io" + "log" + "net/http" + "github.com/ormushq/ormus/cli/cmd" "github.com/spf13/cobra" ) @@ -13,15 +17,42 @@ import ( var showCmd = &cobra.Command{ Use: "show", Short: "Show details of a specific source.", - Long: `ormus source show --project-id --source-id `, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("show called") + Long: `ormus source show --source-id `, + Run: func(cmdCobra *cobra.Command, args []string) { + sourceID, err := cmdCobra.Flags().GetString("source-id") + if err != nil { + fmt.Println("error on get source id flag", err) + + return + } + + if sourceID == "" { + fmt.Println("source id is required") + + return + } + resp, err := cmd.Client.SendRequest(cmd.Client.Source.Show(sourceID)) + if err != nil { + log.Fatal(err) + } + j, err := io.ReadAll(resp.Body) + if err != nil { + log.Fatal(err) + } + + if resp.StatusCode != http.StatusOK { + log.Fatal(fmt.Errorf("status not Ok ,status code %d, body: %s", resp.StatusCode, j)) + } + + fmt.Printf("success response : \n%s\n", j) }, } func init() { sourceCmd.AddCommand(showCmd) + showCmd.Flags().String("source-id", "", "source-id") + // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command diff --git a/cli/cmd/source/update.go b/cli/cmd/source/update.go index 0fc7e0ec..806c530a 100644 --- a/cli/cmd/source/update.go +++ b/cli/cmd/source/update.go @@ -5,7 +5,11 @@ package source import ( "fmt" + "io" + "log" + "net/http" + "github.com/ormushq/ormus/cli/cmd" "github.com/spf13/cobra" ) @@ -13,15 +17,58 @@ import ( var updateCmd = &cobra.Command{ Use: "update", Short: "Update a source's details.", - Long: `ormus source update --project-id --source-id --name `, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("update called") + Long: `ormus source update --source-id --name --description `, + Run: func(cmdCobra *cobra.Command, args []string) { + name, err := cmdCobra.Flags().GetString("name") + if err != nil { + fmt.Println("error on get name flag", err) + + return + } + + description, err := cmdCobra.Flags().GetString("description") + if err != nil { + fmt.Println("error on get description flag", err) + + return + } + + sourceID, err := cmdCobra.Flags().GetString("source-id") + if err != nil { + fmt.Println("error on get source id flag", err) + + return + } + + if name == "" || description == "" || sourceID == "" { + fmt.Println("name and description and source id is required") + + return + } + resp, err := cmd.Client.SendRequest(cmd.Client.Source.Update(sourceID, name, description)) + if err != nil { + log.Fatal(err) + } + j, err := io.ReadAll(resp.Body) + if err != nil { + log.Fatal(err) + } + + if resp.StatusCode != http.StatusOK { + log.Fatal(fmt.Errorf("status not Ok ,status code %d, body: %s", resp.StatusCode, j)) + } + + fmt.Printf("success response : \n%s\n", j) }, } func init() { sourceCmd.AddCommand(updateCmd) + updateCmd.Flags().String("name", "", "name") + updateCmd.Flags().String("description", "", "description") + updateCmd.Flags().String("source-id", "", "source-id") + // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command diff --git a/config/test.yml b/config/test.yml new file mode 100644 index 00000000..ad5df7c0 --- /dev/null +++ b/config/test.yml @@ -0,0 +1,7 @@ +debug: false +multi_word_var: "I'm complex in config.yml" +db: + host: "localhost" + username: "ali" + password: "passwd" + multi_word_nested_var: "WHAT??" \ No newline at end of file diff --git a/doc/swagger/manager_docs.go b/doc/swagger/manager_docs.go index b9f4afb0..75bb9c48 100644 --- a/doc/swagger/manager_docs.go +++ b/doc/swagger/manager_docs.go @@ -388,6 +388,59 @@ const docTemplatemanager = `{ } }, "/sources/{source_id}": { + "get": { + "security": [ + { + "JWTToken": [] + } + ], + "description": "Show source", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Source" + ], + "summary": "Show source", + "parameters": [ + { + "type": "string", + "description": "Source identifier", + "name": "source_id", + "in": "path", + "required": true + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/sourceparam.ShowResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + } + } + }, "post": { "security": [ { @@ -504,6 +557,171 @@ const docTemplatemanager = `{ } } }, + "/sources/{source_id}/disable": { + "get": { + "security": [ + { + "JWTToken": [] + } + ], + "description": "Disable source", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Source" + ], + "summary": "Disable source", + "parameters": [ + { + "type": "string", + "description": "Source identifier", + "name": "source_id", + "in": "path", + "required": true + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/sourceparam.DisableResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + } + } + } + }, + "/sources/{source_id}/enable": { + "get": { + "security": [ + { + "JWTToken": [] + } + ], + "description": "Enable source", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Source" + ], + "summary": "Enable source", + "parameters": [ + { + "type": "string", + "description": "Source identifier", + "name": "source_id", + "in": "path", + "required": true + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/sourceparam.EnableResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + } + } + } + }, + "/sources/{source_id}/rotate-write-key": { + "get": { + "security": [ + { + "JWTToken": [] + } + ], + "description": "Rotate writekey", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Source" + ], + "summary": "Rotate writekey", + "parameters": [ + { + "type": "string", + "description": "Source identifier", + "name": "source_id", + "in": "path", + "required": true + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/sourceparam.ShowResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + } + } + } + }, "/users/login": { "post": { "security": [ @@ -914,6 +1132,22 @@ const docTemplatemanager = `{ } } }, + "sourceparam.DisableResponse": { + "type": "object", + "properties": { + "message": { + "type": "string" + } + } + }, + "sourceparam.EnableResponse": { + "type": "object", + "properties": { + "message": { + "type": "string" + } + } + }, "sourceparam.ListResponse": { "type": "object", "properties": { @@ -934,6 +1168,14 @@ const docTemplatemanager = `{ } } }, + "sourceparam.ShowResponse": { + "type": "object", + "properties": { + "source": { + "$ref": "#/definitions/entity.Source" + } + } + }, "sourceparam.UpdateRequest": { "type": "object", "properties": { diff --git a/doc/swagger/manager_swagger.json b/doc/swagger/manager_swagger.json index d6628ebe..0c9ba288 100644 --- a/doc/swagger/manager_swagger.json +++ b/doc/swagger/manager_swagger.json @@ -377,6 +377,59 @@ } }, "/sources/{source_id}": { + "get": { + "security": [ + { + "JWTToken": [] + } + ], + "description": "Show source", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Source" + ], + "summary": "Show source", + "parameters": [ + { + "type": "string", + "description": "Source identifier", + "name": "source_id", + "in": "path", + "required": true + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/sourceparam.ShowResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + } + } + }, "post": { "security": [ { @@ -493,6 +546,171 @@ } } }, + "/sources/{source_id}/disable": { + "get": { + "security": [ + { + "JWTToken": [] + } + ], + "description": "Disable source", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Source" + ], + "summary": "Disable source", + "parameters": [ + { + "type": "string", + "description": "Source identifier", + "name": "source_id", + "in": "path", + "required": true + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/sourceparam.DisableResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + } + } + } + }, + "/sources/{source_id}/enable": { + "get": { + "security": [ + { + "JWTToken": [] + } + ], + "description": "Enable source", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Source" + ], + "summary": "Enable source", + "parameters": [ + { + "type": "string", + "description": "Source identifier", + "name": "source_id", + "in": "path", + "required": true + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/sourceparam.EnableResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + } + } + } + }, + "/sources/{source_id}/rotate-write-key": { + "get": { + "security": [ + { + "JWTToken": [] + } + ], + "description": "Rotate writekey", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Source" + ], + "summary": "Rotate writekey", + "parameters": [ + { + "type": "string", + "description": "Source identifier", + "name": "source_id", + "in": "path", + "required": true + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/sourceparam.ShowResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + } + } + } + }, "/users/login": { "post": { "security": [ @@ -903,6 +1121,22 @@ } } }, + "sourceparam.DisableResponse": { + "type": "object", + "properties": { + "message": { + "type": "string" + } + } + }, + "sourceparam.EnableResponse": { + "type": "object", + "properties": { + "message": { + "type": "string" + } + } + }, "sourceparam.ListResponse": { "type": "object", "properties": { @@ -923,6 +1157,14 @@ } } }, + "sourceparam.ShowResponse": { + "type": "object", + "properties": { + "source": { + "$ref": "#/definitions/entity.Source" + } + } + }, "sourceparam.UpdateRequest": { "type": "object", "properties": { diff --git a/doc/swagger/manager_swagger.yaml b/doc/swagger/manager_swagger.yaml index 0d77ade0..ed51ba91 100644 --- a/doc/swagger/manager_swagger.yaml +++ b/doc/swagger/manager_swagger.yaml @@ -198,6 +198,16 @@ definitions: message: type: string type: object + sourceparam.DisableResponse: + properties: + message: + type: string + type: object + sourceparam.EnableResponse: + properties: + message: + type: string + type: object sourceparam.ListResponse: properties: has_more: @@ -211,6 +221,11 @@ definitions: $ref: '#/definitions/entity.Source' type: array type: object + sourceparam.ShowResponse: + properties: + source: + $ref: '#/definitions/entity.Source' + type: object sourceparam.UpdateRequest: properties: description: @@ -505,6 +520,40 @@ paths: summary: Delete source tags: - Source + get: + consumes: + - application/json + description: Show source + parameters: + - description: Source identifier + in: path + name: source_id + required: true + type: string + produces: + - application/json + responses: + "201": + description: Created + schema: + $ref: '#/definitions/sourceparam.ShowResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/httputil.HTTPError' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/httputil.HTTPError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/httputil.HTTPError' + security: + - JWTToken: [] + summary: Show source + tags: + - Source post: consumes: - application/json @@ -545,6 +594,111 @@ paths: summary: Update source tags: - Source + /sources/{source_id}/disable: + get: + consumes: + - application/json + description: Disable source + parameters: + - description: Source identifier + in: path + name: source_id + required: true + type: string + produces: + - application/json + responses: + "201": + description: Created + schema: + $ref: '#/definitions/sourceparam.DisableResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/httputil.HTTPError' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/httputil.HTTPError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/httputil.HTTPError' + security: + - JWTToken: [] + summary: Disable source + tags: + - Source + /sources/{source_id}/enable: + get: + consumes: + - application/json + description: Enable source + parameters: + - description: Source identifier + in: path + name: source_id + required: true + type: string + produces: + - application/json + responses: + "201": + description: Created + schema: + $ref: '#/definitions/sourceparam.EnableResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/httputil.HTTPError' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/httputil.HTTPError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/httputil.HTTPError' + security: + - JWTToken: [] + summary: Enable source + tags: + - Source + /sources/{source_id}/rotate-write-key: + get: + consumes: + - application/json + description: Rotate writekey + parameters: + - description: Source identifier + in: path + name: source_id + required: true + type: string + produces: + - application/json + responses: + "201": + description: Created + schema: + $ref: '#/definitions/sourceparam.ShowResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/httputil.HTTPError' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/httputil.HTTPError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/httputil.HTTPError' + security: + - JWTToken: [] + summary: Rotate writekey + tags: + - Source /users/login: post: consumes: diff --git a/manager/delivery/httpserver/sourcehandler/disable.go b/manager/delivery/httpserver/sourcehandler/disable.go new file mode 100644 index 00000000..3f722a48 --- /dev/null +++ b/manager/delivery/httpserver/sourcehandler/disable.go @@ -0,0 +1,64 @@ +package sourcehandler + +import ( + "errors" + "net/http" + + "github.com/labstack/echo/v4" + "github.com/ormushq/ormus/logger" + "github.com/ormushq/ormus/manager/managerparam/sourceparam" + "github.com/ormushq/ormus/manager/service/authservice" + "github.com/ormushq/ormus/manager/validator" + "github.com/ormushq/ormus/pkg/errmsg" + "github.com/ormushq/ormus/pkg/httpmsg" + "github.com/ormushq/ormus/pkg/httputil" +) + +// Update godoc +// +// @Summary Disable source +// @Description Disable source +// @Tags Source +// @Accept json +// @Produce json +// @Param source_id path string true "Source identifier" +// @Success 201 {object} sourceparam.DisableResponse +// @Failure 400 {object} httputil.HTTPError +// @Failure 401 {object} httputil.HTTPError +// @Failure 500 {object} httputil.HTTPError +// @Security JWTToken +// @Router /sources/{source_id}/disable [get] +func (h Handler) Disable(ctx echo.Context) error { + // get user id from context + claim, ok := ctx.Get(h.authSvc.GetConfig().ContextKey).(*authservice.Claims) + if !ok { + return ctx.JSON(http.StatusBadRequest, echo.Map{ + "message": "Invalid auth token", + }) + } + + var req sourceparam.DisableRequest + if err := ctx.Bind(&req); err != nil { + return httputil.NewError(ctx, http.StatusBadRequest, errmsg.ErrBadRequest) + } + + req.UserID = claim.UserID + + resp, err := h.sourceSvc.Disable(req) + logger.LogError(err) + var vErr *validator.Error + if errors.As(err, &vErr) { + msg, code := httpmsg.Error(vErr.Err) + + return ctx.JSON(code, echo.Map{ + "message": msg, + "errors": vErr.Fields, + }) + } + + if err != nil { + return httputil.NewErrorWithError(ctx, err) + } + + return ctx.JSON(http.StatusOK, resp) +} diff --git a/manager/delivery/httpserver/sourcehandler/enable.go b/manager/delivery/httpserver/sourcehandler/enable.go new file mode 100644 index 00000000..816b5080 --- /dev/null +++ b/manager/delivery/httpserver/sourcehandler/enable.go @@ -0,0 +1,64 @@ +package sourcehandler + +import ( + "errors" + "net/http" + + "github.com/labstack/echo/v4" + "github.com/ormushq/ormus/logger" + "github.com/ormushq/ormus/manager/managerparam/sourceparam" + "github.com/ormushq/ormus/manager/service/authservice" + "github.com/ormushq/ormus/manager/validator" + "github.com/ormushq/ormus/pkg/errmsg" + "github.com/ormushq/ormus/pkg/httpmsg" + "github.com/ormushq/ormus/pkg/httputil" +) + +// Update godoc +// +// @Summary Enable source +// @Description Enable source +// @Tags Source +// @Accept json +// @Produce json +// @Param source_id path string true "Source identifier" +// @Success 201 {object} sourceparam.EnableResponse +// @Failure 400 {object} httputil.HTTPError +// @Failure 401 {object} httputil.HTTPError +// @Failure 500 {object} httputil.HTTPError +// @Security JWTToken +// @Router /sources/{source_id}/enable [get] +func (h Handler) Enable(ctx echo.Context) error { + // get user id from context + claim, ok := ctx.Get(h.authSvc.GetConfig().ContextKey).(*authservice.Claims) + if !ok { + return ctx.JSON(http.StatusBadRequest, echo.Map{ + "message": "Invalid auth token", + }) + } + + var req sourceparam.EnableRequest + if err := ctx.Bind(&req); err != nil { + return httputil.NewError(ctx, http.StatusBadRequest, errmsg.ErrBadRequest) + } + + req.UserID = claim.UserID + + resp, err := h.sourceSvc.Enable(req) + logger.LogError(err) + var vErr *validator.Error + if errors.As(err, &vErr) { + msg, code := httpmsg.Error(vErr.Err) + + return ctx.JSON(code, echo.Map{ + "message": msg, + "errors": vErr.Fields, + }) + } + + if err != nil { + return httputil.NewErrorWithError(ctx, err) + } + + return ctx.JSON(http.StatusOK, resp) +} diff --git a/manager/delivery/httpserver/sourcehandler/rotatewritekey.go b/manager/delivery/httpserver/sourcehandler/rotatewritekey.go new file mode 100644 index 00000000..4353a516 --- /dev/null +++ b/manager/delivery/httpserver/sourcehandler/rotatewritekey.go @@ -0,0 +1,64 @@ +package sourcehandler + +import ( + "errors" + "net/http" + + "github.com/labstack/echo/v4" + "github.com/ormushq/ormus/logger" + "github.com/ormushq/ormus/manager/managerparam/sourceparam" + "github.com/ormushq/ormus/manager/service/authservice" + "github.com/ormushq/ormus/manager/validator" + "github.com/ormushq/ormus/pkg/errmsg" + "github.com/ormushq/ormus/pkg/httpmsg" + "github.com/ormushq/ormus/pkg/httputil" +) + +// Update godoc +// +// @Summary Rotate writekey +// @Description Rotate writekey +// @Tags Source +// @Accept json +// @Produce json +// @Param source_id path string true "Source identifier" +// @Success 201 {object} sourceparam.ShowResponse +// @Failure 400 {object} httputil.HTTPError +// @Failure 401 {object} httputil.HTTPError +// @Failure 500 {object} httputil.HTTPError +// @Security JWTToken +// @Router /sources/{source_id}/rotate-write-key [get] +func (h Handler) RotateWriteKey(ctx echo.Context) error { + // get user id from context + claim, ok := ctx.Get(h.authSvc.GetConfig().ContextKey).(*authservice.Claims) + if !ok { + return ctx.JSON(http.StatusBadRequest, echo.Map{ + "message": "Invalid auth token", + }) + } + + var req sourceparam.RotateWriteKeyRequest + if err := ctx.Bind(&req); err != nil { + return httputil.NewError(ctx, http.StatusBadRequest, errmsg.ErrBadRequest) + } + + req.UserID = claim.UserID + + resp, err := h.sourceSvc.RotateWriteKey(req) + logger.LogError(err) + var vErr *validator.Error + if errors.As(err, &vErr) { + msg, code := httpmsg.Error(vErr.Err) + + return ctx.JSON(code, echo.Map{ + "message": msg, + "errors": vErr.Fields, + }) + } + + if err != nil { + return httputil.NewErrorWithError(ctx, err) + } + + return ctx.JSON(http.StatusOK, resp) +} diff --git a/manager/delivery/httpserver/sourcehandler/route.go b/manager/delivery/httpserver/sourcehandler/route.go index dcdcb565..59a11bf3 100644 --- a/manager/delivery/httpserver/sourcehandler/route.go +++ b/manager/delivery/httpserver/sourcehandler/route.go @@ -10,5 +10,9 @@ func (h Handler) SetRoutes(e *echo.Echo) { sourceGroups.GET("", h.List) sourceGroups.POST("", h.Create) sourceGroups.POST("/:sourceID", h.Update) + sourceGroups.GET("/:sourceID", h.Show) + sourceGroups.GET("/:sourceID/rotate-write-key", h.RotateWriteKey) + sourceGroups.GET("/:sourceID/enable", h.Enable) + sourceGroups.GET("/:sourceID/disable", h.Disable) sourceGroups.DELETE("/:sourceID", h.Delete) } diff --git a/manager/delivery/httpserver/sourcehandler/show.go b/manager/delivery/httpserver/sourcehandler/show.go new file mode 100644 index 00000000..d3f7e5ab --- /dev/null +++ b/manager/delivery/httpserver/sourcehandler/show.go @@ -0,0 +1,64 @@ +package sourcehandler + +import ( + "errors" + "net/http" + + "github.com/labstack/echo/v4" + "github.com/ormushq/ormus/logger" + "github.com/ormushq/ormus/manager/managerparam/sourceparam" + "github.com/ormushq/ormus/manager/service/authservice" + "github.com/ormushq/ormus/manager/validator" + "github.com/ormushq/ormus/pkg/errmsg" + "github.com/ormushq/ormus/pkg/httpmsg" + "github.com/ormushq/ormus/pkg/httputil" +) + +// Update godoc +// +// @Summary Show source +// @Description Show source +// @Tags Source +// @Accept json +// @Produce json +// @Param source_id path string true "Source identifier" +// @Success 201 {object} sourceparam.ShowResponse +// @Failure 400 {object} httputil.HTTPError +// @Failure 401 {object} httputil.HTTPError +// @Failure 500 {object} httputil.HTTPError +// @Security JWTToken +// @Router /sources/{source_id} [get] +func (h Handler) Show(ctx echo.Context) error { + // get user id from context + claim, ok := ctx.Get(h.authSvc.GetConfig().ContextKey).(*authservice.Claims) + if !ok { + return ctx.JSON(http.StatusBadRequest, echo.Map{ + "message": "Invalid auth token", + }) + } + + var req sourceparam.ShowRequest + if err := ctx.Bind(&req); err != nil { + return httputil.NewError(ctx, http.StatusBadRequest, errmsg.ErrBadRequest) + } + + req.UserID = claim.UserID + + resp, err := h.sourceSvc.Show(req) + logger.LogError(err) + var vErr *validator.Error + if errors.As(err, &vErr) { + msg, code := httpmsg.Error(vErr.Err) + + return ctx.JSON(code, echo.Map{ + "message": msg, + "errors": vErr.Fields, + }) + } + + if err != nil { + return httputil.NewErrorWithError(ctx, err) + } + + return ctx.JSON(http.StatusOK, resp) +} diff --git a/manager/managerparam/sourceparam/disable.go b/manager/managerparam/sourceparam/disable.go new file mode 100644 index 00000000..65330f61 --- /dev/null +++ b/manager/managerparam/sourceparam/disable.go @@ -0,0 +1,10 @@ +package sourceparam + +type DisableRequest struct { + UserID string `json:"-"` + SourceID string `json:"-" param:"SourceID"` +} + +type DisableResponse struct { + Message string `json:"message"` +} diff --git a/manager/managerparam/sourceparam/enable.go b/manager/managerparam/sourceparam/enable.go new file mode 100644 index 00000000..29d572d0 --- /dev/null +++ b/manager/managerparam/sourceparam/enable.go @@ -0,0 +1,10 @@ +package sourceparam + +type EnableRequest struct { + UserID string `json:"-"` + SourceID string `json:"-" param:"SourceID"` +} + +type EnableResponse struct { + Message string `json:"message"` +} diff --git a/manager/managerparam/sourceparam/rotatewritekey.go b/manager/managerparam/sourceparam/rotatewritekey.go new file mode 100644 index 00000000..666b426e --- /dev/null +++ b/manager/managerparam/sourceparam/rotatewritekey.go @@ -0,0 +1,12 @@ +package sourceparam + +import "github.com/ormushq/ormus/manager/entity" + +type RotateWriteKeyRequest struct { + UserID string `json:"-"` + SourceID string `json:"-" param:"SourceID"` +} + +type RotateWriteKeyResponse struct { + Source entity.Source `json:"source"` +} diff --git a/manager/managerparam/sourceparam/show.go b/manager/managerparam/sourceparam/show.go new file mode 100644 index 00000000..d502cd9b --- /dev/null +++ b/manager/managerparam/sourceparam/show.go @@ -0,0 +1,12 @@ +package sourceparam + +import "github.com/ormushq/ormus/manager/entity" + +type ShowRequest struct { + UserID string `json:"-"` + SourceID string `json:"-" param:"SourceID"` +} + +type ShowResponse struct { + Source entity.Source `json:"source"` +} diff --git a/manager/managerparam/sourceparam/update.go b/manager/managerparam/sourceparam/update.go index 7035c9c2..81a6ddcd 100644 --- a/manager/managerparam/sourceparam/update.go +++ b/manager/managerparam/sourceparam/update.go @@ -7,7 +7,6 @@ type UpdateRequest struct { SourceID string `json:"-" param:"SourceID"` Name string `json:"name" example:"updated name"` Description string `json:"description" example:"updated description"` - Status string `json:"status" example:"active"` } type UpdateResponse struct { diff --git a/manager/service/sourceservice/disable.go b/manager/service/sourceservice/disable.go new file mode 100644 index 00000000..58ceb5d6 --- /dev/null +++ b/manager/service/sourceservice/disable.go @@ -0,0 +1,36 @@ +package sourceservice + +import ( + "github.com/ormushq/ormus/manager/entity" + "github.com/ormushq/ormus/manager/managerparam/sourceparam" + "github.com/ormushq/ormus/pkg/errmsg" + "github.com/ormushq/ormus/pkg/richerror" +) + +func (s Service) Disable(req sourceparam.DisableRequest) (sourceparam.DisableResponse, error) { + const op = "sourceService.Disable" + + vErr := s.validator.ValidateDisableRequest(req) + if vErr != nil { + return sourceparam.DisableResponse{}, vErr + } + source, err := s.repo.GetWithID(req.SourceID) + if err != nil { + return sourceparam.DisableResponse{}, richerror.New(op).WithWrappedError(err) + } + + if source.OwnerID != req.UserID { + return sourceparam.DisableResponse{}, richerror.New(op).WithKind(richerror.KindForbidden).WithMessage(errmsg.ErrAccessDenied) + } + + source.Status = entity.SourceStatusNotActive + + _, err = s.repo.Update(source) + if err != nil { + return sourceparam.DisableResponse{}, richerror.New(op).WithWrappedError(err).WithMessage(errmsg.ErrSomeThingWentWrong) + } + + return sourceparam.DisableResponse{ + Message: "source Disabled", + }, nil +} diff --git a/manager/service/sourceservice/enable.go b/manager/service/sourceservice/enable.go new file mode 100644 index 00000000..c2784634 --- /dev/null +++ b/manager/service/sourceservice/enable.go @@ -0,0 +1,36 @@ +package sourceservice + +import ( + "github.com/ormushq/ormus/manager/entity" + "github.com/ormushq/ormus/manager/managerparam/sourceparam" + "github.com/ormushq/ormus/pkg/errmsg" + "github.com/ormushq/ormus/pkg/richerror" +) + +func (s Service) Enable(req sourceparam.EnableRequest) (sourceparam.EnableResponse, error) { + const op = "sourceService.Enable" + + vErr := s.validator.ValidateEnableRequest(req) + if vErr != nil { + return sourceparam.EnableResponse{}, vErr + } + source, err := s.repo.GetWithID(req.SourceID) + if err != nil { + return sourceparam.EnableResponse{}, richerror.New(op).WithWrappedError(err) + } + + if source.OwnerID != req.UserID { + return sourceparam.EnableResponse{}, richerror.New(op).WithKind(richerror.KindForbidden).WithMessage(errmsg.ErrAccessDenied) + } + + source.Status = entity.SourceStatusActive + + _, err = s.repo.Update(source) + if err != nil { + return sourceparam.EnableResponse{}, richerror.New(op).WithWrappedError(err).WithMessage(errmsg.ErrSomeThingWentWrong) + } + + return sourceparam.EnableResponse{ + Message: "source enabled", + }, nil +} diff --git a/manager/service/sourceservice/rotatewritekey.go b/manager/service/sourceservice/rotatewritekey.go new file mode 100644 index 00000000..959a0865 --- /dev/null +++ b/manager/service/sourceservice/rotatewritekey.go @@ -0,0 +1,40 @@ +package sourceservice + +import ( + "github.com/ormushq/ormus/manager/entity" + "github.com/ormushq/ormus/manager/managerparam/sourceparam" + "github.com/ormushq/ormus/pkg/errmsg" + "github.com/ormushq/ormus/pkg/richerror" + writekey "github.com/ormushq/ormus/pkg/write_key" +) + +func (s Service) RotateWriteKey(req sourceparam.RotateWriteKeyRequest) (sourceparam.RotateWriteKeyResponse, error) { + const op = "sourceService.RotateWriteKey" + + vErr := s.validator.ValidateRotateWriteKeyRequest(req) + if vErr != nil { + return sourceparam.RotateWriteKeyResponse{}, vErr + } + source, err := s.repo.GetWithID(req.SourceID) + if err != nil { + return sourceparam.RotateWriteKeyResponse{}, richerror.New(op).WithWrappedError(err) + } + + if source.OwnerID != req.UserID { + return sourceparam.RotateWriteKeyResponse{}, richerror.New(op).WithKind(richerror.KindForbidden).WithMessage(errmsg.ErrAccessDenied) + } + + w, err := writekey.GenerateNewWriteKey() + if err != nil { + return sourceparam.RotateWriteKeyResponse{}, err + } + source.WriteKey = entity.WriteKey(w) + source, err = s.repo.Update(source) + if err != nil { + return sourceparam.RotateWriteKeyResponse{}, richerror.New(op).WithWrappedError(err).WithMessage(errmsg.ErrSomeThingWentWrong) + } + + return sourceparam.RotateWriteKeyResponse{ + Source: source, + }, nil +} diff --git a/manager/service/sourceservice/show.go b/manager/service/sourceservice/show.go new file mode 100644 index 00000000..b73f3b9c --- /dev/null +++ b/manager/service/sourceservice/show.go @@ -0,0 +1,28 @@ +package sourceservice + +import ( + "github.com/ormushq/ormus/manager/managerparam/sourceparam" + "github.com/ormushq/ormus/pkg/errmsg" + "github.com/ormushq/ormus/pkg/richerror" +) + +func (s Service) Show(req sourceparam.ShowRequest) (sourceparam.ShowResponse, error) { + const op = "sourceService.Show" + + vErr := s.validator.ValidateShowRequest(req) + if vErr != nil { + return sourceparam.ShowResponse{}, vErr + } + source, err := s.repo.GetWithID(req.SourceID) + if err != nil { + return sourceparam.ShowResponse{}, richerror.New(op).WithWrappedError(err) + } + + if source.OwnerID != req.UserID { + return sourceparam.ShowResponse{}, richerror.New(op).WithKind(richerror.KindForbidden).WithMessage(errmsg.ErrAccessDenied) + } + + return sourceparam.ShowResponse{ + Source: source, + }, nil +} diff --git a/manager/service/sourceservice/update.go b/manager/service/sourceservice/update.go index f85c26fc..9591cc5d 100644 --- a/manager/service/sourceservice/update.go +++ b/manager/service/sourceservice/update.go @@ -1,7 +1,6 @@ package sourceservice import ( - "github.com/ormushq/ormus/manager/entity" "github.com/ormushq/ormus/manager/managerparam/sourceparam" "github.com/ormushq/ormus/pkg/errmsg" "github.com/ormushq/ormus/pkg/richerror" @@ -24,12 +23,6 @@ func (s Service) Update(req sourceparam.UpdateRequest) (sourceparam.UpdateRespon } source.Name = req.Name source.Description = req.Description - switch req.Status { - case string(entity.SourceStatusActive): - source.Status = entity.SourceStatusActive - case string(entity.SourceStatusNotActive): - source.Status = entity.SourceStatusNotActive - } source, err = s.repo.Update(source) if err != nil { diff --git a/manager/validator/sourcevalidator/disable.go b/manager/validator/sourcevalidator/disable.go new file mode 100644 index 00000000..61bf3158 --- /dev/null +++ b/manager/validator/sourcevalidator/disable.go @@ -0,0 +1,41 @@ +package sourcevalidator + +import ( + "errors" + + validation "github.com/go-ozzo/ozzo-validation/v4" + "github.com/ormushq/ormus/manager/managerparam/sourceparam" + "github.com/ormushq/ormus/manager/validator" + "github.com/ormushq/ormus/pkg/errmsg" + "github.com/ormushq/ormus/pkg/richerror" +) + +func (v Validator) ValidateDisableRequest(req sourceparam.DisableRequest) *validator.Error { + const op = "sourcevalidator.ValidateDisableRequest" + + if err := validation.ValidateStruct(&req, + validation.Field(&req.UserID, validation.Required), + ); err != nil { + + fieldErr := make(map[string]string) + + var errV validation.Errors + ok := errors.As(err, &errV) + + if ok { + for key, value := range errV { + if value != nil { + fieldErr[key] = value.Error() + } + } + } + + return &validator.Error{ + Fields: fieldErr, + Err: richerror.New(op).WithMessage(errmsg.ErrorMsgInvalidInput).WhitKind(richerror.KindInvalid). + WhitMeta(map[string]interface{}{"request:": req}).WithWrappedError(err), + } + } + + return nil +} diff --git a/manager/validator/sourcevalidator/enable.go b/manager/validator/sourcevalidator/enable.go new file mode 100644 index 00000000..d030fc0e --- /dev/null +++ b/manager/validator/sourcevalidator/enable.go @@ -0,0 +1,41 @@ +package sourcevalidator + +import ( + "errors" + + validation "github.com/go-ozzo/ozzo-validation/v4" + "github.com/ormushq/ormus/manager/managerparam/sourceparam" + "github.com/ormushq/ormus/manager/validator" + "github.com/ormushq/ormus/pkg/errmsg" + "github.com/ormushq/ormus/pkg/richerror" +) + +func (v Validator) ValidateEnableRequest(req sourceparam.EnableRequest) *validator.Error { + const op = "sourcevalidator.ValidateEnableRequest" + + if err := validation.ValidateStruct(&req, + validation.Field(&req.UserID, validation.Required), + ); err != nil { + + fieldErr := make(map[string]string) + + var errV validation.Errors + ok := errors.As(err, &errV) + + if ok { + for key, value := range errV { + if value != nil { + fieldErr[key] = value.Error() + } + } + } + + return &validator.Error{ + Fields: fieldErr, + Err: richerror.New(op).WithMessage(errmsg.ErrorMsgInvalidInput).WhitKind(richerror.KindInvalid). + WhitMeta(map[string]interface{}{"request:": req}).WithWrappedError(err), + } + } + + return nil +} diff --git a/manager/validator/sourcevalidator/rotatewritekey.go b/manager/validator/sourcevalidator/rotatewritekey.go new file mode 100644 index 00000000..709a91c6 --- /dev/null +++ b/manager/validator/sourcevalidator/rotatewritekey.go @@ -0,0 +1,41 @@ +package sourcevalidator + +import ( + "errors" + + validation "github.com/go-ozzo/ozzo-validation/v4" + "github.com/ormushq/ormus/manager/managerparam/sourceparam" + "github.com/ormushq/ormus/manager/validator" + "github.com/ormushq/ormus/pkg/errmsg" + "github.com/ormushq/ormus/pkg/richerror" +) + +func (v Validator) ValidateRotateWriteKeyRequest(req sourceparam.RotateWriteKeyRequest) *validator.Error { + const op = "sourcevalidator.ValidateRotateWriteKeyRequest" + + if err := validation.ValidateStruct(&req, + validation.Field(&req.UserID, validation.Required), + ); err != nil { + + fieldErr := make(map[string]string) + + var errV validation.Errors + ok := errors.As(err, &errV) + + if ok { + for key, value := range errV { + if value != nil { + fieldErr[key] = value.Error() + } + } + } + + return &validator.Error{ + Fields: fieldErr, + Err: richerror.New(op).WithMessage(errmsg.ErrorMsgInvalidInput).WhitKind(richerror.KindInvalid). + WhitMeta(map[string]interface{}{"request:": req}).WithWrappedError(err), + } + } + + return nil +} diff --git a/manager/validator/sourcevalidator/show.go b/manager/validator/sourcevalidator/show.go new file mode 100644 index 00000000..3ae7a6bb --- /dev/null +++ b/manager/validator/sourcevalidator/show.go @@ -0,0 +1,41 @@ +package sourcevalidator + +import ( + "errors" + + validation "github.com/go-ozzo/ozzo-validation/v4" + "github.com/ormushq/ormus/manager/managerparam/sourceparam" + "github.com/ormushq/ormus/manager/validator" + "github.com/ormushq/ormus/pkg/errmsg" + "github.com/ormushq/ormus/pkg/richerror" +) + +func (v Validator) ValidateShowRequest(req sourceparam.ShowRequest) *validator.Error { + const op = "sourcevalidator.ValidateShowRequest" + + if err := validation.ValidateStruct(&req, + validation.Field(&req.UserID, validation.Required), + ); err != nil { + + fieldErr := make(map[string]string) + + var errV validation.Errors + ok := errors.As(err, &errV) + + if ok { + for key, value := range errV { + if value != nil { + fieldErr[key] = value.Error() + } + } + } + + return &validator.Error{ + Fields: fieldErr, + Err: richerror.New(op).WithMessage(errmsg.ErrorMsgInvalidInput).WhitKind(richerror.KindInvalid). + WhitMeta(map[string]interface{}{"request:": req}).WithWrappedError(err), + } + } + + return nil +} diff --git a/manager/validator/sourcevalidator/update.go b/manager/validator/sourcevalidator/update.go index 16dfb548..686abfb1 100644 --- a/manager/validator/sourcevalidator/update.go +++ b/manager/validator/sourcevalidator/update.go @@ -4,7 +4,6 @@ import ( "errors" validation "github.com/go-ozzo/ozzo-validation/v4" - "github.com/ormushq/ormus/manager/entity" "github.com/ormushq/ormus/manager/managerparam/sourceparam" "github.com/ormushq/ormus/manager/validator" "github.com/ormushq/ormus/pkg/errmsg" @@ -24,7 +23,6 @@ func (v Validator) ValidateUpdateRequest(req sourceparam.UpdateRequest) *validat validation.Field(&req.Name, validation.Required, validation.Length(minNameLength, maxNameLength)), validation.Field(&req.Description, validation.Required, validation.Length(minDescriptionLength, maxDescriptionLength)), validation.Field(&req.UserID, validation.Required), - validation.Field(&req.Status, validation.Required, validation.By(v.validateStatus)), ); err != nil { fieldErr := make(map[string]string) @@ -49,18 +47,3 @@ func (v Validator) ValidateUpdateRequest(req sourceparam.UpdateRequest) *validat return nil } - -func (v Validator) validateStatus(value interface{}) error { - s, ok := value.(string) - if !ok { - return errors.New("error while reflection interface") - } - switch s { - case string(entity.SourceStatusActive): - return nil - case string(entity.SourceStatusNotActive): - return nil - } - - return errors.New("invalide status of source") -}