From dacdd8b5b6a6e911913cf5e5496a2a7fe487a441 Mon Sep 17 00:00:00 2001 From: Manuel Imperiale Date: Wed, 15 Apr 2020 10:44:04 +0200 Subject: [PATCH 1/4] NOISSUE - Fix bootstrap token naming and interfaces named args Signed-off-by: Manuel Imperiale --- bootstrap/api/endpoint.go | 2 +- bootstrap/api/logging.go | 46 +++---- bootstrap/api/metrics.go | 32 ++--- bootstrap/api/requests.go | 4 +- bootstrap/api/requests_test.go | 10 +- bootstrap/api/transport.go | 2 +- bootstrap/configs.go | 36 +++--- bootstrap/mocks/configs.go | 28 ++--- bootstrap/postgres/configs.go | 70 +++++------ bootstrap/postgres/configs_test.go | 30 ++--- bootstrap/redis/producer/streams.go | 32 ++--- bootstrap/redis/producer/streams_test.go | 46 +++---- bootstrap/service.go | 90 ++++++------- bootstrap/service_test.go | 154 +++++++++++------------ 14 files changed, 291 insertions(+), 291 deletions(-) diff --git a/bootstrap/api/endpoint.go b/bootstrap/api/endpoint.go index 1b0d42c249..7a3cdc2fee 100644 --- a/bootstrap/api/endpoint.go +++ b/bootstrap/api/endpoint.go @@ -34,7 +34,7 @@ func addEndpoint(svc bootstrap.Service) endpoint.Endpoint { Content: req.Content, } - saved, err := svc.Add(req.key, config) + saved, err := svc.Add(req.token, config) if err != nil { return nil, err } diff --git a/bootstrap/api/logging.go b/bootstrap/api/logging.go index 5493357e00..e9ed80bda7 100644 --- a/bootstrap/api/logging.go +++ b/bootstrap/api/logging.go @@ -25,9 +25,9 @@ func NewLoggingMiddleware(svc bootstrap.Service, logger log.Logger) bootstrap.Se return &loggingMiddleware{logger, svc} } -func (lm *loggingMiddleware) Add(key string, cfg bootstrap.Config) (saved bootstrap.Config, err error) { +func (lm *loggingMiddleware) Add(token string, cfg bootstrap.Config) (saved bootstrap.Config, err error) { defer func(begin time.Time) { - message := fmt.Sprintf("Method add for key %s and thing %s took %s to complete", key, saved.MFThing, time.Since(begin)) + message := fmt.Sprintf("Method add for token %s and thing %s took %s to complete", token, saved.MFThing, time.Since(begin)) if err != nil { lm.logger.Warn(fmt.Sprintf("%s with error: %s.", message, err)) return @@ -35,12 +35,12 @@ func (lm *loggingMiddleware) Add(key string, cfg bootstrap.Config) (saved bootst lm.logger.Info(fmt.Sprintf("%s without errors.", message)) }(time.Now()) - return lm.svc.Add(key, cfg) + return lm.svc.Add(token, cfg) } -func (lm *loggingMiddleware) View(key, id string) (saved bootstrap.Config, err error) { +func (lm *loggingMiddleware) View(token, id string) (saved bootstrap.Config, err error) { defer func(begin time.Time) { - message := fmt.Sprintf("Method view for key %s and thing %s took %s to complete", key, saved.MFThing, time.Since(begin)) + message := fmt.Sprintf("Method view for token %s and thing %s took %s to complete", token, saved.MFThing, time.Since(begin)) if err != nil { lm.logger.Warn(fmt.Sprintf("%s with error: %s.", message, err)) return @@ -48,12 +48,12 @@ func (lm *loggingMiddleware) View(key, id string) (saved bootstrap.Config, err e lm.logger.Info(fmt.Sprintf("%s without errors.", message)) }(time.Now()) - return lm.svc.View(key, id) + return lm.svc.View(token, id) } -func (lm *loggingMiddleware) Update(key string, cfg bootstrap.Config) (err error) { +func (lm *loggingMiddleware) Update(token string, cfg bootstrap.Config) (err error) { defer func(begin time.Time) { - message := fmt.Sprintf("Method update for key %s and thing %s took %s to complete", key, cfg.MFThing, time.Since(begin)) + message := fmt.Sprintf("Method update for token %s and thing %s took %s to complete", token, cfg.MFThing, time.Since(begin)) if err != nil { lm.logger.Warn(fmt.Sprintf("%s with error: %s.", message, err)) return @@ -61,10 +61,10 @@ func (lm *loggingMiddleware) Update(key string, cfg bootstrap.Config) (err error lm.logger.Info(fmt.Sprintf("%s without errors.", message)) }(time.Now()) - return lm.svc.Update(key, cfg) + return lm.svc.Update(token, cfg) } -func (lm *loggingMiddleware) UpdateCert(key, thingID, clientCert, clientKey, caCert string) (err error) { +func (lm *loggingMiddleware) UpdateCert(token, thingID, clientCert, clientKey, caCert string) (err error) { defer func(begin time.Time) { message := fmt.Sprintf("Method update_cert for thing with id %s took %s to complete", thingID, time.Since(begin)) if err != nil { @@ -74,12 +74,12 @@ func (lm *loggingMiddleware) UpdateCert(key, thingID, clientCert, clientKey, caC lm.logger.Info(fmt.Sprintf("%s without errors.", message)) }(time.Now()) - return lm.svc.UpdateCert(key, thingID, clientCert, clientKey, caCert) + return lm.svc.UpdateCert(token, thingID, clientCert, clientKey, caCert) } -func (lm *loggingMiddleware) UpdateConnections(key, id string, connections []string) (err error) { +func (lm *loggingMiddleware) UpdateConnections(token, id string, connections []string) (err error) { defer func(begin time.Time) { - message := fmt.Sprintf("Method update_connections for key %s and thing %s took %s to complete", key, id, time.Since(begin)) + message := fmt.Sprintf("Method update_connections for token %s and thing %s took %s to complete", token, id, time.Since(begin)) if err != nil { lm.logger.Warn(fmt.Sprintf("%s with error: %s.", message, err)) return @@ -87,12 +87,12 @@ func (lm *loggingMiddleware) UpdateConnections(key, id string, connections []str lm.logger.Info(fmt.Sprintf("%s without errors.", message)) }(time.Now()) - return lm.svc.UpdateConnections(key, id, connections) + return lm.svc.UpdateConnections(token, id, connections) } -func (lm *loggingMiddleware) List(key string, filter bootstrap.Filter, offset, limit uint64) (res bootstrap.ConfigsPage, err error) { +func (lm *loggingMiddleware) List(token string, filter bootstrap.Filter, offset, limit uint64) (res bootstrap.ConfigsPage, err error) { defer func(begin time.Time) { - message := fmt.Sprintf("Method list for key %s and offset %d and limit %d took %s to complete", key, offset, limit, time.Since(begin)) + message := fmt.Sprintf("Method list for token %s and offset %d and limit %d took %s to complete", token, offset, limit, time.Since(begin)) if err != nil { lm.logger.Warn(fmt.Sprintf("%s with error: %s.", message, err)) return @@ -100,12 +100,12 @@ func (lm *loggingMiddleware) List(key string, filter bootstrap.Filter, offset, l lm.logger.Info(fmt.Sprintf("%s without errors.", message)) }(time.Now()) - return lm.svc.List(key, filter, offset, limit) + return lm.svc.List(token, filter, offset, limit) } -func (lm *loggingMiddleware) Remove(key, id string) (err error) { +func (lm *loggingMiddleware) Remove(token, id string) (err error) { defer func(begin time.Time) { - message := fmt.Sprintf("Method remove for key %s and thing %s took %s to complete", key, id, time.Since(begin)) + message := fmt.Sprintf("Method remove for token %s and thing %s took %s to complete", token, id, time.Since(begin)) if err != nil { lm.logger.Warn(fmt.Sprintf("%s with error: %s.", message, err)) return @@ -113,7 +113,7 @@ func (lm *loggingMiddleware) Remove(key, id string) (err error) { lm.logger.Info(fmt.Sprintf("%s without errors.", message)) }(time.Now()) - return lm.svc.Remove(key, id) + return lm.svc.Remove(token, id) } func (lm *loggingMiddleware) Bootstrap(externalKey, externalID string, secure bool) (cfg bootstrap.Config, err error) { @@ -129,9 +129,9 @@ func (lm *loggingMiddleware) Bootstrap(externalKey, externalID string, secure bo return lm.svc.Bootstrap(externalKey, externalID, secure) } -func (lm *loggingMiddleware) ChangeState(key, id string, state bootstrap.State) (err error) { +func (lm *loggingMiddleware) ChangeState(token, id string, state bootstrap.State) (err error) { defer func(begin time.Time) { - message := fmt.Sprintf("Method change_state for key %s and thing %s took %s to complete", key, id, time.Since(begin)) + message := fmt.Sprintf("Method change_state for token %s and thing %s took %s to complete", token, id, time.Since(begin)) if err != nil { lm.logger.Warn(fmt.Sprintf("%s with error: %s.", message, err)) return @@ -139,7 +139,7 @@ func (lm *loggingMiddleware) ChangeState(key, id string, state bootstrap.State) lm.logger.Info(fmt.Sprintf("%s without errors.", message)) }(time.Now()) - return lm.svc.ChangeState(key, id, state) + return lm.svc.ChangeState(token, id, state) } func (lm *loggingMiddleware) UpdateChannelHandler(channel bootstrap.Channel) (err error) { diff --git a/bootstrap/api/metrics.go b/bootstrap/api/metrics.go index 50b61e6781..a578c5702f 100644 --- a/bootstrap/api/metrics.go +++ b/bootstrap/api/metrics.go @@ -30,67 +30,67 @@ func MetricsMiddleware(svc bootstrap.Service, counter metrics.Counter, latency m } } -func (mm *metricsMiddleware) Add(key string, cfg bootstrap.Config) (saved bootstrap.Config, err error) { +func (mm *metricsMiddleware) Add(token string, cfg bootstrap.Config) (saved bootstrap.Config, err error) { defer func(begin time.Time) { mm.counter.With("method", "add").Add(1) mm.latency.With("method", "add").Observe(time.Since(begin).Seconds()) }(time.Now()) - return mm.svc.Add(key, cfg) + return mm.svc.Add(token, cfg) } -func (mm *metricsMiddleware) View(id, key string) (saved bootstrap.Config, err error) { +func (mm *metricsMiddleware) View(token, id string) (saved bootstrap.Config, err error) { defer func(begin time.Time) { mm.counter.With("method", "view").Add(1) mm.latency.With("method", "view").Observe(time.Since(begin).Seconds()) }(time.Now()) - return mm.svc.View(id, key) + return mm.svc.View(token, id) } -func (mm *metricsMiddleware) Update(key string, cfg bootstrap.Config) (err error) { +func (mm *metricsMiddleware) Update(token string, cfg bootstrap.Config) (err error) { defer func(begin time.Time) { mm.counter.With("method", "update").Add(1) mm.latency.With("method", "update").Observe(time.Since(begin).Seconds()) }(time.Now()) - return mm.svc.Update(key, cfg) + return mm.svc.Update(token, cfg) } -func (mm *metricsMiddleware) UpdateCert(key, thingKey, clientCert, clientKey, caCert string) (err error) { +func (mm *metricsMiddleware) UpdateCert(token, thingKey, clientCert, clientKey, caCert string) (err error) { defer func(begin time.Time) { mm.counter.With("method", "update_cert").Add(1) mm.latency.With("method", "update_cert").Observe(time.Since(begin).Seconds()) }(time.Now()) - return mm.svc.UpdateCert(key, thingKey, clientCert, clientKey, caCert) + return mm.svc.UpdateCert(token, thingKey, clientCert, clientKey, caCert) } -func (mm *metricsMiddleware) UpdateConnections(key, id string, connections []string) (err error) { +func (mm *metricsMiddleware) UpdateConnections(token, id string, connections []string) (err error) { defer func(begin time.Time) { mm.counter.With("method", "update_connections").Add(1) mm.latency.With("method", "update_connections").Observe(time.Since(begin).Seconds()) }(time.Now()) - return mm.svc.UpdateConnections(key, id, connections) + return mm.svc.UpdateConnections(token, id, connections) } -func (mm *metricsMiddleware) List(key string, filter bootstrap.Filter, offset, limit uint64) (saved bootstrap.ConfigsPage, err error) { +func (mm *metricsMiddleware) List(token string, filter bootstrap.Filter, offset, limit uint64) (saved bootstrap.ConfigsPage, err error) { defer func(begin time.Time) { mm.counter.With("method", "list").Add(1) mm.latency.With("method", "list").Observe(time.Since(begin).Seconds()) }(time.Now()) - return mm.svc.List(key, filter, offset, limit) + return mm.svc.List(token, filter, offset, limit) } -func (mm *metricsMiddleware) Remove(id, key string) (err error) { +func (mm *metricsMiddleware) Remove(token, id string) (err error) { defer func(begin time.Time) { mm.counter.With("method", "remove").Add(1) mm.latency.With("method", "remove").Observe(time.Since(begin).Seconds()) }(time.Now()) - return mm.svc.Remove(id, key) + return mm.svc.Remove(token, id) } func (mm *metricsMiddleware) Bootstrap(externalKey, externalID string, secure bool) (cfg bootstrap.Config, err error) { @@ -102,13 +102,13 @@ func (mm *metricsMiddleware) Bootstrap(externalKey, externalID string, secure bo return mm.svc.Bootstrap(externalKey, externalID, secure) } -func (mm *metricsMiddleware) ChangeState(id, key string, state bootstrap.State) (err error) { +func (mm *metricsMiddleware) ChangeState(token, id string, state bootstrap.State) (err error) { defer func(begin time.Time) { mm.counter.With("method", "change_state").Add(1) mm.latency.With("method", "change_state").Observe(time.Since(begin).Seconds()) }(time.Now()) - return mm.svc.ChangeState(id, key, state) + return mm.svc.ChangeState(token, id, state) } func (mm *metricsMiddleware) UpdateChannelHandler(channel bootstrap.Channel) (err error) { diff --git a/bootstrap/api/requests.go b/bootstrap/api/requests.go index 9e9361bcec..0157e39d93 100644 --- a/bootstrap/api/requests.go +++ b/bootstrap/api/requests.go @@ -10,7 +10,7 @@ type apiReq interface { } type addReq struct { - key string + token string ThingID string `json:"thing_id"` ExternalID string `json:"external_id"` ExternalKey string `json:"external_key"` @@ -23,7 +23,7 @@ type addReq struct { } func (req addReq) validate() error { - if req.key == "" { + if req.token == "" { return bootstrap.ErrUnauthorizedAccess } diff --git a/bootstrap/api/requests_test.go b/bootstrap/api/requests_test.go index 81a8db08ca..41941f2729 100644 --- a/bootstrap/api/requests_test.go +++ b/bootstrap/api/requests_test.go @@ -11,28 +11,28 @@ import ( func TestAddReqValidation(t *testing.T) { cases := []struct { desc string - key string + token string externalID string externalKey string err error }{ { desc: "empty key", - key: "", + token: "", externalID: "external-id", externalKey: "external-key", err: bootstrap.ErrUnauthorizedAccess, }, { desc: "empty external ID", - key: "key", + token: "token", externalID: "", externalKey: "external-key", err: bootstrap.ErrMalformedEntity, }, { desc: "empty external key", - key: "key", + token: "token", externalID: "external-id", externalKey: "", err: bootstrap.ErrMalformedEntity, @@ -41,7 +41,7 @@ func TestAddReqValidation(t *testing.T) { for _, tc := range cases { req := addReq{ - key: tc.key, + token: tc.token, ExternalID: tc.externalID, ExternalKey: tc.externalKey, } diff --git a/bootstrap/api/transport.go b/bootstrap/api/transport.go index 42fdd598e0..249cd4d357 100644 --- a/bootstrap/api/transport.go +++ b/bootstrap/api/transport.go @@ -119,7 +119,7 @@ func decodeAddRequest(_ context.Context, r *http.Request) (interface{}, error) { return nil, errUnsupportedContentType } - req := addReq{key: r.Header.Get("Authorization")} + req := addReq{token: r.Header.Get("Authorization")} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { return nil, errors.Wrap(bootstrap.ErrMalformedEntity, err) } diff --git a/bootstrap/configs.go b/bootstrap/configs.go index 0bc82aa475..e2204816c4 100644 --- a/bootstrap/configs.go +++ b/bootstrap/configs.go @@ -50,60 +50,60 @@ type ConfigsPage struct { type ConfigRepository interface { // Save persists the Config. Successful operation is indicated by non-nil // error response. - Save(Config, []string) (string, error) + Save(cfg Config, connections []string) (string, error) // RetrieveByID retrieves the Config having the provided identifier, that is owned // by the specified user. - RetrieveByID(string, string) (Config, error) + RetrieveByID(key, id string) (Config, error) // RetrieveAll retrieves a subset of Configs that are owned // by the specific user, with given filter parameters. - RetrieveAll(string, Filter, uint64, uint64) ConfigsPage + RetrieveAll(key string, filter Filter, offset, limit uint64) ConfigsPage // RetrieveByExternalID returns Config for given external ID. - RetrieveByExternalID(string) (Config, error) + RetrieveByExternalID(externalID string) (Config, error) // Update updates an existing Config. A non-nil error is returned // to indicate operation failure. - Update(Config) error + Update(cfg Config) error // UpdateCerts updates an existing Config certificate and key. // A non-nil error is returned to indicate operation failure. - UpdateCert(string, string, string, string, string) error + UpdateCert(owner, thingID, clientCert, clientKey, caCert string) error // UpdateConnections updates a list of Channels the Config is connected to // adding new Channels if needed. - UpdateConnections(string, string, []Channel, []string) error + UpdateConnections(key, id string, channels []Channel, connections []string) error // Remove removes the Config having the provided identifier, that is owned // by the specified user. - Remove(string, string) error + Remove(key, id string) error // ChangeState changes of the Config, that is owned by the specific user. - ChangeState(string, string, State) error + ChangeState(key, id string, state State) error + + // ListExisting retrieves those channels from the given list that exist in DB. + ListExisting(key string, ids []string) ([]Channel, error) // SaveUnknown saves Thing which unsuccessfully bootstrapped. - SaveUnknown(string, string) error + SaveUnknown(key, id string) error // RetrieveUnknown returns a subset of unsuccessfully bootstrapped Things. - RetrieveUnknown(uint64, uint64) ConfigsPage - - // ListExisting retrieves those channels from the given list that exist in DB. - ListExisting(string, []string) ([]Channel, error) + RetrieveUnknown(offset, limit uint64) ConfigsPage // Methods RemoveThing, UpdateChannel, and RemoveChannel are related to // event sourcing. That's why these methods surpass ownership check. // RemoveThing removes Config of the Thing with the given ID. - RemoveThing(string) error + RemoveThing(id string) error // UpdateChannel updates channel with the given ID. - UpdateChannel(Channel) error + UpdateChannel(c Channel) error // RemoveChannel removes channel with the given ID. - RemoveChannel(string) error + RemoveChannel(id string) error // DisconnectHandler changes state of the Config when the corresponding Thing is // disconnected from the Channel. - DisconnectThing(string, string) error + DisconnectThing(channelID, thingID string) error } diff --git a/bootstrap/mocks/configs.go b/bootstrap/mocks/configs.go index 6bac368ce5..5d34a8b763 100644 --- a/bootstrap/mocks/configs.go +++ b/bootstrap/mocks/configs.go @@ -66,7 +66,7 @@ func (crm *configRepositoryMock) Save(config bootstrap.Config, connections []str return config.MFThing, nil } -func (crm *configRepositoryMock) RetrieveByID(key, id string) (bootstrap.Config, error) { +func (crm *configRepositoryMock) RetrieveByID(token, id string) (bootstrap.Config, error) { crm.mu.Lock() defer crm.mu.Unlock() @@ -74,7 +74,7 @@ func (crm *configRepositoryMock) RetrieveByID(key, id string) (bootstrap.Config, if !ok { return bootstrap.Config{}, bootstrap.ErrNotFound } - if c.Owner != key { + if c.Owner != token { return bootstrap.Config{}, bootstrap.ErrUnauthorizedAccess } @@ -82,7 +82,7 @@ func (crm *configRepositoryMock) RetrieveByID(key, id string) (bootstrap.Config, } -func (crm *configRepositoryMock) RetrieveAll(key string, filter bootstrap.Filter, offset, limit uint64) bootstrap.ConfigsPage { +func (crm *configRepositoryMock) RetrieveAll(token string, filter bootstrap.Filter, offset, limit uint64) bootstrap.ConfigsPage { crm.mu.Lock() defer crm.mu.Unlock() @@ -110,7 +110,7 @@ func (crm *configRepositoryMock) RetrieveAll(key string, filter bootstrap.Filter id, _ := strconv.ParseUint(v.MFThing, 10, 64) if (state == emptyState || v.State == state) && (name == "" || strings.Index(strings.ToLower(v.Name), name) != notFoundIdx) && - v.Owner == key { + v.Owner == token { if id >= first && id < last { configs = append(configs, v) } @@ -180,7 +180,7 @@ func (crm *configRepositoryMock) UpdateCert(owner, thingID, clientCert, clientKe return nil } -func (crm *configRepositoryMock) UpdateConnections(key, id string, channels []bootstrap.Channel, connections []string) error { +func (crm *configRepositoryMock) UpdateConnections(token, id string, channels []bootstrap.Channel, connections []string) error { crm.mu.Lock() defer crm.mu.Unlock() @@ -206,12 +206,12 @@ func (crm *configRepositoryMock) UpdateConnections(key, id string, channels []bo return nil } -func (crm *configRepositoryMock) Remove(key, id string) error { +func (crm *configRepositoryMock) Remove(token, id string) error { crm.mu.Lock() defer crm.mu.Unlock() for k, v := range crm.configs { - if v.Owner == key && k == id { + if v.Owner == token && k == id { delete(crm.configs, k) break } @@ -220,7 +220,7 @@ func (crm *configRepositoryMock) Remove(key, id string) error { return nil } -func (crm *configRepositoryMock) ChangeState(key, id string, state bootstrap.State) error { +func (crm *configRepositoryMock) ChangeState(token, id string, state bootstrap.State) error { crm.mu.Lock() defer crm.mu.Unlock() @@ -228,7 +228,7 @@ func (crm *configRepositoryMock) ChangeState(key, id string, state bootstrap.Sta if !ok { return bootstrap.ErrNotFound } - if config.Owner != key { + if config.Owner != token { return bootstrap.ErrUnauthorizedAccess } @@ -268,12 +268,12 @@ func (crm *configRepositoryMock) RetrieveUnknown(offset, limit uint64) bootstrap } } -func (crm *configRepositoryMock) RemoveUnknown(key, id string) error { +func (crm *configRepositoryMock) RemoveUnknown(token, id string) error { crm.mu.Lock() defer crm.mu.Unlock() for k, v := range crm.unknown { - if k == id && v == key { + if k == id && v == token { delete(crm.unknown, k) return nil } @@ -282,15 +282,15 @@ func (crm *configRepositoryMock) RemoveUnknown(key, id string) error { return nil } -func (crm *configRepositoryMock) SaveUnknown(key, id string) error { +func (crm *configRepositoryMock) SaveUnknown(token, id string) error { crm.mu.Lock() defer crm.mu.Unlock() - crm.unknown[id] = key + crm.unknown[id] = token return nil } -func (crm *configRepositoryMock) ListExisting(key string, connections []string) ([]bootstrap.Channel, error) { +func (crm *configRepositoryMock) ListExisting(token string, connections []string) ([]bootstrap.Channel, error) { crm.mu.Lock() defer crm.mu.Unlock() diff --git a/bootstrap/postgres/configs.go b/bootstrap/postgres/configs.go index a0461b8548..f62df6186e 100644 --- a/bootstrap/postgres/configs.go +++ b/bootstrap/postgres/configs.go @@ -106,17 +106,17 @@ func (cr configRepository) Save(cfg bootstrap.Config, connections []string) (str return cfg.MFThing, nil } -func (cr configRepository) RetrieveByID(key, id string) (bootstrap.Config, error) { - q := `SELECT mainflux_thing, mainflux_key, external_id, external_key, name, content, state - FROM configs +func (cr configRepository) RetrieveByID(token, id string) (bootstrap.Config, error) { + q := `SELECT mainflux_thing, mainflux_key, external_id, external_key, name, content, state + FROM configs WHERE mainflux_thing = $1 AND owner = $2` dbcfg := dbConfig{ MFThing: id, - Owner: key, + Owner: token, } - if err := cr.db.QueryRowx(q, id, key).StructScan(&dbcfg); err != nil { + if err := cr.db.QueryRowx(q, id, token).StructScan(&dbcfg); err != nil { empty := bootstrap.Config{} if err == sql.ErrNoRows { return empty, errors.Wrap(bootstrap.ErrNotFound, err) @@ -159,8 +159,8 @@ func (cr configRepository) RetrieveByID(key, id string) (bootstrap.Config, error return cfg, nil } -func (cr configRepository) RetrieveAll(key string, filter bootstrap.Filter, offset, limit uint64) bootstrap.ConfigsPage { - search, params := cr.retrieveAll(key, filter) +func (cr configRepository) RetrieveAll(token string, filter bootstrap.Filter, offset, limit uint64) bootstrap.ConfigsPage { + search, params := cr.retrieveAll(token, filter) n := len(params) q := `SELECT mainflux_thing, mainflux_key, external_id, external_key, name, content, state @@ -178,7 +178,7 @@ func (cr configRepository) RetrieveAll(key string, filter bootstrap.Filter, offs configs := []bootstrap.Config{} for rows.Next() { - c := bootstrap.Config{Owner: key} + c := bootstrap.Config{Owner: token} if err := rows.Scan(&c.MFThing, &c.MFKey, &c.ExternalID, &c.ExternalKey, &name, &content, &c.State); err != nil { cr.log.Error(fmt.Sprintf("Failed to read retrieved config due to %s", err)) return bootstrap.ConfigsPage{} @@ -206,8 +206,8 @@ func (cr configRepository) RetrieveAll(key string, filter bootstrap.Filter, offs } func (cr configRepository) RetrieveByExternalID(externalID string) (bootstrap.Config, error) { - q := `SELECT mainflux_thing, mainflux_key, external_key, owner, name, client_cert, client_key, ca_cert, content, state - FROM configs + q := `SELECT mainflux_thing, mainflux_key, external_key, owner, name, client_cert, client_key, ca_cert, content, state + FROM configs WHERE external_id = $1` dbcfg := dbConfig{ ExternalID: externalID, @@ -299,19 +299,19 @@ func (cr configRepository) UpdateCert(owner, thingID, clientCert, clientKey, caC return nil } -func (cr configRepository) UpdateConnections(key, id string, channels []bootstrap.Channel, connections []string) error { +func (cr configRepository) UpdateConnections(token, id string, channels []bootstrap.Channel, connections []string) error { tx, err := cr.db.Beginx() if err != nil { return err } - if err := insertChannels(key, channels, tx); err != nil { + if err := insertChannels(token, channels, tx); err != nil { cr.rollback("Failed to insert Channels during the update", tx, err) return err } - if err := updateConnections(key, id, connections, tx); err != nil { + if err := updateConnections(token, id, connections, tx); err != nil { if e, ok := err.(*pq.Error); ok { if e.Code.Name() == fkViolation && e.Constraint == connConstraintErr { return bootstrap.ErrNotFound @@ -329,9 +329,9 @@ func (cr configRepository) UpdateConnections(key, id string, channels []bootstra return nil } -func (cr configRepository) Remove(key, id string) error { +func (cr configRepository) Remove(token, id string) error { q := `DELETE FROM configs WHERE mainflux_thing = $1 AND owner = $2` - if _, err := cr.db.Exec(q, id, key); err != nil { + if _, err := cr.db.Exec(q, id, token); err != nil { return errors.Wrap(errRemove, err) } @@ -342,10 +342,10 @@ func (cr configRepository) Remove(key, id string) error { return nil } -func (cr configRepository) ChangeState(key, id string, state bootstrap.State) error { +func (cr configRepository) ChangeState(token, id string, state bootstrap.State) error { q := `UPDATE configs SET state = $1 WHERE mainflux_thing = $2 AND owner = $3;` - res, err := cr.db.Exec(q, state, id, key) + res, err := cr.db.Exec(q, state, id, token) if err != nil { return err } @@ -362,14 +362,14 @@ func (cr configRepository) ChangeState(key, id string, state bootstrap.State) er return nil } -func (cr configRepository) ListExisting(key string, ids []string) ([]bootstrap.Channel, error) { +func (cr configRepository) ListExisting(token string, ids []string) ([]bootstrap.Channel, error) { var channels []bootstrap.Channel if len(ids) == 0 { return channels, nil } q := "SELECT mainflux_channel, name, metadata FROM channels WHERE owner = $1 AND mainflux_channel = ANY ($2)" - rows, err := cr.db.Queryx(q, key, pq.Array(ids)) + rows, err := cr.db.Queryx(q, token, pq.Array(ids)) if err != nil { return []bootstrap.Channel{}, err } @@ -393,10 +393,10 @@ func (cr configRepository) ListExisting(key string, ids []string) ([]bootstrap.C return channels, nil } -func (cr configRepository) SaveUnknown(key, id string) error { +func (cr configRepository) SaveUnknown(token, id string) error { q := `INSERT INTO unknown_configs (external_id, external_key) VALUES ($1, $2)` - if _, err := cr.db.Exec(q, id, key); err != nil { + if _, err := cr.db.Exec(q, id, token); err != nil { if pqErr, ok := err.(*pq.Error); ok && pqErr.Code.Name() == duplicateErr { return nil } @@ -455,8 +455,8 @@ func (cr configRepository) RemoveThing(id string) error { return nil } -func (cr configRepository) UpdateChannel(channel bootstrap.Channel) error { - dbch, err := toDBChannel("", channel) +func (cr configRepository) UpdateChannel(c bootstrap.Channel) error { + dbch, err := toDBChannel("", c) if err != nil { return err } @@ -485,12 +485,12 @@ func (cr configRepository) DisconnectThing(channelID, thingID string) error { return nil } -func (cr configRepository) retrieveAll(key string, filter bootstrap.Filter) (string, []interface{}) { +func (cr configRepository) retrieveAll(token string, filter bootstrap.Filter) (string, []interface{}) { template := `WHERE owner = $1 %s` - params := []interface{}{key} + params := []interface{}{token} // One empty string so that strings Join works if only one filter is applied. queries := []string{""} - // Since key is the first param, start from 2. + // Since token is the first param, start from 2. counter := 2 for k, v := range filter.FullMatch { queries = append(queries, fmt.Sprintf("%s = $%d", k, counter)) @@ -516,21 +516,21 @@ func (cr configRepository) rollback(content string, tx *sqlx.Tx, err error) { } } -func insertChannels(key string, channels []bootstrap.Channel, tx *sqlx.Tx) error { +func insertChannels(token string, channels []bootstrap.Channel, tx *sqlx.Tx) error { if len(channels) == 0 { return nil } var chans []dbChannel for _, ch := range channels { - dbch, err := toDBChannel(key, ch) + dbch, err := toDBChannel(token, ch) if err != nil { return err } chans = append(chans, dbch) } - q := `INSERT INTO channels (mainflux_channel, owner, name, metadata) + q := `INSERT INTO channels (mainflux_channel, owner, name, metadata) VALUES (:mainflux_channel, :owner, :name, :metadata)` if _, err := tx.NamedExec(q, chans); err != nil { e := err @@ -548,7 +548,7 @@ func insertConnections(cfg bootstrap.Config, connections []string, tx *sqlx.Tx) return nil } - q := `INSERT INTO connections (config_id, channel_id, config_owner, channel_owner) + q := `INSERT INTO connections (config_id, channel_id, config_owner, channel_owner) VALUES (:config_id, :channel_id, :config_owner, :channel_owner)` conns := []dbConnection{} for _, conn := range connections { @@ -565,7 +565,7 @@ func insertConnections(cfg bootstrap.Config, connections []string, tx *sqlx.Tx) return err } -func updateConnections(key, id string, connections []string, tx *sqlx.Tx) error { +func updateConnections(token, id string, connections []string, tx *sqlx.Tx) error { if len(connections) == 0 { return nil } @@ -574,7 +574,7 @@ func updateConnections(key, id string, connections []string, tx *sqlx.Tx) error WHERE config_id = $1 AND config_owner = $2 AND channel_owner = $2 AND channel_id NOT IN ($3)` - res, err := tx.Exec(q, id, key, pq.Array(connections)) + res, err := tx.Exec(q, id, token, pq.Array(connections)) if err != nil { return err } @@ -584,7 +584,7 @@ func updateConnections(key, id string, connections []string, tx *sqlx.Tx) error return err } - q = `INSERT INTO connections (config_id, channel_id, config_owner, channel_owner) + q = `INSERT INTO connections (config_id, channel_id, config_owner, channel_owner) VALUES (:config_id, :channel_id, :config_owner, :channel_owner)` conns := []dbConnection{} @@ -592,8 +592,8 @@ func updateConnections(key, id string, connections []string, tx *sqlx.Tx) error dbconn := dbConnection{ Config: id, Channel: conn, - ConfigOwner: key, - ChannelOwner: key, + ConfigOwner: token, + ChannelOwner: token, } conns = append(conns, dbconn) } diff --git a/bootstrap/postgres/configs_test.go b/bootstrap/postgres/configs_test.go index cd9b63ff87..d71f9c9fc9 100644 --- a/bootstrap/postgres/configs_test.go +++ b/bootstrap/postgres/configs_test.go @@ -339,7 +339,7 @@ func TestUpdateCert(t *testing.T) { cases := []struct { desc string - key string + thingID string owner string cert string certKey string @@ -348,7 +348,7 @@ func TestUpdateCert(t *testing.T) { }{ { desc: "update with wrong owner", - key: "", + thingID: "", cert: "cert", certKey: "certKey", ca: "", @@ -357,7 +357,7 @@ func TestUpdateCert(t *testing.T) { }, { desc: "update a config", - key: c.MFKey, + thingID: c.MFThing, cert: "cert", certKey: "certKey", ca: "ca", @@ -366,7 +366,7 @@ func TestUpdateCert(t *testing.T) { }, } for _, tc := range cases { - err := repo.UpdateCert(tc.owner, tc.key, tc.cert, tc.key, tc.ca) + err := repo.UpdateCert(tc.owner, tc.thingID, tc.cert, tc.certKey, tc.ca) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) } } @@ -399,7 +399,7 @@ func TestUpdateConnections(t *testing.T) { cases := []struct { desc string - key string + token string id string channels []bootstrap.Channel connections []string @@ -407,7 +407,7 @@ func TestUpdateConnections(t *testing.T) { }{ { desc: "update connections of non-existing config", - key: config.Owner, + token: config.Owner, id: "unknown", channels: nil, connections: []string{channels[1]}, @@ -415,7 +415,7 @@ func TestUpdateConnections(t *testing.T) { }, { desc: "update connections", - key: config.Owner, + token: config.Owner, id: c.MFThing, channels: nil, connections: []string{channels[1]}, @@ -423,7 +423,7 @@ func TestUpdateConnections(t *testing.T) { }, { desc: "update connections with existing channels", - key: config.Owner, + token: config.Owner, id: c2, channels: nil, connections: channels, @@ -431,7 +431,7 @@ func TestUpdateConnections(t *testing.T) { }, { desc: "update connections no channels", - key: config.Owner, + token: config.Owner, id: c.MFThing, channels: nil, connections: nil, @@ -439,7 +439,7 @@ func TestUpdateConnections(t *testing.T) { }, } for _, tc := range cases { - err := repo.UpdateConnections(tc.key, tc.id, tc.channels, tc.connections) + err := repo.UpdateConnections(tc.token, tc.id, tc.channels, tc.connections) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) } } @@ -550,31 +550,31 @@ func TestListExisting(t *testing.T) { cases := []struct { desc string - key string + token string connections []string existing []bootstrap.Channel }{ { desc: "list all existing channels", - key: c.Owner, + token: c.Owner, connections: channels, existing: chs, }, { desc: "list a subset of existing channels", - key: c.Owner, + token: c.Owner, connections: []string{channels[0], "5"}, existing: []bootstrap.Channel{chs[0]}, }, { desc: "list a subset of existing channels empty", - key: c.Owner, + token: c.Owner, connections: []string{"5", "6"}, existing: []bootstrap.Channel{}, }, } for _, tc := range cases { - existing, err := repo.ListExisting(tc.key, tc.connections) + existing, err := repo.ListExisting(tc.token, tc.connections) assert.Nil(t, err, fmt.Sprintf("%s: unexpected error: %s", tc.desc, err)) assert.ElementsMatch(t, tc.existing, existing, fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.existing, existing)) } diff --git a/bootstrap/redis/producer/streams.go b/bootstrap/redis/producer/streams.go index 7517a5e28a..484bd2b95f 100644 --- a/bootstrap/redis/producer/streams.go +++ b/bootstrap/redis/producer/streams.go @@ -31,8 +31,8 @@ func NewEventStoreMiddleware(svc bootstrap.Service, client *redis.Client) bootst } } -func (es eventStore) Add(key string, cfg bootstrap.Config) (bootstrap.Config, error) { - saved, err := es.svc.Add(key, cfg) +func (es eventStore) Add(token string, cfg bootstrap.Config) (bootstrap.Config, error) { + saved, err := es.svc.Add(token, cfg) if err != nil { return saved, err } @@ -57,12 +57,12 @@ func (es eventStore) Add(key string, cfg bootstrap.Config) (bootstrap.Config, er return saved, err } -func (es eventStore) View(key, id string) (bootstrap.Config, error) { - return es.svc.View(key, id) +func (es eventStore) View(token, id string) (bootstrap.Config, error) { + return es.svc.View(token, id) } -func (es eventStore) Update(key string, cfg bootstrap.Config) error { - if err := es.svc.Update(key, cfg); err != nil { +func (es eventStore) Update(token string, cfg bootstrap.Config) error { + if err := es.svc.Update(token, cfg); err != nil { return err } @@ -78,12 +78,12 @@ func (es eventStore) Update(key string, cfg bootstrap.Config) error { return nil } -func (es eventStore) UpdateCert(key, thingKey, clientCert, clientKey, caCert string) error { - return es.svc.UpdateCert(key, thingKey, clientCert, clientKey, caCert) +func (es eventStore) UpdateCert(token, thingKey, clientCert, clientKey, caCert string) error { + return es.svc.UpdateCert(token, thingKey, clientCert, clientKey, caCert) } -func (es eventStore) UpdateConnections(key, id string, connections []string) error { - if err := es.svc.UpdateConnections(key, id, connections); err != nil { +func (es eventStore) UpdateConnections(token, id string, connections []string) error { + if err := es.svc.UpdateConnections(token, id, connections); err != nil { return err } @@ -98,12 +98,12 @@ func (es eventStore) UpdateConnections(key, id string, connections []string) err return nil } -func (es eventStore) List(key string, filter bootstrap.Filter, offset, limit uint64) (bootstrap.ConfigsPage, error) { - return es.svc.List(key, filter, offset, limit) +func (es eventStore) List(token string, filter bootstrap.Filter, offset, limit uint64) (bootstrap.ConfigsPage, error) { + return es.svc.List(token, filter, offset, limit) } -func (es eventStore) Remove(key, id string) error { - if err := es.svc.Remove(key, id); err != nil { +func (es eventStore) Remove(token, id string) error { + if err := es.svc.Remove(token, id); err != nil { return err } @@ -135,8 +135,8 @@ func (es eventStore) Bootstrap(externalKey, externalID string, secure bool) (boo return cfg, err } -func (es eventStore) ChangeState(key, id string, state bootstrap.State) error { - if err := es.svc.ChangeState(key, id, state); err != nil { +func (es eventStore) ChangeState(token, id string, state bootstrap.State) error { + if err := es.svc.ChangeState(token, id, state); err != nil { return err } diff --git a/bootstrap/redis/producer/streams_test.go b/bootstrap/redis/producer/streams_test.go index d42c3fdc5d..e980812fdb 100644 --- a/bootstrap/redis/producer/streams_test.go +++ b/bootstrap/redis/producer/streams_test.go @@ -110,14 +110,14 @@ func TestAdd(t *testing.T) { cases := []struct { desc string config bootstrap.Config - key string + token string err error event map[string]interface{} }{ { desc: "create config successfully", config: config, - key: validToken, + token: validToken, err: nil, event: map[string]interface{}{ "thing_id": "1", @@ -133,7 +133,7 @@ func TestAdd(t *testing.T) { { desc: "create invalid config", config: invalidConfig, - key: validToken, + token: validToken, err: bootstrap.ErrMalformedEntity, event: nil, }, @@ -141,7 +141,7 @@ func TestAdd(t *testing.T) { lastID := "0" for _, tc := range cases { - _, err := svc.Add(tc.key, tc.config) + _, err := svc.Add(tc.token, tc.config) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) streams := redisClient.XRead(&redis.XReadArgs{ @@ -205,14 +205,14 @@ func TestUpdate(t *testing.T) { cases := []struct { desc string config bootstrap.Config - key string + token string err error event map[string]interface{} }{ { desc: "update config successfully", config: modified, - key: validToken, + token: validToken, err: nil, event: map[string]interface{}{ "thing_id": modified.MFThing, @@ -225,7 +225,7 @@ func TestUpdate(t *testing.T) { { desc: "update non-existing config", config: nonExisting, - key: validToken, + token: validToken, err: bootstrap.ErrNotFound, event: nil, }, @@ -233,7 +233,7 @@ func TestUpdate(t *testing.T) { lastID := "0" for _, tc := range cases { - err := svc.Update(tc.key, tc.config) + err := svc.Update(tc.token, tc.config) assert.Equal(t, tc.err, err, fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) streams := redisClient.XRead(&redis.XReadArgs{ @@ -268,7 +268,7 @@ func TestUpdateConnections(t *testing.T) { cases := []struct { desc string id string - key string + token string connections []string err error event map[string]interface{} @@ -276,7 +276,7 @@ func TestUpdateConnections(t *testing.T) { { desc: "update connections successfully", id: saved.MFThing, - key: validToken, + token: validToken, connections: []string{"2"}, err: nil, event: map[string]interface{}{ @@ -289,7 +289,7 @@ func TestUpdateConnections(t *testing.T) { { desc: "update connections unsuccessfully", id: saved.MFThing, - key: validToken, + token: validToken, connections: []string{"256"}, err: bootstrap.ErrMalformedEntity, event: nil, @@ -298,7 +298,7 @@ func TestUpdateConnections(t *testing.T) { lastID := "0" for _, tc := range cases { - err := svc.UpdateConnections(tc.key, tc.id, tc.connections) + err := svc.UpdateConnections(tc.token, tc.id, tc.connections) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) streams := redisClient.XRead(&redis.XReadArgs{ @@ -353,15 +353,15 @@ func TestRemove(t *testing.T) { cases := []struct { desc string id string - key string + token string err error event map[string]interface{} }{ { - desc: "remove config successfully", - id: saved.MFThing, - key: validToken, - err: nil, + desc: "remove config successfully", + id: saved.MFThing, + token: validToken, + err: nil, event: map[string]interface{}{ "thing_id": saved.MFThing, "timestamp": time.Now().Unix(), @@ -371,7 +371,7 @@ func TestRemove(t *testing.T) { { desc: "remove config with invalid credentials", id: saved.MFThing, - key: "", + token: "", err: bootstrap.ErrUnauthorizedAccess, event: nil, }, @@ -379,7 +379,7 @@ func TestRemove(t *testing.T) { lastID := "0" for _, tc := range cases { - err := svc.Remove(tc.key, tc.id) + err := svc.Remove(tc.token, tc.id) assert.Equal(t, tc.err, err, fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) streams := redisClient.XRead(&redis.XReadArgs{ @@ -485,7 +485,7 @@ func TestChangeState(t *testing.T) { cases := []struct { desc string id string - key string + token string state bootstrap.State err error event map[string]interface{} @@ -493,7 +493,7 @@ func TestChangeState(t *testing.T) { { desc: "change state to active", id: saved.MFThing, - key: validToken, + token: validToken, state: bootstrap.Active, err: nil, event: map[string]interface{}{ @@ -506,7 +506,7 @@ func TestChangeState(t *testing.T) { { desc: "change state invalid credentials", id: saved.MFThing, - key: "", + token: "", state: bootstrap.Inactive, err: bootstrap.ErrUnauthorizedAccess, event: nil, @@ -515,7 +515,7 @@ func TestChangeState(t *testing.T) { lastID := "0" for _, tc := range cases { - err := svc.ChangeState(tc.key, tc.id, tc.state) + err := svc.ChangeState(tc.token, tc.id, tc.state) assert.Equal(t, tc.err, err, fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) streams := redisClient.XRead(&redis.XReadArgs{ diff --git a/bootstrap/service.go b/bootstrap/service.go index 1e435b6a96..686fdf29b2 100644 --- a/bootstrap/service.go +++ b/bootstrap/service.go @@ -60,34 +60,34 @@ var _ Service = (*bootstrapService)(nil) // Service specifies an API that must be fulfilled by the domain service // implementation, and all of its decorators (e.g. logging & metrics). type Service interface { - // Add adds new Thing Config to the user identified by the provided key. - Add(key string, cfg Config) (Config, error) + // Add adds new Thing Config to the user identified by the provided token. + Add(token string, cfg Config) (Config, error) - // View returns Thing Config with given ID belonging to the user identified by the given key. - View(key, id string) (Config, error) + // View returns Thing Config with given ID belonging to the user identified by the given token. + View(token, id string) (Config, error) // Update updates editable fields of the provided Config. - Update(key string, cfg Config) error + Update(token string, cfg Config) error - // UpdateCert updates an existing Config certificate and key. + // UpdateCert updates an existing Config certificate and token. // A non-nil error is returned to indicate operation failure. - UpdateCert(key, thingID, clientCert, clientKey, caCert string) error + UpdateCert(token, thingID, clientCert, clientKey, caCert string) error // UpdateConnections updates list of Channels related to given Config. - UpdateConnections(key, id string, connections []string) error + UpdateConnections(token, id string, connections []string) error // List returns subset of Configs with given search params that belong to the - // user identified by the given key. - List(key string, filter Filter, offset, limit uint64) (ConfigsPage, error) + // user identified by the given token. + List(token string, filter Filter, offset, limit uint64) (ConfigsPage, error) - // Remove removes Config with specified key that belongs to the user identified by the given key. - Remove(key, id string) error + // Remove removes Config with specified token that belongs to the user identified by the given token. + Remove(token, id string) error - // Bootstrap returns Config to the Thing with provided external ID using external key. + // Bootstrap returns Config to the Thing with provided external ID using external token. Bootstrap(externalKey, externalID string, secure bool) (Config, error) // ChangeState changes state of the Thing with given ID and owner. - ChangeState(key, id string, state State) error + ChangeState(token, id string, state State) error // Methods RemoveConfig, UpdateChannel, and RemoveChannel are used as // handlers for events. That's why these methods surpass ownership check. @@ -131,8 +131,8 @@ func New(auth mainflux.AuthNServiceClient, configs ConfigRepository, sdk mfsdk.S } } -func (bs bootstrapService) Add(key string, cfg Config) (Config, error) { - owner, err := bs.identify(key) +func (bs bootstrapService) Add(token string, cfg Config) (Config, error) { + owner, err := bs.identify(token) if err != nil { return Config{}, err } @@ -145,14 +145,14 @@ func (bs bootstrapService) Add(key string, cfg Config) (Config, error) { return Config{}, errors.Wrap(errCheckChannels, err) } - cfg.MFChannels, err = bs.connectionChannels(toConnect, bs.toIDList(existing), key) + cfg.MFChannels, err = bs.connectionChannels(toConnect, bs.toIDList(existing), token) if err != nil { return Config{}, errors.Wrap(errConnectionChannels, err) } id := cfg.MFThing - mfThing, err := bs.thing(key, id) + mfThing, err := bs.thing(token, id) if err != nil { return Config{}, errors.Wrap(errAddBootstrap, err) } @@ -161,12 +161,12 @@ func (bs bootstrapService) Add(key string, cfg Config) (Config, error) { cfg.Owner = owner cfg.State = Inactive cfg.MFKey = mfThing.Key - saved, err := bs.configs.Save(cfg, toConnect) + saved, err := bs.configs.Save(cfg, toConnect) if err != nil { if id == "" { // Fail silently. - bs.sdk.DeleteThing(cfg.MFThing, key) + bs.sdk.DeleteThing(cfg.MFThing, token) } return Config{}, errors.Wrap(errAddBootstrap, err) } @@ -177,8 +177,8 @@ func (bs bootstrapService) Add(key string, cfg Config) (Config, error) { return cfg, nil } -func (bs bootstrapService) View(key, id string) (Config, error) { - owner, err := bs.identify(key) +func (bs bootstrapService) View(token, id string) (Config, error) { + owner, err := bs.identify(token) if err != nil { return Config{}, err } @@ -186,8 +186,8 @@ func (bs bootstrapService) View(key, id string) (Config, error) { return bs.configs.RetrieveByID(owner, id) } -func (bs bootstrapService) Update(key string, cfg Config) error { - owner, err := bs.identify(key) +func (bs bootstrapService) Update(token string, cfg Config) error { + owner, err := bs.identify(token) if err != nil { return err } @@ -197,8 +197,8 @@ func (bs bootstrapService) Update(key string, cfg Config) error { return bs.configs.Update(cfg) } -func (bs bootstrapService) UpdateCert(key, thingID, clientCert, clientKey, caCert string) error { - owner, err := bs.identify(key) +func (bs bootstrapService) UpdateCert(token, thingID, clientCert, clientKey, caCert string) error { + owner, err := bs.identify(token) if err != nil { return err } @@ -208,8 +208,8 @@ func (bs bootstrapService) UpdateCert(key, thingID, clientCert, clientKey, caCer return nil } -func (bs bootstrapService) UpdateConnections(key, id string, connections []string) error { - owner, err := bs.identify(key) +func (bs bootstrapService) UpdateConnections(token, id string, connections []string) error { + owner, err := bs.identify(token) if err != nil { return err } @@ -227,7 +227,7 @@ func (bs bootstrapService) UpdateConnections(key, id string, connections []strin return errors.Wrap(errUpdateConnections, err) } - channels, err := bs.connectionChannels(connections, bs.toIDList(existing), key) + channels, err := bs.connectionChannels(connections, bs.toIDList(existing), token) if err != nil { return errors.Wrap(errUpdateConnections, err) } @@ -241,7 +241,7 @@ func (bs bootstrapService) UpdateConnections(key, id string, connections []strin } for _, c := range disconnect { - if err := bs.sdk.DisconnectThing(id, c, key); err != nil { + if err := bs.sdk.DisconnectThing(id, c, token); err != nil { if err == mfsdk.ErrNotFound { continue } @@ -254,7 +254,7 @@ func (bs bootstrapService) UpdateConnections(key, id string, connections []strin ChannelIDs: []string{c}, ThingIDs: []string{id}, } - if err := bs.sdk.Connect(conIDs, key); err != nil { + if err := bs.sdk.Connect(conIDs, token); err != nil { if err == mfsdk.ErrNotFound { return ErrMalformedEntity } @@ -265,8 +265,8 @@ func (bs bootstrapService) UpdateConnections(key, id string, connections []strin return bs.configs.UpdateConnections(owner, id, channels, connections) } -func (bs bootstrapService) List(key string, filter Filter, offset, limit uint64) (ConfigsPage, error) { - owner, err := bs.identify(key) +func (bs bootstrapService) List(token string, filter Filter, offset, limit uint64) (ConfigsPage, error) { + owner, err := bs.identify(token) if err != nil { return ConfigsPage{}, err } @@ -278,8 +278,8 @@ func (bs bootstrapService) List(key string, filter Filter, offset, limit uint64) return bs.configs.RetrieveAll(owner, filter, offset, limit), nil } -func (bs bootstrapService) Remove(key, id string) error { - owner, err := bs.identify(key) +func (bs bootstrapService) Remove(token, id string) error { + owner, err := bs.identify(token) if err != nil { return err } @@ -314,8 +314,8 @@ func (bs bootstrapService) Bootstrap(externalKey, externalID string, secure bool return cfg, nil } -func (bs bootstrapService) ChangeState(key, id string, state State) error { - owner, err := bs.identify(key) +func (bs bootstrapService) ChangeState(token, id string, state State) error { + owner, err := bs.identify(token) if err != nil { return err } @@ -336,13 +336,13 @@ func (bs bootstrapService) ChangeState(key, id string, state State) error { ChannelIDs: []string{c.ID}, ThingIDs: []string{cfg.MFThing}, } - if err := bs.sdk.Connect(conIDs, key); err != nil { + if err := bs.sdk.Connect(conIDs, token); err != nil { return ErrThings } } case Inactive: for _, c := range cfg.MFChannels { - if err := bs.sdk.DisconnectThing(cfg.MFThing, c.ID, key); err != nil { + if err := bs.sdk.DisconnectThing(cfg.MFThing, c.ID, token); err != nil { if err == mfsdk.ErrNotFound { continue } @@ -397,25 +397,25 @@ func (bs bootstrapService) identify(token string) (string, error) { } // Method thing retrieves Mainflux Thing creating one if an empty ID is passed. -func (bs bootstrapService) thing(key, id string) (mfsdk.Thing, error) { +func (bs bootstrapService) thing(token, id string) (mfsdk.Thing, error) { thingID := id var err error if id == "" { - thingID, err = bs.sdk.CreateThing(mfsdk.Thing{}, key) + thingID, err = bs.sdk.CreateThing(mfsdk.Thing{}, token) if err != nil { return mfsdk.Thing{}, errors.Wrap(errCreateThing, err) } } - thing, err := bs.sdk.Thing(thingID, key) + thing, err := bs.sdk.Thing(thingID, token) if err != nil { if err == mfsdk.ErrNotFound { return mfsdk.Thing{}, errors.Wrap(errThingNotFound, ErrNotFound) } if id != "" { - bs.sdk.DeleteThing(thingID, key) + bs.sdk.DeleteThing(thingID, token) } return mfsdk.Thing{}, ErrThings @@ -424,7 +424,7 @@ func (bs bootstrapService) thing(key, id string) (mfsdk.Thing, error) { return thing, nil } -func (bs bootstrapService) connectionChannels(channels, existing []string, key string) ([]Channel, error) { +func (bs bootstrapService) connectionChannels(channels, existing []string, token string) ([]Channel, error) { add := make(map[string]bool, len(channels)) for _, ch := range channels { add[ch] = true @@ -438,7 +438,7 @@ func (bs bootstrapService) connectionChannels(channels, existing []string, key s var ret []Channel for id := range add { - ch, err := bs.sdk.Channel(id, key) + ch, err := bs.sdk.Channel(id, token) if err != nil { return nil, errors.Wrap(ErrMalformedEntity, err) } diff --git a/bootstrap/service_test.go b/bootstrap/service_test.go index 845f731dcc..1df8a6fe0f 100644 --- a/bootstrap/service_test.go +++ b/bootstrap/service_test.go @@ -116,37 +116,37 @@ func TestAdd(t *testing.T) { cases := []struct { desc string config bootstrap.Config - key string + token string err error }{ { desc: "add a new config", config: config, - key: validToken, + token: validToken, err: nil, }, { desc: "add a config with an invalid ID", config: neID, - key: validToken, + token: validToken, err: bootstrap.ErrNotFound, }, { desc: "add a config with wrong credentials", config: config, - key: invalidToken, + token: invalidToken, err: bootstrap.ErrUnauthorizedAccess, }, { desc: "add a config with invalid list of channels", config: wrongChannels, - key: validToken, + token: validToken, err: bootstrap.ErrMalformedEntity, }, } for _, tc := range cases { - _, err := svc.Add(tc.key, tc.config) + _, err := svc.Add(tc.token, tc.config) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) } } @@ -161,33 +161,33 @@ func TestView(t *testing.T) { require.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) cases := []struct { - desc string - id string - key string - err error + desc string + id string + token string + err error }{ { - desc: "view an existing config", - id: saved.MFThing, - key: validToken, - err: nil, + desc: "view an existing config", + id: saved.MFThing, + token: validToken, + err: nil, }, { - desc: "view a non-existing config", - id: unknown, - key: validToken, - err: bootstrap.ErrNotFound, + desc: "view a non-existing config", + id: unknown, + token: validToken, + err: bootstrap.ErrNotFound, }, { - desc: "view a config with wrong credentials", - id: config.MFThing, - key: invalidToken, - err: bootstrap.ErrUnauthorizedAccess, + desc: "view a config with wrong credentials", + id: config.MFThing, + token: invalidToken, + err: bootstrap.ErrUnauthorizedAccess, }, } for _, tc := range cases { - _, err := svc.View(tc.key, tc.id) + _, err := svc.View(tc.token, tc.id) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) } } @@ -215,31 +215,31 @@ func TestUpdate(t *testing.T) { cases := []struct { desc string config bootstrap.Config - key string + token string err error }{ { desc: "update a config with state Created", config: modifiedCreated, - key: validToken, + token: validToken, err: nil, }, { desc: "update a non-existing config", config: nonExisting, - key: validToken, + token: validToken, err: bootstrap.ErrNotFound, }, { desc: "update a config with wrong credentials", config: saved, - key: invalidToken, + token: invalidToken, err: bootstrap.ErrUnauthorizedAccess, }, } for _, tc := range cases { - err := svc.Update(tc.key, tc.config) + err := svc.Update(tc.token, tc.config) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) } } @@ -259,7 +259,7 @@ func TestUpdateCert(t *testing.T) { cases := []struct { desc string - key string + token string thingKey string clientCert string clientKey string @@ -272,7 +272,7 @@ func TestUpdateCert(t *testing.T) { clientCert: "newCert", clientKey: "newKey", caCert: "newCert", - key: validToken, + token: validToken, err: nil, }, { @@ -282,8 +282,8 @@ func TestUpdateCert(t *testing.T) { clientKey: "newKey", caCert: "newCert", - key: validToken, - err: bootstrap.ErrNotFound, + token: validToken, + err: bootstrap.ErrNotFound, }, { desc: "update config cert with wrong credentials", @@ -291,13 +291,13 @@ func TestUpdateCert(t *testing.T) { clientCert: "newCert", clientKey: "newKey", caCert: "newCert", - key: invalidToken, + token: invalidToken, err: bootstrap.ErrUnauthorizedAccess, }, } for _, tc := range cases { - err := svc.UpdateCert(tc.key, tc.thingKey, tc.clientCert, tc.clientKey, tc.caCert) + err := svc.UpdateCert(tc.token, tc.thingKey, tc.clientCert, tc.clientKey, tc.caCert) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) } } @@ -328,42 +328,42 @@ func TestUpdateConnections(t *testing.T) { cases := []struct { desc string - key string + token string id string connections []string err error }{ { desc: "update connections for config with state Inactive", - key: validToken, + token: validToken, id: created.MFThing, connections: []string{"2"}, err: nil, }, { desc: "update connections for config with state Active", - key: validToken, + token: validToken, id: active.MFThing, connections: []string{"3"}, err: nil, }, { desc: "update connections for non-existing config", - key: validToken, + token: validToken, id: "", connections: []string{"3"}, err: bootstrap.ErrNotFound, }, { desc: "update connections with invalid channels", - key: validToken, + token: validToken, id: created.MFThing, connections: []string{"wrong"}, err: bootstrap.ErrMalformedEntity, }, { desc: "update connections a config with wrong credentials", - key: invalidToken, + token: invalidToken, id: created.MFKey, connections: []string{"2", "3"}, err: bootstrap.ErrUnauthorizedAccess, @@ -371,7 +371,7 @@ func TestUpdateConnections(t *testing.T) { } for _, tc := range cases { - err := svc.UpdateConnections(tc.key, tc.id, tc.connections) + err := svc.UpdateConnections(tc.token, tc.id, tc.connections) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) } } @@ -411,7 +411,7 @@ func TestList(t *testing.T) { filter bootstrap.Filter offset uint64 limit uint64 - key string + token string err error }{ { @@ -423,7 +423,7 @@ func TestList(t *testing.T) { Configs: saved[0:10], }, filter: bootstrap.Filter{}, - key: validToken, + token: validToken, offset: 0, limit: 10, err: nil, @@ -437,7 +437,7 @@ func TestList(t *testing.T) { Configs: saved[95:96], }, filter: bootstrap.Filter{PartialMatch: map[string]string{"name": "95"}}, - key: validToken, + token: validToken, offset: 0, limit: 100, err: nil, @@ -446,7 +446,7 @@ func TestList(t *testing.T) { desc: "list configs unauthorized", config: bootstrap.ConfigsPage{}, filter: bootstrap.Filter{}, - key: invalidToken, + token: invalidToken, offset: 0, limit: 10, err: bootstrap.ErrUnauthorizedAccess, @@ -460,7 +460,7 @@ func TestList(t *testing.T) { Configs: saved[95:], }, filter: bootstrap.Filter{}, - key: validToken, + token: validToken, offset: 95, limit: 10, err: nil, @@ -474,7 +474,7 @@ func TestList(t *testing.T) { Configs: []bootstrap.Config{saved[41]}, }, filter: bootstrap.Filter{FullMatch: map[string]string{"state": bootstrap.Active.String()}}, - key: validToken, + token: validToken, offset: 35, limit: 20, err: nil, @@ -488,7 +488,7 @@ func TestList(t *testing.T) { Configs: []bootstrap.Config{unknownConfig}, }, filter: bootstrap.Filter{Unknown: true}, - key: validToken, + token: validToken, offset: 0, limit: 20, err: nil, @@ -496,7 +496,7 @@ func TestList(t *testing.T) { } for _, tc := range cases { - result, err := svc.List(tc.key, tc.filter, tc.offset, tc.limit) + result, err := svc.List(tc.token, tc.filter, tc.offset, tc.limit) assert.ElementsMatch(t, tc.config.Configs, result.Configs, fmt.Sprintf("%s: expected %v got %v", tc.desc, tc.config.Configs, result.Configs)) assert.Equal(t, tc.config.Total, result.Total, fmt.Sprintf("%s: expected %v got %v", tc.desc, tc.config.Total, result.Total)) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) @@ -513,39 +513,39 @@ func TestRemove(t *testing.T) { require.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) cases := []struct { - desc string - id string - key string - err error + desc string + id string + token string + err error }{ { - desc: "view a config with wrong credentials", - id: saved.MFThing, - key: invalidToken, - err: bootstrap.ErrUnauthorizedAccess, + desc: "view a config with wrong credentials", + id: saved.MFThing, + token: invalidToken, + err: bootstrap.ErrUnauthorizedAccess, }, { - desc: "remove an existing config", - id: saved.MFThing, - key: validToken, - err: nil, + desc: "remove an existing config", + id: saved.MFThing, + token: validToken, + err: nil, }, { - desc: "remove removed config", - id: saved.MFThing, - key: validToken, - err: nil, + desc: "remove removed config", + id: saved.MFThing, + token: validToken, + err: nil, }, { - desc: "remove non-existing config", - id: unknown, - key: validToken, - err: nil, + desc: "remove non-existing config", + id: unknown, + token: validToken, + err: nil, }, } for _, tc := range cases { - err := svc.Remove(tc.key, tc.id) + err := svc.Remove(tc.token, tc.id) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) } } @@ -624,48 +624,48 @@ func TestChangeState(t *testing.T) { desc string state bootstrap.State id string - key string + token string err error }{ { desc: "change state with wrong credentials", state: bootstrap.Active, id: saved.MFThing, - key: invalidToken, + token: invalidToken, err: bootstrap.ErrUnauthorizedAccess, }, { desc: "change state of non-existing config", state: bootstrap.Active, id: unknown, - key: validToken, + token: validToken, err: bootstrap.ErrNotFound, }, { desc: "change state to Active", state: bootstrap.Active, id: saved.MFThing, - key: validToken, + token: validToken, err: nil, }, { desc: "change state to current state", state: bootstrap.Active, id: saved.MFThing, - key: validToken, + token: validToken, err: nil, }, { desc: "change state to Inactive", state: bootstrap.Inactive, id: saved.MFThing, - key: validToken, + token: validToken, err: nil, }, } for _, tc := range cases { - err := svc.ChangeState(tc.key, tc.id, tc.state) + err := svc.ChangeState(tc.token, tc.id, tc.state) assert.True(t, errors.Contains(err, tc.err), err, fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) } } From 336e933cf91904eb27fed9395ca79265aeff5a9b Mon Sep 17 00:00:00 2001 From: Manuel Imperiale Date: Wed, 15 Apr 2020 11:08:32 +0200 Subject: [PATCH 2/4] Fix CI bot Signed-off-by: Manuel Imperiale --- bootstrap/service.go | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/bootstrap/service.go b/bootstrap/service.go index 686fdf29b2..b161cbf1cd 100644 --- a/bootstrap/service.go +++ b/bootstrap/service.go @@ -165,8 +165,9 @@ func (bs bootstrapService) Add(token string, cfg Config) (Config, error) { saved, err := bs.configs.Save(cfg, toConnect) if err != nil { if id == "" { - // Fail silently. - bs.sdk.DeleteThing(cfg.MFThing, token) + if errT := bs.sdk.DeleteThing(cfg.MFThing, token); errT != nil { + err = errors.Wrap(err, errT) + } } return Config{}, errors.Wrap(errAddBootstrap, err) } @@ -415,10 +416,12 @@ func (bs bootstrapService) thing(token, id string) (mfsdk.Thing, error) { } if id != "" { - bs.sdk.DeleteThing(thingID, token) + if errT := bs.sdk.DeleteThing(thingID, token); errT != nil { + err = errors.Wrap(err, errT) + } } - return mfsdk.Thing{}, ErrThings + return mfsdk.Thing{}, errors.Wrap(ErrThings, err) } return thing, nil From 267891840df7534b26db4c3acc3f77bf7ffdd596 Mon Sep 17 00:00:00 2001 From: Manuel Imperiale Date: Wed, 15 Apr 2020 16:26:04 +0200 Subject: [PATCH 3/4] Use owner for repository layer Signed-off-by: Manuel Imperiale --- bootstrap/configs.go | 16 ++++----- bootstrap/postgres/configs.go | 52 +++++++++++++++--------------- bootstrap/postgres/configs_test.go | 22 ++++++------- 3 files changed, 45 insertions(+), 45 deletions(-) diff --git a/bootstrap/configs.go b/bootstrap/configs.go index e2204816c4..abf4c6189e 100644 --- a/bootstrap/configs.go +++ b/bootstrap/configs.go @@ -54,11 +54,11 @@ type ConfigRepository interface { // RetrieveByID retrieves the Config having the provided identifier, that is owned // by the specified user. - RetrieveByID(key, id string) (Config, error) + RetrieveByID(owner, id string) (Config, error) // RetrieveAll retrieves a subset of Configs that are owned // by the specific user, with given filter parameters. - RetrieveAll(key string, filter Filter, offset, limit uint64) ConfigsPage + RetrieveAll(owner string, filter Filter, offset, limit uint64) ConfigsPage // RetrieveByExternalID returns Config for given external ID. RetrieveByExternalID(externalID string) (Config, error) @@ -67,26 +67,26 @@ type ConfigRepository interface { // to indicate operation failure. Update(cfg Config) error - // UpdateCerts updates an existing Config certificate and key. + // UpdateCerts updates an existing Config certificate and owner. // A non-nil error is returned to indicate operation failure. UpdateCert(owner, thingID, clientCert, clientKey, caCert string) error // UpdateConnections updates a list of Channels the Config is connected to // adding new Channels if needed. - UpdateConnections(key, id string, channels []Channel, connections []string) error + UpdateConnections(owner, id string, channels []Channel, connections []string) error // Remove removes the Config having the provided identifier, that is owned // by the specified user. - Remove(key, id string) error + Remove(owner, id string) error // ChangeState changes of the Config, that is owned by the specific user. - ChangeState(key, id string, state State) error + ChangeState(owner, id string, state State) error // ListExisting retrieves those channels from the given list that exist in DB. - ListExisting(key string, ids []string) ([]Channel, error) + ListExisting(owner string, ids []string) ([]Channel, error) // SaveUnknown saves Thing which unsuccessfully bootstrapped. - SaveUnknown(key, id string) error + SaveUnknown(owner, id string) error // RetrieveUnknown returns a subset of unsuccessfully bootstrapped Things. RetrieveUnknown(offset, limit uint64) ConfigsPage diff --git a/bootstrap/postgres/configs.go b/bootstrap/postgres/configs.go index f62df6186e..eff286c4bf 100644 --- a/bootstrap/postgres/configs.go +++ b/bootstrap/postgres/configs.go @@ -106,17 +106,17 @@ func (cr configRepository) Save(cfg bootstrap.Config, connections []string) (str return cfg.MFThing, nil } -func (cr configRepository) RetrieveByID(token, id string) (bootstrap.Config, error) { +func (cr configRepository) RetrieveByID(owner, id string) (bootstrap.Config, error) { q := `SELECT mainflux_thing, mainflux_key, external_id, external_key, name, content, state FROM configs WHERE mainflux_thing = $1 AND owner = $2` dbcfg := dbConfig{ MFThing: id, - Owner: token, + Owner: owner, } - if err := cr.db.QueryRowx(q, id, token).StructScan(&dbcfg); err != nil { + if err := cr.db.QueryRowx(q, id, owner).StructScan(&dbcfg); err != nil { empty := bootstrap.Config{} if err == sql.ErrNoRows { return empty, errors.Wrap(bootstrap.ErrNotFound, err) @@ -159,8 +159,8 @@ func (cr configRepository) RetrieveByID(token, id string) (bootstrap.Config, err return cfg, nil } -func (cr configRepository) RetrieveAll(token string, filter bootstrap.Filter, offset, limit uint64) bootstrap.ConfigsPage { - search, params := cr.retrieveAll(token, filter) +func (cr configRepository) RetrieveAll(owner string, filter bootstrap.Filter, offset, limit uint64) bootstrap.ConfigsPage { + search, params := cr.retrieveAll(owner, filter) n := len(params) q := `SELECT mainflux_thing, mainflux_key, external_id, external_key, name, content, state @@ -178,7 +178,7 @@ func (cr configRepository) RetrieveAll(token string, filter bootstrap.Filter, of configs := []bootstrap.Config{} for rows.Next() { - c := bootstrap.Config{Owner: token} + c := bootstrap.Config{Owner: owner} if err := rows.Scan(&c.MFThing, &c.MFKey, &c.ExternalID, &c.ExternalKey, &name, &content, &c.State); err != nil { cr.log.Error(fmt.Sprintf("Failed to read retrieved config due to %s", err)) return bootstrap.ConfigsPage{} @@ -299,19 +299,19 @@ func (cr configRepository) UpdateCert(owner, thingID, clientCert, clientKey, caC return nil } -func (cr configRepository) UpdateConnections(token, id string, channels []bootstrap.Channel, connections []string) error { +func (cr configRepository) UpdateConnections(owner, id string, channels []bootstrap.Channel, connections []string) error { tx, err := cr.db.Beginx() if err != nil { return err } - if err := insertChannels(token, channels, tx); err != nil { + if err := insertChannels(owner, channels, tx); err != nil { cr.rollback("Failed to insert Channels during the update", tx, err) return err } - if err := updateConnections(token, id, connections, tx); err != nil { + if err := updateConnections(owner, id, connections, tx); err != nil { if e, ok := err.(*pq.Error); ok { if e.Code.Name() == fkViolation && e.Constraint == connConstraintErr { return bootstrap.ErrNotFound @@ -329,9 +329,9 @@ func (cr configRepository) UpdateConnections(token, id string, channels []bootst return nil } -func (cr configRepository) Remove(token, id string) error { +func (cr configRepository) Remove(owner, id string) error { q := `DELETE FROM configs WHERE mainflux_thing = $1 AND owner = $2` - if _, err := cr.db.Exec(q, id, token); err != nil { + if _, err := cr.db.Exec(q, id, owner); err != nil { return errors.Wrap(errRemove, err) } @@ -342,10 +342,10 @@ func (cr configRepository) Remove(token, id string) error { return nil } -func (cr configRepository) ChangeState(token, id string, state bootstrap.State) error { +func (cr configRepository) ChangeState(owner, id string, state bootstrap.State) error { q := `UPDATE configs SET state = $1 WHERE mainflux_thing = $2 AND owner = $3;` - res, err := cr.db.Exec(q, state, id, token) + res, err := cr.db.Exec(q, state, id, owner) if err != nil { return err } @@ -362,14 +362,14 @@ func (cr configRepository) ChangeState(token, id string, state bootstrap.State) return nil } -func (cr configRepository) ListExisting(token string, ids []string) ([]bootstrap.Channel, error) { +func (cr configRepository) ListExisting(owner string, ids []string) ([]bootstrap.Channel, error) { var channels []bootstrap.Channel if len(ids) == 0 { return channels, nil } q := "SELECT mainflux_channel, name, metadata FROM channels WHERE owner = $1 AND mainflux_channel = ANY ($2)" - rows, err := cr.db.Queryx(q, token, pq.Array(ids)) + rows, err := cr.db.Queryx(q, owner, pq.Array(ids)) if err != nil { return []bootstrap.Channel{}, err } @@ -393,10 +393,10 @@ func (cr configRepository) ListExisting(token string, ids []string) ([]bootstrap return channels, nil } -func (cr configRepository) SaveUnknown(token, id string) error { +func (cr configRepository) SaveUnknown(owner, id string) error { q := `INSERT INTO unknown_configs (external_id, external_key) VALUES ($1, $2)` - if _, err := cr.db.Exec(q, id, token); err != nil { + if _, err := cr.db.Exec(q, id, owner); err != nil { if pqErr, ok := err.(*pq.Error); ok && pqErr.Code.Name() == duplicateErr { return nil } @@ -485,12 +485,12 @@ func (cr configRepository) DisconnectThing(channelID, thingID string) error { return nil } -func (cr configRepository) retrieveAll(token string, filter bootstrap.Filter) (string, []interface{}) { +func (cr configRepository) retrieveAll(owner string, filter bootstrap.Filter) (string, []interface{}) { template := `WHERE owner = $1 %s` - params := []interface{}{token} + params := []interface{}{owner} // One empty string so that strings Join works if only one filter is applied. queries := []string{""} - // Since token is the first param, start from 2. + // Since owner is the first param, start from 2. counter := 2 for k, v := range filter.FullMatch { queries = append(queries, fmt.Sprintf("%s = $%d", k, counter)) @@ -516,14 +516,14 @@ func (cr configRepository) rollback(content string, tx *sqlx.Tx, err error) { } } -func insertChannels(token string, channels []bootstrap.Channel, tx *sqlx.Tx) error { +func insertChannels(owner string, channels []bootstrap.Channel, tx *sqlx.Tx) error { if len(channels) == 0 { return nil } var chans []dbChannel for _, ch := range channels { - dbch, err := toDBChannel(token, ch) + dbch, err := toDBChannel(owner, ch) if err != nil { return err } @@ -565,7 +565,7 @@ func insertConnections(cfg bootstrap.Config, connections []string, tx *sqlx.Tx) return err } -func updateConnections(token, id string, connections []string, tx *sqlx.Tx) error { +func updateConnections(owner, id string, connections []string, tx *sqlx.Tx) error { if len(connections) == 0 { return nil } @@ -574,7 +574,7 @@ func updateConnections(token, id string, connections []string, tx *sqlx.Tx) erro WHERE config_id = $1 AND config_owner = $2 AND channel_owner = $2 AND channel_id NOT IN ($3)` - res, err := tx.Exec(q, id, token, pq.Array(connections)) + res, err := tx.Exec(q, id, owner, pq.Array(connections)) if err != nil { return err } @@ -592,8 +592,8 @@ func updateConnections(token, id string, connections []string, tx *sqlx.Tx) erro dbconn := dbConnection{ Config: id, Channel: conn, - ConfigOwner: token, - ChannelOwner: token, + ConfigOwner: owner, + ChannelOwner: owner, } conns = append(conns, dbconn) } diff --git a/bootstrap/postgres/configs_test.go b/bootstrap/postgres/configs_test.go index d71f9c9fc9..4934ae90e0 100644 --- a/bootstrap/postgres/configs_test.go +++ b/bootstrap/postgres/configs_test.go @@ -399,7 +399,7 @@ func TestUpdateConnections(t *testing.T) { cases := []struct { desc string - token string + owner string id string channels []bootstrap.Channel connections []string @@ -407,7 +407,7 @@ func TestUpdateConnections(t *testing.T) { }{ { desc: "update connections of non-existing config", - token: config.Owner, + owner: config.Owner, id: "unknown", channels: nil, connections: []string{channels[1]}, @@ -415,7 +415,7 @@ func TestUpdateConnections(t *testing.T) { }, { desc: "update connections", - token: config.Owner, + owner: config.Owner, id: c.MFThing, channels: nil, connections: []string{channels[1]}, @@ -423,7 +423,7 @@ func TestUpdateConnections(t *testing.T) { }, { desc: "update connections with existing channels", - token: config.Owner, + owner: config.Owner, id: c2, channels: nil, connections: channels, @@ -431,7 +431,7 @@ func TestUpdateConnections(t *testing.T) { }, { desc: "update connections no channels", - token: config.Owner, + owner: config.Owner, id: c.MFThing, channels: nil, connections: nil, @@ -439,7 +439,7 @@ func TestUpdateConnections(t *testing.T) { }, } for _, tc := range cases { - err := repo.UpdateConnections(tc.token, tc.id, tc.channels, tc.connections) + err := repo.UpdateConnections(tc.owner, tc.id, tc.channels, tc.connections) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) } } @@ -550,31 +550,31 @@ func TestListExisting(t *testing.T) { cases := []struct { desc string - token string + owner string connections []string existing []bootstrap.Channel }{ { desc: "list all existing channels", - token: c.Owner, + owner: c.Owner, connections: channels, existing: chs, }, { desc: "list a subset of existing channels", - token: c.Owner, + owner: c.Owner, connections: []string{channels[0], "5"}, existing: []bootstrap.Channel{chs[0]}, }, { desc: "list a subset of existing channels empty", - token: c.Owner, + owner: c.Owner, connections: []string{"5", "6"}, existing: []bootstrap.Channel{}, }, } for _, tc := range cases { - existing, err := repo.ListExisting(tc.token, tc.connections) + existing, err := repo.ListExisting(tc.owner, tc.connections) assert.Nil(t, err, fmt.Sprintf("%s: unexpected error: %s", tc.desc, err)) assert.ElementsMatch(t, tc.existing, existing, fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.existing, existing)) } From 2d22f83813cf0d633ec5d5bd2ed64dcde90b2095 Mon Sep 17 00:00:00 2001 From: Manuel Imperiale Date: Wed, 15 Apr 2020 16:36:25 +0200 Subject: [PATCH 4/4] Fix reviews Signed-off-by: Manuel Imperiale --- bootstrap/configs.go | 2 +- bootstrap/postgres/configs.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/bootstrap/configs.go b/bootstrap/configs.go index abf4c6189e..972019a1c1 100644 --- a/bootstrap/configs.go +++ b/bootstrap/configs.go @@ -50,7 +50,7 @@ type ConfigsPage struct { type ConfigRepository interface { // Save persists the Config. Successful operation is indicated by non-nil // error response. - Save(cfg Config, connections []string) (string, error) + Save(cfg Config, chsConnIDs []string) (string, error) // RetrieveByID retrieves the Config having the provided identifier, that is owned // by the specified user. diff --git a/bootstrap/postgres/configs.go b/bootstrap/postgres/configs.go index eff286c4bf..4cd465144d 100644 --- a/bootstrap/postgres/configs.go +++ b/bootstrap/postgres/configs.go @@ -57,7 +57,7 @@ func NewConfigRepository(db *sqlx.DB, log logger.Logger) bootstrap.ConfigReposit return &configRepository{db: db, log: log} } -func (cr configRepository) Save(cfg bootstrap.Config, connections []string) (string, error) { +func (cr configRepository) Save(cfg bootstrap.Config, chsConnIDs []string) (string, error) { q := `INSERT INTO configs (mainflux_thing, owner, name, client_cert, client_key, ca_cert, mainflux_key, external_id, external_key, content, state) VALUES (:mainflux_thing, :owner, :name, :client_cert, :client_key, :ca_cert, :mainflux_key, :external_id, :external_key, :content, :state)` @@ -85,7 +85,7 @@ func (cr configRepository) Save(cfg bootstrap.Config, connections []string) (str return "", errors.Wrap(errSaveChannels, err) } - if err := insertConnections(cfg, connections, tx); err != nil { + if err := insertConnections(cfg, chsConnIDs, tx); err != nil { cr.rollback("Failed to insert connections", tx, err) return "", errors.Wrap(errSaveConnections, err)