From a183909b1122ff19dbddb08b3fa51771a4c68738 Mon Sep 17 00:00:00 2001 From: MartinezAvellan Date: Mon, 14 Oct 2024 15:00:58 +0200 Subject: [PATCH 1/8] feat: implement auth on transaction :sparkles: --- components/ledger/internal/gen/inject.go | 2 +- .../internal/adapters/grpc/account.grpc.go | 17 +++++-- .../domain/account/account_repository.go | 6 +-- components/transaction/internal/gen/inject.go | 21 +++++++-- .../internal/gen/mock/account/account_mock.go | 24 +++++----- .../transaction/internal/gen/wire_gen.go | 26 ++++++++--- .../internal/ports/{ => http}/operation.go | 2 +- .../transaction/internal/ports/http/routes.go | 35 +++++++-------- .../internal/ports/{ => http}/transaction.go | 10 ++--- .../transaction/internal/service/config.go | 45 +++++++++++-------- go.sum | 1 + 11 files changed, 117 insertions(+), 72 deletions(-) rename components/transaction/internal/ports/{ => http}/operation.go (99%) rename components/transaction/internal/ports/{ => http}/transaction.go (97%) diff --git a/components/ledger/internal/gen/inject.go b/components/ledger/internal/gen/inject.go index 7a90fdab..9e52520b 100644 --- a/components/ledger/internal/gen/inject.go +++ b/components/ledger/internal/gen/inject.go @@ -5,10 +5,10 @@ package gen import ( "fmt" - "github.com/LerianStudio/midaz/common/mcasdoor" "sync" "github.com/LerianStudio/midaz/common" + "github.com/LerianStudio/midaz/common/mcasdoor" "github.com/LerianStudio/midaz/common/mmongo" "github.com/LerianStudio/midaz/common/mpostgres" "github.com/LerianStudio/midaz/common/mzap" diff --git a/components/transaction/internal/adapters/grpc/account.grpc.go b/components/transaction/internal/adapters/grpc/account.grpc.go index fac32379..735e4f52 100644 --- a/components/transaction/internal/adapters/grpc/account.grpc.go +++ b/components/transaction/internal/adapters/grpc/account.grpc.go @@ -2,9 +2,11 @@ package grpc import ( "context" + "fmt" "github.com/LerianStudio/midaz/common/mgrpc" proto "github.com/LerianStudio/midaz/common/mgrpc/account" + gmtdt "google.golang.org/grpc/metadata" ) // AccountGRPCRepository is a gRPC implementation of the account.proto @@ -27,7 +29,7 @@ func NewAccountGRPC(c *mgrpc.GRPCConnection) *AccountGRPCRepository { } // GetAccountsByIds returns a grpc accounts on ledger bi given ids. -func (a *AccountGRPCRepository) GetAccountsByIds(ctx context.Context, ids []string) (*proto.AccountsResponse, error) { +func (a *AccountGRPCRepository) GetAccountsByIds(ctx context.Context, token string, ids []string) (*proto.AccountsResponse, error) { conn, err := a.conn.GetNewClient() if err != nil { return nil, err @@ -39,6 +41,9 @@ func (a *AccountGRPCRepository) GetAccountsByIds(ctx context.Context, ids []stri Ids: ids, } + md := gmtdt.Pairs("authorization", fmt.Sprintf("Bearer %s", token)) + ctx = gmtdt.NewOutgoingContext(ctx, md) + accountsResponse, err := client.GetAccountsByIds(ctx, accountsID) if err != nil { return nil, err @@ -48,7 +53,7 @@ func (a *AccountGRPCRepository) GetAccountsByIds(ctx context.Context, ids []stri } // GetAccountsByAlias returns a grpc accounts on ledger bi given aliases. -func (a *AccountGRPCRepository) GetAccountsByAlias(ctx context.Context, aliases []string) (*proto.AccountsResponse, error) { +func (a *AccountGRPCRepository) GetAccountsByAlias(ctx context.Context, token string, aliases []string) (*proto.AccountsResponse, error) { conn, err := a.conn.GetNewClient() if err != nil { return nil, err @@ -60,6 +65,9 @@ func (a *AccountGRPCRepository) GetAccountsByAlias(ctx context.Context, aliases Aliases: aliases, } + md := gmtdt.Pairs("authorization", fmt.Sprintf("Bearer %s", token)) + ctx = gmtdt.NewOutgoingContext(ctx, md) + accountsResponse, err := client.GetAccountsByAliases(ctx, accountsAlias) if err != nil { return nil, err @@ -69,7 +77,7 @@ func (a *AccountGRPCRepository) GetAccountsByAlias(ctx context.Context, aliases } // UpdateAccounts update a grpc accounts on ledger. -func (a *AccountGRPCRepository) UpdateAccounts(ctx context.Context, accounts []*proto.Account) (*proto.AccountsResponse, error) { +func (a *AccountGRPCRepository) UpdateAccounts(ctx context.Context, token string, accounts []*proto.Account) (*proto.AccountsResponse, error) { conn, err := a.conn.GetNewClient() if err != nil { return nil, err @@ -81,6 +89,9 @@ func (a *AccountGRPCRepository) UpdateAccounts(ctx context.Context, accounts []* Accounts: accounts, } + md := gmtdt.Pairs("authorization", fmt.Sprintf("Bearer %s", token)) + ctx = gmtdt.NewOutgoingContext(ctx, md) + accountsResponse, err := client.UpdateAccounts(ctx, accountsRequest) if err != nil { return nil, err diff --git a/components/transaction/internal/domain/account/account_repository.go b/components/transaction/internal/domain/account/account_repository.go index ce2144f0..14447b4d 100644 --- a/components/transaction/internal/domain/account/account_repository.go +++ b/components/transaction/internal/domain/account/account_repository.go @@ -10,7 +10,7 @@ import ( // //go:generate mockgen --destination=../../gen/mock/account/account_mock.go --package=mock . Repository type Repository interface { - GetAccountsByIds(ctx context.Context, ids []string) (*proto.AccountsResponse, error) - GetAccountsByAlias(ctx context.Context, aliases []string) (*proto.AccountsResponse, error) - UpdateAccounts(ctx context.Context, accounts []*proto.Account) (*proto.AccountsResponse, error) + GetAccountsByIds(ctx context.Context, token string, ids []string) (*proto.AccountsResponse, error) + GetAccountsByAlias(ctx context.Context, token string, aliases []string) (*proto.AccountsResponse, error) + UpdateAccounts(ctx context.Context, token string, accounts []*proto.Account) (*proto.AccountsResponse, error) } diff --git a/components/transaction/internal/gen/inject.go b/components/transaction/internal/gen/inject.go index 59a5fc1c..98ee34e6 100644 --- a/components/transaction/internal/gen/inject.go +++ b/components/transaction/internal/gen/inject.go @@ -5,10 +5,10 @@ package gen import ( "fmt" - "github.com/LerianStudio/midaz/components/transaction/internal/ports" "sync" "github.com/LerianStudio/midaz/common" + "github.com/LerianStudio/midaz/common/mcasdoor" "github.com/LerianStudio/midaz/common/mgrpc" "github.com/LerianStudio/midaz/common/mmongo" "github.com/LerianStudio/midaz/common/mpostgres" @@ -58,6 +58,20 @@ func setupMongoDBConnection(cfg *service.Config) *mmongo.MongoConnection { } } +func setupCasdoorConnection(cfg *service.Config) *mcasdoor.CasdoorConnection { + casdoor := &mcasdoor.CasdoorConnection{ + JWKUri: cfg.JWKAddress, + Endpoint: cfg.CasdoorAddress, + ClientID: cfg.CasdoorClientID, + ClientSecret: cfg.CasdoorClientSecret, + OrganizationName: cfg.CasdoorOrganizationName, + ApplicationName: cfg.CasdoorApplicationName, + EnforcerName: cfg.CasdoorEnforcerName, + } + + return casdoor +} + func setupGRPCConnection(cfg *service.Config) *mgrpc.GRPCConnection { addr := fmt.Sprintf("%s:%s", cfg.LedgerGRPCAddr, cfg.LedgerGRPCPort) @@ -72,6 +86,7 @@ var ( mzap.InitializeLogger, setupPostgreSQLConnection, setupMongoDBConnection, + setupCasdoorConnection, setupGRPCConnection, service.NewConfig, httpHandler.NewRouter, @@ -80,8 +95,8 @@ var ( postgres.NewOperationPostgreSQLRepository, mongodb.NewMetadataMongoDBRepository, grpc.NewAccountGRPC, - wire.Struct(new(ports.TransactionHandler), "*"), - wire.Struct(new(ports.OperationHandler), "*"), + wire.Struct(new(httpHandler.TransactionHandler), "*"), + wire.Struct(new(httpHandler.OperationHandler), "*"), wire.Struct(new(command.UseCase), "*"), wire.Struct(new(query.UseCase), "*"), wire.Bind(new(t.Repository), new(*postgres.TransactionPostgreSQLRepository)), diff --git a/components/transaction/internal/gen/mock/account/account_mock.go b/components/transaction/internal/gen/mock/account/account_mock.go index fe52c232..e1fc26b0 100644 --- a/components/transaction/internal/gen/mock/account/account_mock.go +++ b/components/transaction/internal/gen/mock/account/account_mock.go @@ -41,46 +41,46 @@ func (m *MockRepository) EXPECT() *MockRepositoryMockRecorder { } // GetAccountsByAlias mocks base method. -func (m *MockRepository) GetAccountsByAlias(arg0 context.Context, arg1 []string) (*account.AccountsResponse, error) { +func (m *MockRepository) GetAccountsByAlias(arg0 context.Context, arg1 string, arg2 []string) (*account.AccountsResponse, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAccountsByAlias", arg0, arg1) + ret := m.ctrl.Call(m, "GetAccountsByAlias", arg0, arg1, arg2) ret0, _ := ret[0].(*account.AccountsResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // GetAccountsByAlias indicates an expected call of GetAccountsByAlias. -func (mr *MockRepositoryMockRecorder) GetAccountsByAlias(arg0, arg1 any) *gomock.Call { +func (mr *MockRepositoryMockRecorder) GetAccountsByAlias(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccountsByAlias", reflect.TypeOf((*MockRepository)(nil).GetAccountsByAlias), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccountsByAlias", reflect.TypeOf((*MockRepository)(nil).GetAccountsByAlias), arg0, arg1, arg2) } // GetAccountsByIds mocks base method. -func (m *MockRepository) GetAccountsByIds(arg0 context.Context, arg1 []string) (*account.AccountsResponse, error) { +func (m *MockRepository) GetAccountsByIds(arg0 context.Context, arg1 string, arg2 []string) (*account.AccountsResponse, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAccountsByIds", arg0, arg1) + ret := m.ctrl.Call(m, "GetAccountsByIds", arg0, arg1, arg2) ret0, _ := ret[0].(*account.AccountsResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // GetAccountsByIds indicates an expected call of GetAccountsByIds. -func (mr *MockRepositoryMockRecorder) GetAccountsByIds(arg0, arg1 any) *gomock.Call { +func (mr *MockRepositoryMockRecorder) GetAccountsByIds(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccountsByIds", reflect.TypeOf((*MockRepository)(nil).GetAccountsByIds), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccountsByIds", reflect.TypeOf((*MockRepository)(nil).GetAccountsByIds), arg0, arg1, arg2) } // UpdateAccounts mocks base method. -func (m *MockRepository) UpdateAccounts(arg0 context.Context, arg1 []*account.Account) (*account.AccountsResponse, error) { +func (m *MockRepository) UpdateAccounts(arg0 context.Context, arg1 string, arg2 []*account.Account) (*account.AccountsResponse, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateAccounts", arg0, arg1) + ret := m.ctrl.Call(m, "UpdateAccounts", arg0, arg1, arg2) ret0, _ := ret[0].(*account.AccountsResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // UpdateAccounts indicates an expected call of UpdateAccounts. -func (mr *MockRepositoryMockRecorder) UpdateAccounts(arg0, arg1 any) *gomock.Call { +func (mr *MockRepositoryMockRecorder) UpdateAccounts(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateAccounts", reflect.TypeOf((*MockRepository)(nil).UpdateAccounts), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateAccounts", reflect.TypeOf((*MockRepository)(nil).UpdateAccounts), arg0, arg1, arg2) } diff --git a/components/transaction/internal/gen/wire_gen.go b/components/transaction/internal/gen/wire_gen.go index b8df4ede..d930bc9e 100644 --- a/components/transaction/internal/gen/wire_gen.go +++ b/components/transaction/internal/gen/wire_gen.go @@ -9,6 +9,7 @@ package gen import ( "fmt" "github.com/LerianStudio/midaz/common" + "github.com/LerianStudio/midaz/common/mcasdoor" "github.com/LerianStudio/midaz/common/mgrpc" "github.com/LerianStudio/midaz/common/mmongo" "github.com/LerianStudio/midaz/common/mpostgres" @@ -22,7 +23,6 @@ import ( "github.com/LerianStudio/midaz/components/transaction/internal/domain/metadata" "github.com/LerianStudio/midaz/components/transaction/internal/domain/operation" "github.com/LerianStudio/midaz/components/transaction/internal/domain/transaction" - "github.com/LerianStudio/midaz/components/transaction/internal/ports" "github.com/LerianStudio/midaz/components/transaction/internal/ports/http" "github.com/LerianStudio/midaz/components/transaction/internal/service" "github.com/google/wire" @@ -34,6 +34,7 @@ import ( // InitializeService the setup the dependencies and returns a new *service.Service instance func InitializeService() *service.Service { config := service.NewConfig() + casdoorConnection := setupCasdoorConnection(config) postgresConnection := setupPostgreSQLConnection(config) transactionPostgreSQLRepository := postgres.NewTransactionPostgreSQLRepository(postgresConnection) grpcConnection := setupGRPCConnection(config) @@ -53,15 +54,15 @@ func InitializeService() *service.Service { OperationRepo: operationPostgreSQLRepository, MetadataRepo: metadataMongoDBRepository, } - transactionHandler := &ports.TransactionHandler{ + transactionHandler := &http.TransactionHandler{ Command: useCase, Query: queryUseCase, } - operationHandler := &ports.OperationHandler{ + operationHandler := &http.OperationHandler{ Command: useCase, Query: queryUseCase, } - app := http.NewRouter(transactionHandler, operationHandler) + app := http.NewRouter(casdoorConnection, transactionHandler, operationHandler) logger := mzap.InitializeLogger() server := service.NewServer(config, app, logger) serviceService := &service.Service{ @@ -103,6 +104,20 @@ func setupMongoDBConnection(cfg *service.Config) *mmongo.MongoConnection { } } +func setupCasdoorConnection(cfg *service.Config) *mcasdoor.CasdoorConnection { + casdoor := &mcasdoor.CasdoorConnection{ + JWKUri: cfg.JWKAddress, + Endpoint: cfg.CasdoorAddress, + ClientID: cfg.CasdoorClientID, + ClientSecret: cfg.CasdoorClientSecret, + OrganizationName: cfg.CasdoorOrganizationName, + ApplicationName: cfg.CasdoorApplicationName, + EnforcerName: cfg.CasdoorEnforcerName, + } + + return casdoor +} + func setupGRPCConnection(cfg *service.Config) *mgrpc.GRPCConnection { addr := fmt.Sprintf("%s:%s", cfg.LedgerGRPCAddr, cfg.LedgerGRPCPort) @@ -114,7 +129,8 @@ func setupGRPCConnection(cfg *service.Config) *mgrpc.GRPCConnection { var ( serviceSet = wire.NewSet(common.InitLocalEnvConfig, mzap.InitializeLogger, setupPostgreSQLConnection, setupMongoDBConnection, - setupGRPCConnection, service.NewConfig, http.NewRouter, service.NewServer, postgres.NewTransactionPostgreSQLRepository, postgres.NewOperationPostgreSQLRepository, mongodb.NewMetadataMongoDBRepository, grpc.NewAccountGRPC, wire.Struct(new(ports.TransactionHandler), "*"), wire.Struct(new(ports.OperationHandler), "*"), wire.Struct(new(command.UseCase), "*"), wire.Struct(new(query.UseCase), "*"), wire.Bind(new(transaction.Repository), new(*postgres.TransactionPostgreSQLRepository)), wire.Bind(new(operation.Repository), new(*postgres.OperationPostgreSQLRepository)), wire.Bind(new(account.Repository), new(*grpc.AccountGRPCRepository)), wire.Bind(new(metadata.Repository), new(*mongodb.MetadataMongoDBRepository)), + setupCasdoorConnection, + setupGRPCConnection, service.NewConfig, http.NewRouter, service.NewServer, postgres.NewTransactionPostgreSQLRepository, postgres.NewOperationPostgreSQLRepository, mongodb.NewMetadataMongoDBRepository, grpc.NewAccountGRPC, wire.Struct(new(http.TransactionHandler), "*"), wire.Struct(new(http.OperationHandler), "*"), wire.Struct(new(command.UseCase), "*"), wire.Struct(new(query.UseCase), "*"), wire.Bind(new(transaction.Repository), new(*postgres.TransactionPostgreSQLRepository)), wire.Bind(new(operation.Repository), new(*postgres.OperationPostgreSQLRepository)), wire.Bind(new(account.Repository), new(*grpc.AccountGRPCRepository)), wire.Bind(new(metadata.Repository), new(*mongodb.MetadataMongoDBRepository)), ) svcSet = wire.NewSet(wire.Struct(new(service.Service), "Server", "Logger")) diff --git a/components/transaction/internal/ports/operation.go b/components/transaction/internal/ports/http/operation.go similarity index 99% rename from components/transaction/internal/ports/operation.go rename to components/transaction/internal/ports/http/operation.go index c7673270..bcd3becc 100644 --- a/components/transaction/internal/ports/operation.go +++ b/components/transaction/internal/ports/http/operation.go @@ -1,4 +1,4 @@ -package ports +package http import ( "github.com/LerianStudio/midaz/common/mlog" diff --git a/components/transaction/internal/ports/http/routes.go b/components/transaction/internal/ports/http/routes.go index 2396ae0a..1b1df3b7 100644 --- a/components/transaction/internal/ports/http/routes.go +++ b/components/transaction/internal/ports/http/routes.go @@ -1,43 +1,38 @@ package http import ( + "github.com/LerianStudio/midaz/common/mcasdoor" lib "github.com/LerianStudio/midaz/common/net/http" t "github.com/LerianStudio/midaz/components/transaction/internal/domain/transaction" - "github.com/LerianStudio/midaz/components/transaction/internal/ports" - "github.com/LerianStudio/midaz/components/transaction/internal/service" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" ) -func NewRouter(th *ports.TransactionHandler, oh *ports.OperationHandler) *fiber.App { - f := fiber.New() - - _ = service.NewConfig() +func NewRouter(cc *mcasdoor.CasdoorConnection, th *TransactionHandler, oh *OperationHandler) *fiber.App { + f := fiber.New(fiber.Config{ + DisableStartupMessage: true, + }) f.Use(cors.New()) f.Use(lib.WithCorrelationID()) - - // jwt := lib.NewJWTMiddleware(config.JWKAddress) + jwt := lib.NewJWTMiddleware(cc) // -- Routes -- // Transactions - f.Post("/v1/organizations/:organization_id/ledgers/:ledger_id/transactions", th.CreateTransaction) - f.Patch("/v1/organizations/:organization_id/ledgers/:ledger_id/transactions/:transaction_id", lib.WithBody(new(t.UpdateTransactionInput), th.UpdateTransaction)) - f.Post("/v1/organizations/:organization_id/ledgers/:ledger_id/transactions/:transaction_id/commit", th.CommitTransaction) - f.Post("/v1/organizations/:organization_id/ledgers/:ledger_id/transactions/:transaction_id/revert", th.RevertTransaction) - f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/transactions/:transaction_id", th.GetTransaction) - f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/transactions", th.GetAllTTransactions) + f.Post("/v1/organizations/:organization_id/ledgers/:ledger_id/transactions", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("transactions"), th.CreateTransaction) + f.Patch("/v1/organizations/:organization_id/ledgers/:ledger_id/transactions/:transaction_id", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("transactions"), lib.WithBody(new(t.UpdateTransactionInput), th.UpdateTransaction)) + f.Post("/v1/organizations/:organization_id/ledgers/:ledger_id/transactions/:transaction_id/commit", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("transactions"), th.CommitTransaction) + f.Post("/v1/organizations/:organization_id/ledgers/:ledger_id/transactions/:transaction_id/revert", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("transactions"), th.RevertTransaction) + f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/transactions/:transaction_id", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("transactions"), th.GetTransaction) + f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/transactions", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("transactions"), th.GetAllTransactions) // Transactions Templates - f.Post("/v1/organizations/:organization_id/ledgers/:ledger_id/transaction-templates", lib.WithBody(new(t.InputDSL), th.CreateTransactionTemplate)) - - // f.Put("/v1/organizations/:organization_id/ledgers/:ledger_id/transaction-templates/:code", nil) - // f.Delete("/v1/organizations/:organization_id/ledgers/:ledger_id/transaction-templates/:code", nil) + f.Post("/v1/organizations/:organization_id/ledgers/:ledger_id/transaction-templates", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("transaction-templates"), lib.WithBody(new(t.InputDSL), th.CreateTransactionTemplate)) // Operations - f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/accounts/:account_id/operations", oh.GetAllOperationsByAccount) - f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/portfolios/:portfolio_id/operations", oh.GetAllOperationsByPortfolio) + f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/accounts/:account_id/operations", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("operations"), oh.GetAllOperationsByAccount) + f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/portfolios/:portfolio_id/operations", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("operations"), oh.GetAllOperationsByPortfolio) // f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/portfolios/:portfolio_id/operations/:operation_id", nil) // f.Patch("/v1/organizations/:organization_id/ledgers/:ledger_id/transactions/:transaction_id/operations/:operation_id", nil) diff --git a/components/transaction/internal/ports/transaction.go b/components/transaction/internal/ports/http/transaction.go similarity index 97% rename from components/transaction/internal/ports/transaction.go rename to components/transaction/internal/ports/http/transaction.go index 590077be..bd310a0a 100644 --- a/components/transaction/internal/ports/transaction.go +++ b/components/transaction/internal/ports/http/transaction.go @@ -1,4 +1,4 @@ -package ports +package http import ( "context" @@ -188,7 +188,7 @@ func (handler *TransactionHandler) GetTransaction(c *fiber.Ctx) error { return commonHTTP.OK(c, tran) } -func (handler *TransactionHandler) GetAllTTransactions(c *fiber.Ctx) error { +func (handler *TransactionHandler) GetAllTransactions(c *fiber.Ctx) error { ctx := c.UserContext() logger := mlog.NewLoggerFromContext(c.UserContext()) @@ -252,7 +252,7 @@ func (handler *TransactionHandler) getAccounts(c context.Context, logger mlog.Lo var accounts []*account.Account if len(ids) > 0 { - gRPCAccounts, err := handler.Query.AccountGRPCRepo.GetAccountsByIds(c, ids) + gRPCAccounts, err := handler.Query.AccountGRPCRepo.GetAccountsByIds(c, "", ids) if err != nil { logger.Error("Failed to get account gRPC by ids on Ledger", err.Error()) return nil, err @@ -262,7 +262,7 @@ func (handler *TransactionHandler) getAccounts(c context.Context, logger mlog.Lo } if len(aliases) > 0 { - gRPCAccounts, err := handler.Query.AccountGRPCRepo.GetAccountsByAlias(c, aliases) + gRPCAccounts, err := handler.Query.AccountGRPCRepo.GetAccountsByAlias(c, "", aliases) if err != nil { logger.Error("Failed to get account by alias gRPC on Ledger", err.Error()) return nil, err @@ -297,7 +297,7 @@ func (handler *TransactionHandler) processAccounts(c context.Context, logger mlo return err } - acc, err := handler.Command.AccountGRPCRepo.UpdateAccounts(c, update) + acc, err := handler.Command.AccountGRPCRepo.UpdateAccounts(c, "", update) if err != nil { logger.Error("Failed to update accounts gRPC on Ledger", err.Error()) return err diff --git a/components/transaction/internal/service/config.go b/components/transaction/internal/service/config.go index 8e34cb15..6c5faf10 100644 --- a/components/transaction/internal/service/config.go +++ b/components/transaction/internal/service/config.go @@ -6,25 +6,32 @@ import ( // Config is the top level configuration struct for the entire application. type Config struct { - EnvName string `env:"ENV_NAME"` - ServerAddress string `env:"SERVER_ADDRESS"` - PrimaryDBHost string `env:"DB_HOST"` - PrimaryDBUser string `env:"DB_USER"` - PrimaryDBPassword string `env:"DB_PASSWORD"` - PrimaryDBName string `env:"DB_NAME"` - PrimaryDBPort string `env:"DB_PORT"` - ReplicaDBHost string `env:"DB_REPLICA_HOST"` - ReplicaDBUser string `env:"DB_REPLICA_USER"` - ReplicaDBPassword string `env:"DB_REPLICA_PASSWORD"` - ReplicaDBName string `env:"DB_REPLICA_NAME"` - ReplicaDBPort string `env:"DB_REPLICA_PORT"` - MongoDBHost string `env:"MONGO_HOST"` - MongoDBName string `env:"MONGO_NAME"` - MongoDBUser string `env:"MONGO_USER"` - MongoDBPassword string `env:"MONGO_PASSWORD"` - MongoDBPort string `env:"MONGO_PORT"` - LedgerGRPCAddr string `env:"LEDGER_GRPC_ADDR"` - LedgerGRPCPort string `env:"LEDGER_GRPC_PORT"` + EnvName string `env:"ENV_NAME"` + ServerAddress string `env:"SERVER_ADDRESS"` + PrimaryDBHost string `env:"DB_HOST"` + PrimaryDBUser string `env:"DB_USER"` + PrimaryDBPassword string `env:"DB_PASSWORD"` + PrimaryDBName string `env:"DB_NAME"` + PrimaryDBPort string `env:"DB_PORT"` + ReplicaDBHost string `env:"DB_REPLICA_HOST"` + ReplicaDBUser string `env:"DB_REPLICA_USER"` + ReplicaDBPassword string `env:"DB_REPLICA_PASSWORD"` + ReplicaDBName string `env:"DB_REPLICA_NAME"` + ReplicaDBPort string `env:"DB_REPLICA_PORT"` + MongoDBHost string `env:"MONGO_HOST"` + MongoDBName string `env:"MONGO_NAME"` + MongoDBUser string `env:"MONGO_USER"` + MongoDBPassword string `env:"MONGO_PASSWORD"` + MongoDBPort string `env:"MONGO_PORT"` + LedgerGRPCAddr string `env:"LEDGER_GRPC_ADDR"` + LedgerGRPCPort string `env:"LEDGER_GRPC_PORT"` + CasdoorAddress string `env:"CASDOOR_ADDRESS"` + CasdoorClientID string `env:"CASDOOR_CLIENT_ID"` + CasdoorClientSecret string `env:"CASDOOR_CLIENT_SECRET"` + CasdoorOrganizationName string `env:"CASDOOR_ORGANIZATION_NAME"` + CasdoorApplicationName string `env:"CASDOOR_APPLICATION_NAME"` + CasdoorEnforcerName string `env:"CASDOOR_ENFORCER_NAME"` + JWKAddress string `env:"CASDOOR_JWK_ADDRESS"` } // NewConfig creates an instance of Config. diff --git a/go.sum b/go.sum index a7df012a..a4ec2307 100644 --- a/go.sum +++ b/go.sum @@ -104,6 +104,7 @@ github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/subcommands v1.2.0 h1:vWQspBTo2nEqTUFita5/KeEWlUL8kQObDFbub/EN9oE= github.com/google/subcommands v1.2.0/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= From 74ae594c2a2f69761958bb53a619afaa7d7c0d55 Mon Sep 17 00:00:00 2001 From: MartinezAvellan Date: Mon, 14 Oct 2024 18:50:36 +0200 Subject: [PATCH 2/8] refactor: update fetch to use fiber context; use commons validate string; move getheadertoken to http utils; :hammer: --- common/net/http/httputils.go | 10 ++++++++++ common/net/http/withJWT.go | 15 +++------------ 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/common/net/http/httputils.go b/common/net/http/httputils.go index f29e9e26..dc976409 100644 --- a/common/net/http/httputils.go +++ b/common/net/http/httputils.go @@ -127,3 +127,13 @@ func GetFileFromHeader(ctx *fiber.Ctx) (string, error) { return fileString, nil } + +// GetTokenHeader func that get token from header +func GetTokenHeader(c *fiber.Ctx) string { + splitToken := strings.Split(c.Get(fiber.HeaderAuthorization), "Bearer") + if len(splitToken) == 2 { + return strings.TrimSpace(splitToken[1]) + } + + return "" +} diff --git a/common/net/http/withJWT.go b/common/net/http/withJWT.go index 7f6da34c..0f1f5e1f 100644 --- a/common/net/http/withJWT.go +++ b/common/net/http/withJWT.go @@ -111,15 +111,6 @@ func convertGroups(groups []any) []string { return newGroups } -func getTokenHeader(c *fiber.Ctx) string { - splitToken := strings.Split(c.Get(fiber.HeaderAuthorization), "Bearer") - if len(splitToken) == 2 { - return strings.TrimSpace(splitToken[1]) - } - - return "" -} - func getTokenHeaderFromContext(ctx context.Context) string { md, ok := metadata.FromIncomingContext(ctx) if !ok { @@ -234,9 +225,9 @@ func (jwtm *JWTMiddleware) ProtectHTTP() fiber.Handler { l.Debug("Read token from header") - tokenString := getTokenHeader(c) + tokenString := GetTokenHeader(c) - if len(tokenString) == 0 { + if common.IsNilOrEmpty(&tokenString) { msg := errors.Wrap(errors.New("token not found in context"), "No token found in context") l.Error(msg.Error()) @@ -245,7 +236,7 @@ func (jwtm *JWTMiddleware) ProtectHTTP() fiber.Handler { l.Debugf("Get JWK keys using %s", jwtm.JWK.URI) - keySet, err := jwtm.JWK.Fetch(context.Background()) + keySet, err := jwtm.JWK.Fetch(c.Context()) if err != nil { msg := errors.Wrap(err, "Couldn't load JWK keys from source") l.Error(msg.Error()) From d593b9d9dff22b84261266fdbbdc582bae27f920 Mon Sep 17 00:00:00 2001 From: MartinezAvellan Date: Mon, 14 Oct 2024 18:51:30 +0200 Subject: [PATCH 3/8] refactor: update docker app-tier network name to midaz-network :hammer: --- components/auth/docker-compose.yml | 10 +++++----- components/ledger/docker-compose.yml | 14 +++++++------- components/transaction/docker-compose.yml | 12 ++++++------ 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/components/auth/docker-compose.yml b/components/auth/docker-compose.yml index a539fa48..74b8a953 100644 --- a/components/auth/docker-compose.yml +++ b/components/auth/docker-compose.yml @@ -5,7 +5,7 @@ x-postgres-common: env_file: - .env networks: - - app-tier + - midaz_network services: casdoor: @@ -21,7 +21,7 @@ services: casdoor-db: condition: service_healthy networks: - - app-tier + - midaz_network casdoor-db: <<: *postgres-common @@ -43,6 +43,6 @@ services: retries: 5 networks: - app-tier: - driver: bridge - name: app-tier \ No newline at end of file + midaz_network: + name: midaz_network + driver: bridge \ No newline at end of file diff --git a/components/ledger/docker-compose.yml b/components/ledger/docker-compose.yml index 62bc2c55..ec89e8c7 100644 --- a/components/ledger/docker-compose.yml +++ b/components/ledger/docker-compose.yml @@ -9,7 +9,7 @@ x-postgres-ledger-common: timeout: 5s retries: 5 networks: - - app-tier + - midaz_network x-mongodb-common: &mongodb-common @@ -21,7 +21,7 @@ x-mongodb-common: timeout: 5s retries: 5 networks: - - app-tier + - midaz_network x-redis-common: &redis-common @@ -29,7 +29,7 @@ x-redis-common: env_file: - .env networks: - - app-tier + - midaz_network services: ledger: @@ -59,7 +59,7 @@ services: replica-ledger: condition: service_healthy networks: - - app-tier + - midaz_network mongodb: <<: *mongodb-common @@ -135,6 +135,6 @@ volumes: mongodb_data_container: networks: - app-tier: - driver: bridge - name: app-tier \ No newline at end of file + midaz_network: + name: midaz_network + driver: bridge \ No newline at end of file diff --git a/components/transaction/docker-compose.yml b/components/transaction/docker-compose.yml index 046151d4..9ac17010 100644 --- a/components/transaction/docker-compose.yml +++ b/components/transaction/docker-compose.yml @@ -9,7 +9,7 @@ x-postgres-transaction-common: timeout: 5s retries: 5 networks: - - app-tier + - midaz_network x-mongodb-common: &mongodb-common @@ -21,7 +21,7 @@ x-mongodb-common: timeout: 5s retries: 5 networks: - - app-tier + - midaz_network services: transaction: @@ -47,7 +47,7 @@ services: replica-transaction: condition: service_healthy networks: - - app-tier + - midaz_network mongodb: <<: *mongodb-common @@ -175,6 +175,6 @@ volumes: mongodb_data_container: networks: - app-tier: - driver: bridge - name: app-tier \ No newline at end of file + midaz_network: + name: midaz_network + driver: bridge \ No newline at end of file From 909eb23613df8b284190fa490802239dcd256ebc Mon Sep 17 00:00:00 2001 From: MartinezAvellan Date: Mon, 14 Oct 2024 18:52:09 +0200 Subject: [PATCH 4/8] fix: accept only @external accounts to be negative values :bug: --- components/transaction/internal/domain/account/validations.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/transaction/internal/domain/account/validations.go b/components/transaction/internal/domain/account/validations.go index 6203cbc2..60bac4a4 100644 --- a/components/transaction/internal/domain/account/validations.go +++ b/components/transaction/internal/domain/account/validations.go @@ -32,7 +32,7 @@ type Responses struct { // ValidateAccounts function with some validates in accounts and DSL operations func ValidateAccounts(validate Responses, accounts []*a.Account) error { for _, acc := range accounts { - if acc.Balance.Available == 0 { + if acc.Balance.Available <= 0 && !strings.Contains(acc.Alias, "@external") { return common.ValidationError{ Code: "0025", Title: "Insuficient balance", From b1fc617c95a1aecfefd35a48ef6f069b08397e77 Mon Sep 17 00:00:00 2001 From: MartinezAvellan Date: Mon, 14 Oct 2024 18:52:40 +0200 Subject: [PATCH 5/8] feat: implement token to call grpc :sparkles: --- .../internal/ports/http/transaction.go | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/components/transaction/internal/ports/http/transaction.go b/components/transaction/internal/ports/http/transaction.go index bd310a0a..ffeb1183 100644 --- a/components/transaction/internal/ports/http/transaction.go +++ b/components/transaction/internal/ports/http/transaction.go @@ -72,7 +72,9 @@ func (handler *TransactionHandler) CreateTransaction(c *fiber.Ctx) error { return commonHTTP.WithError(c, err) } - accounts, err := handler.getAccounts(c.Context(), logger, validate.Aliases) + token := commonHTTP.GetTokenHeader(c) + + accounts, err := handler.getAccounts(c.Context(), logger, token, validate.Aliases) if err != nil { return commonHTTP.WithError(c, err) } @@ -105,7 +107,7 @@ func (handler *TransactionHandler) CreateTransaction(c *fiber.Ctx) error { return commonHTTP.WithError(c, err) } - err = handler.processAccounts(c.Context(), logger, *validate, accounts) + err = handler.processAccounts(c.Context(), logger, token, *validate, accounts) if err != nil { return commonHTTP.WithError(c, err) } @@ -236,7 +238,7 @@ func (handler *TransactionHandler) GetAllTransactions(c *fiber.Ctx) error { } // getAccounts is a function that split aliases and ids, call the properly function and return Accounts -func (handler *TransactionHandler) getAccounts(c context.Context, logger mlog.Logger, input []string) ([]*account.Account, error) { +func (handler *TransactionHandler) getAccounts(c context.Context, logger mlog.Logger, token string, input []string) ([]*account.Account, error) { var ids []string var aliases []string @@ -252,7 +254,7 @@ func (handler *TransactionHandler) getAccounts(c context.Context, logger mlog.Lo var accounts []*account.Account if len(ids) > 0 { - gRPCAccounts, err := handler.Query.AccountGRPCRepo.GetAccountsByIds(c, "", ids) + gRPCAccounts, err := handler.Query.AccountGRPCRepo.GetAccountsByIds(c, token, ids) if err != nil { logger.Error("Failed to get account gRPC by ids on Ledger", err.Error()) return nil, err @@ -262,7 +264,7 @@ func (handler *TransactionHandler) getAccounts(c context.Context, logger mlog.Lo } if len(aliases) > 0 { - gRPCAccounts, err := handler.Query.AccountGRPCRepo.GetAccountsByAlias(c, "", aliases) + gRPCAccounts, err := handler.Query.AccountGRPCRepo.GetAccountsByAlias(c, token, aliases) if err != nil { logger.Error("Failed to get account by alias gRPC on Ledger", err.Error()) return nil, err @@ -275,7 +277,7 @@ func (handler *TransactionHandler) getAccounts(c context.Context, logger mlog.Lo } // processAccounts is a function that adjust balance on Accounts -func (handler *TransactionHandler) processAccounts(c context.Context, logger mlog.Logger, validate v.Responses, accounts []*account.Account) error { +func (handler *TransactionHandler) processAccounts(c context.Context, logger mlog.Logger, token string, validate v.Responses, accounts []*account.Account) error { e := make(chan error) result := make(chan []*account.Account) @@ -297,7 +299,7 @@ func (handler *TransactionHandler) processAccounts(c context.Context, logger mlo return err } - acc, err := handler.Command.AccountGRPCRepo.UpdateAccounts(c, "", update) + acc, err := handler.Command.AccountGRPCRepo.UpdateAccounts(c, token, update) if err != nil { logger.Error("Failed to update accounts gRPC on Ledger", err.Error()) return err From ed51df902e852469c29d6b4a9e37f772515ed180 Mon Sep 17 00:00:00 2001 From: MartinezAvellan Date: Mon, 14 Oct 2024 19:00:13 +0200 Subject: [PATCH 6/8] fix: add auth on the new route :bug: --- components/transaction/internal/ports/http/routes.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/transaction/internal/ports/http/routes.go b/components/transaction/internal/ports/http/routes.go index 90f8b089..fadbaa5c 100644 --- a/components/transaction/internal/ports/http/routes.go +++ b/components/transaction/internal/ports/http/routes.go @@ -33,7 +33,7 @@ func NewRouter(cc *mcasdoor.CasdoorConnection, th *TransactionHandler, oh *Opera // Operations f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/accounts/:account_id/operations", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("operations"), oh.GetAllOperationsByAccount) f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/portfolios/:portfolio_id/operations", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("operations"), oh.GetAllOperationsByPortfolio) - f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/accounts/:account_id/operations/:operation_id", oh.GetOperationByAccount) + f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/accounts/:account_id/operations/:operation_id", jwt.ProtectHTTP(), jwt.WithPermissionHTTP("operations"), oh.GetOperationByAccount) // f.Get("/v1/organizations/:organization_id/ledgers/:ledger_id/portfolios/:portfolio_id/operations/:operation_id", nil) // f.Patch("/v1/organizations/:organization_id/ledgers/:ledger_id/transactions/:transaction_id/operations/:operation_id", nil) From c3817748f04cdaa6f4ef299add76767b89c93b3d Mon Sep 17 00:00:00 2001 From: MartinezAvellan Date: Mon, 14 Oct 2024 19:08:44 +0200 Subject: [PATCH 7/8] refactor: update postman :hammer: --- postman/MIDAZ.postman_collection.json | 374 ++++++++------------------ 1 file changed, 107 insertions(+), 267 deletions(-) diff --git a/postman/MIDAZ.postman_collection.json b/postman/MIDAZ.postman_collection.json index 284006c8..1b315688 100644 --- a/postman/MIDAZ.postman_collection.json +++ b/postman/MIDAZ.postman_collection.json @@ -1,10 +1,10 @@ { "info": { - "_postman_id": "85863248-3216-47d3-a390-d3c07d1e5c2b", + "_postman_id": "8e5e00be-8120-4cc4-a7e3-fd52c0f4a06f", "name": "MIDAZ", "description": "# ๐Ÿš€ Get started here\n\nThis template guides you through CRUD operations (GET, POST, PUT, DELETE), variables, and tests.\n\n## ๐Ÿ”– **How to use this template**\n\n#### **Step 1: Send requests**\n\nRESTful APIs allow you to perform CRUD operations using the POST, GET, PUT, and DELETE HTTP methods.\n\nThis collection contains each of these [request](https://learning.postman.com/docs/sending-requests/requests/) types. Open each request and click \"Send\" to see what happens.\n\n#### **Step 2: View responses**\n\nObserve the response tab for status code (200 OK), response time, and size.\n\n#### **Step 3: Send new Body data**\n\nUpdate or add new data in \"Body\" in the POST request. Typically, Body data is also used in PUT request.\n\n```\n{\n \"name\": \"Add your name in the body\"\n}\n\n ```\n\n#### **Step 4: Update the variable**\n\nVariables enable you to store and reuse values in Postman. We have created a [variable](https://learning.postman.com/docs/sending-requests/variables/) called `base_url` with the sample request [https://postman-api-learner.glitch.me](https://postman-api-learner.glitch.me). Replace it with your API endpoint to customize this collection.\n\n#### **Step 5: Add tests in the \"Tests\" tab**\n\nTests help you confirm that your API is working as expected. You can write test scripts in JavaScript and view the output in the \"Test Results\" tab.\n\n\n\n## ๐Ÿ’ช Pro tips\n\n- Use folders to group related requests and organize the collection.\n- Add more [scripts](https://learning.postman.com/docs/writing-scripts/intro-to-scripts/) in \"Tests\" to verify if the API works as expected and execute workflows.\n \n\n## ๐Ÿ’กRelated templates\n\n[API testing basics](https://go.postman.co/redirect/workspace?type=personal&collectionTemplateId=e9a37a28-055b-49cd-8c7e-97494a21eb54&sourceTemplateId=ddb19591-3097-41cf-82af-c84273e56719) \n[API documentation](https://go.postman.co/redirect/workspace?type=personal&collectionTemplateId=e9c28f47-1253-44af-a2f3-20dce4da1f18&sourceTemplateId=ddb19591-3097-41cf-82af-c84273e56719) \n[Authorization methods](https://go.postman.co/redirect/workspace?type=personal&collectionTemplateId=31a9a6ed-4cdf-4ced-984c-d12c9aec1c27&sourceTemplateId=ddb19591-3097-41cf-82af-c84273e56719)", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", - "_exporter_id": "38753084" + "_exporter_id": "32592108" }, "item": [ { @@ -23,7 +23,7 @@ "listen": "test", "script": { "exec": [ - "" + "postman.setEnvironmentVariable(\"access_token\", pm.request.auth.oauth2.get(\"accessToken\"));" ], "type": "text/javascript", "packages": {} @@ -700,38 +700,6 @@ }, "response": [] } - ], - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{access_token}}", - "type": "string" - } - ] - }, - "event": [ - { - "listen": "prerequest", - "script": { - "type": "text/javascript", - "packages": {}, - "exec": [ - "" - ] - } - }, - { - "listen": "test", - "script": { - "type": "text/javascript", - "packages": {}, - "exec": [ - "" - ] - } - } ] }, { @@ -941,38 +909,6 @@ }, "response": [] } - ], - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{access_token}}", - "type": "string" - } - ] - }, - "event": [ - { - "listen": "prerequest", - "script": { - "type": "text/javascript", - "packages": {}, - "exec": [ - "" - ] - } - }, - { - "listen": "test", - "script": { - "type": "text/javascript", - "packages": {}, - "exec": [ - "" - ] - } - } ] }, { @@ -1139,38 +1075,33 @@ } }, "response": [] - } - ], - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{access_token}}", - "type": "string" - } - ] - }, - "event": [ - { - "listen": "prerequest", - "script": { - "type": "text/javascript", - "packages": {}, - "exec": [ - "" - ] - } }, { - "listen": "test", - "script": { - "type": "text/javascript", - "packages": {}, - "exec": [ - "" - ] - } + "name": "Assets", + "request": { + "method": "DELETE", + "header": [], + "body": { + "mode": "formdata", + "formdata": [] + }, + "url": { + "raw": "{{url}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/assets/{{asset_id}}", + "host": [ + "{{url}}" + ], + "path": [ + "v1", + "organizations", + "{{organization_id}}", + "ledgers", + "{{ledger_id}}", + "assets", + "{{asset_id}}" + ] + } + }, + "response": [] } ] }, @@ -1366,38 +1297,6 @@ }, "response": [] } - ], - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{access_token}}", - "type": "string" - } - ] - }, - "event": [ - { - "listen": "prerequest", - "script": { - "type": "text/javascript", - "packages": {}, - "exec": [ - "" - ] - } - }, - { - "listen": "test", - "script": { - "type": "text/javascript", - "packages": {}, - "exec": [ - "" - ] - } - } ] }, { @@ -1599,38 +1498,6 @@ }, "response": [] } - ], - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{access_token}}", - "type": "string" - } - ] - }, - "event": [ - { - "listen": "prerequest", - "script": { - "type": "text/javascript", - "packages": {}, - "exec": [ - "" - ] - } - }, - { - "listen": "test", - "script": { - "type": "text/javascript", - "packages": {}, - "exec": [ - "" - ] - } - } ] }, { @@ -1656,11 +1523,21 @@ } ], "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{access_token}}", + "type": "string" + } + ] + }, "method": "POST", "header": [], "body": { "mode": "raw", - "raw": "{\n \"assetCode\": \"BRL\",\n \"name\": \"{{$randomBankAccountName}}\",\n \"alias\": \"@wallet_{{$randomBankAccount}}\",\n \"type\": \"DEBIT\",\n //\"parentAccountId\": \"{{account_id}}\",\n //\"entityId\": \"{{$randomUUID}}\", //optional\n \"productId\": \"{{product_id}}\",\n \"status\": {\n \"code\": \"CREDIT\",\n \"description\": \"Teste Account\",\n \"allowSending\": true,\n \"allowReceiving\": true\n },\n \"metadata\": {\n \"chave\": \"metadata_chave\",\n \"bitcoinn\": \"{{$randomBitcoin}}\",\n \"boolean\": {{$randomBoolean}},\n \"double\": 10.5,\n \"int\": 1\n }\n}", + "raw": "{\n \"assetCode\": \"BRL\",\n \"name\": \"{{$randomBankAccountName}}\",\n \"alias\": \"@wallet_{{$randomBankAccount}}\",\n \"type\": \"deposit\",\n //\"parentAccountId\": \"{{account_id}}\",\n //\"entityId\": \"{{$randomUUID}}\", //optional\n \"productId\": \"{{product_id}}\",\n \"status\": {\n \"code\": \"CREDIT\",\n \"description\": \"Teste Account\",\n \"allowSending\": true,\n \"allowReceiving\": true\n },\n \"metadata\": {\n \"chave\": \"metadata_chave\",\n \"bitcoinn\": \"{{$randomBitcoin}}\",\n \"boolean\": {{$randomBoolean}},\n \"double\": 10.5,\n \"int\": 1\n }\n}", "options": { "raw": { "language": "json" @@ -1834,65 +1711,6 @@ } }, "response": [] - }, - { - "name": "Accounts by by asset id", - "request": { - "method": "DELETE", - "header": [], - "body": { - "mode": "formdata", - "formdata": [] - }, - "url": { - "raw": "{{url}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/assets/{{asset_id}}", - "host": [ - "{{url}}" - ], - "path": [ - "v1", - "organizations", - "{{organization_id}}", - "ledgers", - "{{ledger_id}}", - "assets", - "{{asset_id}}" - ] - } - }, - "response": [] - } - ], - "auth": { - "type": "bearer", - "bearer": [ - { - "key": "token", - "value": "{{access_token}}", - "type": "string" - } - ] - }, - "event": [ - { - "listen": "prerequest", - "script": { - "type": "text/javascript", - "packages": {}, - "exec": [ - "" - ] - } - }, - { - "listen": "test", - "script": { - "type": "text/javascript", - "packages": {}, - "exec": [ - "" - ] - } } ] }, @@ -1920,7 +1738,19 @@ ], "request": { "method": "POST", - "header": [], + "header": [ + { + "key": "idempotencyKey", + "value": "{{$randomUUID}}", + "type": "text" + }, + { + "key": "tolerance", + "value": "300", + "description": "seconds", + "type": "text" + } + ], "body": { "mode": "formdata", "formdata": [ @@ -2242,10 +2072,36 @@ "response": [] }, { - "name": "Transaction by id", + "name": "transactions", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "const jsonData = JSON.parse(responseBody);", + "if (jsonData.hasOwnProperty('id')) {", + " console.log(\"transaction_id before: \" + postman.getEnvironmentVariable(\"transaction_id\"));", + " postman.setEnvironmentVariable(\"transaction_id\", jsonData.id);", + " console.log(\"transaction_id after: \" + postman.getEnvironmentVariable(\"transaction_id\"));", + "}" + ], + "type": "text/javascript", + "packages": {} + } + } + ], "request": { - "method": "GET", + "method": "PATCH", "header": [], + "body": { + "mode": "raw", + "raw": "{\n \"description\": \"description for the transaction mcgregor to jeff value of 100 reais\",\n \"metadata\": {\n \"mensagem\": \"pagamento\",\n \"valor\": \"100\"\n }\n}", + "options": { + "raw": { + "language": "json" + } + } + }, "url": { "raw": "{{url_transaction}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/transactions/{{transaction_id}}", "host": [ @@ -2260,17 +2116,18 @@ "transactions", "{{transaction_id}}" ] - } + }, + "description": "This is a POST request, submitting data to an API via the request body. This request submits JSON data, and the data is reflected in the response.\n\nA successful POST request typically returns a `200 OK` or `201 Created` response code." }, "response": [] }, { - "name": "Transactions", + "name": "Operation by account", "request": { "method": "GET", "header": [], "url": { - "raw": "{{url_transaction}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/transactions", + "raw": "{{url_transaction}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/accounts/{{account_id}}/operations/{{operation_id}}", "host": [ "{{url_transaction}}" ], @@ -2280,43 +2137,20 @@ "{{organization_id}}", "ledgers", "{{ledger_id}}", - "transactions" + "accounts", + "{{account_id}}", + "operations", + "{{operation_id}}" ] } }, "response": [] }, { - "name": "transactions", - "event": [ - { - "listen": "test", - "script": { - "exec": [ - "const jsonData = JSON.parse(responseBody);", - "if (jsonData.hasOwnProperty('id')) {", - " console.log(\"transaction_id before: \" + postman.getEnvironmentVariable(\"transaction_id\"));", - " postman.setEnvironmentVariable(\"transaction_id\", jsonData.id);", - " console.log(\"transaction_id after: \" + postman.getEnvironmentVariable(\"transaction_id\"));", - "}" - ], - "type": "text/javascript", - "packages": {} - } - } - ], + "name": "Transaction by id", "request": { - "method": "PATCH", + "method": "GET", "header": [], - "body": { - "mode": "raw", - "raw": "{\n \"description\": \"description for the transaction mcgregor to jeff value of 100 reais\",\n \"metadata\": {\n \"mensagem\": \"pagamento\",\n \"valor\": \"100\"\n }\n}", - "options": { - "raw": { - "language": "json" - } - } - }, "url": { "raw": "{{url_transaction}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/transactions/{{transaction_id}}", "host": [ @@ -2331,18 +2165,17 @@ "transactions", "{{transaction_id}}" ] - }, - "description": "This is a POST request, submitting data to an API via the request body. This request submits JSON data, and the data is reflected in the response.\n\nA successful POST request typically returns a `200 OK` or `201 Created` response code." + } }, "response": [] }, { - "name": "Operations by account", + "name": "Transactions", "request": { "method": "GET", "header": [], "url": { - "raw": "{{url_transaction}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/accounts/{{account_id}}/operations", + "raw": "{{url_transaction}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/transactions", "host": [ "{{url_transaction}}" ], @@ -2352,21 +2185,19 @@ "{{organization_id}}", "ledgers", "{{ledger_id}}", - "accounts", - "{{account_id}}", - "operations" + "transactions" ] } }, "response": [] }, { - "name": "Operation by account", + "name": "Operations by account", "request": { "method": "GET", "header": [], "url": { - "raw": "{{url_transaction}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/accounts/{{account_id}}/operations/{{operation_id}}", + "raw": "{{url_transaction}}/v1/organizations/{{organization_id}}/ledgers/{{ledger_id}}/accounts/{{account_id}}/operations", "host": [ "{{url_transaction}}" ], @@ -2378,8 +2209,7 @@ "{{ledger_id}}", "accounts", "{{account_id}}", - "operations", - "{{operation_id}}" + "operations" ] } }, @@ -2412,6 +2242,16 @@ ] } ], + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{access_token}}", + "type": "string" + } + ] + }, "event": [ { "listen": "prerequest", From 1ba33f82cfc9a44e7b92b13b75c064107d656f02 Mon Sep 17 00:00:00 2001 From: MartinezAvellan Date: Mon, 14 Oct 2024 19:22:28 +0200 Subject: [PATCH 8/8] fix: remove fmt.sprintf :bug: --- .../transaction/internal/adapters/grpc/account.grpc.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/components/transaction/internal/adapters/grpc/account.grpc.go b/components/transaction/internal/adapters/grpc/account.grpc.go index 735e4f52..0ac58304 100644 --- a/components/transaction/internal/adapters/grpc/account.grpc.go +++ b/components/transaction/internal/adapters/grpc/account.grpc.go @@ -2,7 +2,6 @@ package grpc import ( "context" - "fmt" "github.com/LerianStudio/midaz/common/mgrpc" proto "github.com/LerianStudio/midaz/common/mgrpc/account" @@ -41,7 +40,7 @@ func (a *AccountGRPCRepository) GetAccountsByIds(ctx context.Context, token stri Ids: ids, } - md := gmtdt.Pairs("authorization", fmt.Sprintf("Bearer %s", token)) + md := gmtdt.Pairs("authorization", "Bearer "+token) ctx = gmtdt.NewOutgoingContext(ctx, md) accountsResponse, err := client.GetAccountsByIds(ctx, accountsID) @@ -65,7 +64,7 @@ func (a *AccountGRPCRepository) GetAccountsByAlias(ctx context.Context, token st Aliases: aliases, } - md := gmtdt.Pairs("authorization", fmt.Sprintf("Bearer %s", token)) + md := gmtdt.Pairs("authorization", "Bearer "+token) ctx = gmtdt.NewOutgoingContext(ctx, md) accountsResponse, err := client.GetAccountsByAliases(ctx, accountsAlias) @@ -89,7 +88,7 @@ func (a *AccountGRPCRepository) UpdateAccounts(ctx context.Context, token string Accounts: accounts, } - md := gmtdt.Pairs("authorization", fmt.Sprintf("Bearer %s", token)) + md := gmtdt.Pairs("authorization", "Bearer "+token) ctx = gmtdt.NewOutgoingContext(ctx, md) accountsResponse, err := client.UpdateAccounts(ctx, accountsRequest)