NOISSUE - Add More Linters (#1924)

* Fix linting errors

Signed-off-by: Rodney Osodo <28790446+rodneyosodo@users.noreply.github.com>

* feat(linters): add ineffassign linter

This commit adds the `ineffassign` linter to the project's `.golangci.yml` configuration file. The `ineffassign` linter helps identify and flag assignments to variables that are never used, helping to improve code quality and maintainability.

Signed-off-by: Rodney Osodo <28790446+rodneyosodo@users.noreply.github.com>

* Add extra linters

Signed-off-by: Rodney Osodo <28790446+rodneyosodo@users.noreply.github.com>

* feat(golangci): Add header check

- Added goheader check to ensure all files have license headers
- Added build tags for "nats" in the .golangci.yml file to include the necessary dependencies for the "nats" package during the build process.
- Also, increased the maximum number of issues per linter and the maximum number of same issues reported by the linter to improve the code quality analysis.

Signed-off-by: Rodney Osodo <28790446+rodneyosodo@users.noreply.github.com>

* feat(.golangci.yml): Add new linters

Add the following new linters to the .golangci.yml configuration file:
- asasalint
- asciicheck
- bidichk
- contextcheck
- decorder
- dogsled
- errchkjson
- errname
- execinquery
- exportloopref
- ginkgolinter
- gocheckcompilerdirectives

These linters will help improve code quality and catch potential issues during the code review process.

Signed-off-by: Rodney Osodo <28790446+rodneyosodo@users.noreply.github.com>

---------

Signed-off-by: Rodney Osodo <28790446+rodneyosodo@users.noreply.github.com>
This commit is contained in:
b1ackd0t
2023-10-16 12:43:33 +03:00
committed by GitHub
parent 3d3aa525a6
commit 5e060d5620
101 changed files with 370 additions and 308 deletions
+46 -1
View File
@@ -1,5 +1,12 @@
run:
timeout: 3m
build-tags:
- "nats"
issues:
max-issues-per-linter: 10
max-same-issues: 10
linters-settings:
gocritic:
enabled-checks:
@@ -9,12 +16,22 @@ linters-settings:
disabled-checks:
- appendAssign
enabled-tags:
- diagnostic
- diagnostic
disabled-tags:
- performance
- style
- experimental
- opinionated
misspell:
ignore-words:
- "mosquitto"
stylecheck:
checks: ["-ST1000", "-ST1003", "-ST1020", "-ST1021", "-ST1022"]
goheader:
template: |-
Copyright (c) Mainflux
SPDX-License-Identifier: Apache-2.0
linters:
disable-all: true
enable:
@@ -25,3 +42,31 @@ linters:
- unused
- goconst
- godot
- ineffassign
- misspell
- stylecheck
- whitespace
- gci
- gofmt
- goimports
- loggercheck
- goheader
- asasalint
- asciicheck
- bidichk
- contextcheck
- decorder
- dogsled
- errchkjson
- errname
- execinquery
- exportloopref
- ginkgolinter
- gocheckcompilerdirectives
- gofumpt
- goprintffuncname
- importas
- makezero
- mirror
- misspell
- nakedret
+2 -1
View File
@@ -460,7 +460,8 @@ func (client grpcClient) ListSubjects(ctx context.Context, in *mainflux.ListSubj
Permission: in.GetPermission(),
ObjectType: in.GetObjectType(),
Object: in.GetObject(),
NextPageToken: in.GetNextPageToken()})
NextPageToken: in.GetNextPageToken(),
})
if err != nil {
return &mainflux.ListSubjectsRes{}, err
}
+2 -1
View File
@@ -136,7 +136,8 @@ func addPolicyEndpoint(svc auth.Service) endpoint.Endpoint {
Relation: req.Relation,
Permission: req.Permission,
ObjectType: req.ObjectType,
Object: req.Object})
Object: req.Object,
})
if err != nil {
return addPolicyRes{}, err
}
-3
View File
@@ -32,9 +32,6 @@ const (
usersType = "users"
description = "Description"
numOfThings = 5
numOfUsers = 5
authoritiesObj = "authorities"
memberRelation = "member"
loginDuration = 30 * time.Minute
-8
View File
@@ -43,11 +43,3 @@ type listSubjectsRes struct {
type countSubjectsRes struct {
count int
}
type membersRes struct {
total uint64
offset uint64
limit uint64
groupType string
members []string
}
+28 -14
View File
@@ -246,14 +246,16 @@ func encodeIdentifyResponse(_ context.Context, grpcRes interface{}) (interface{}
func decodeAuthorizeRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
req := grpcReq.(*mainflux.AuthorizeReq)
return authReq{Namespace: req.GetNamespace(),
return authReq{
Namespace: req.GetNamespace(),
SubjectType: req.GetSubjectType(),
SubjectKind: req.GetSubjectKind(),
Subject: req.GetSubject(),
Relation: req.GetRelation(),
Permission: req.GetPermission(),
ObjectType: req.GetObjectType(),
Object: req.GetObject()}, nil
Object: req.GetObject(),
}, nil
}
func encodeAuthorizeResponse(_ context.Context, grpcRes interface{}) (interface{}, error) {
@@ -263,13 +265,15 @@ func encodeAuthorizeResponse(_ context.Context, grpcRes interface{}) (interface{
func decodeAddPolicyRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
req := grpcReq.(*mainflux.AddPolicyReq)
return policyReq{Namespace: req.GetNamespace(),
return policyReq{
Namespace: req.GetNamespace(),
SubjectType: req.GetSubjectType(),
Subject: req.GetSubject(),
Relation: req.GetRelation(),
Permission: req.GetPermission(),
ObjectType: req.GetObjectType(),
Object: req.GetObject()}, nil
Object: req.GetObject(),
}, nil
}
func encodeAddPolicyResponse(_ context.Context, grpcRes interface{}) (interface{}, error) {
@@ -279,13 +283,15 @@ func encodeAddPolicyResponse(_ context.Context, grpcRes interface{}) (interface{
func decodeDeletePolicyRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
req := grpcReq.(*mainflux.DeletePolicyReq)
return policyReq{Namespace: req.GetNamespace(),
return policyReq{
Namespace: req.GetNamespace(),
SubjectType: req.GetSubjectType(),
Subject: req.GetSubject(),
Relation: req.GetRelation(),
Permission: req.GetPermission(),
ObjectType: req.GetObjectType(),
Object: req.GetObject()}, nil
Object: req.GetObject(),
}, nil
}
func encodeDeletePolicyResponse(_ context.Context, grpcRes interface{}) (interface{}, error) {
@@ -295,7 +301,8 @@ func encodeDeletePolicyResponse(_ context.Context, grpcRes interface{}) (interfa
func decodeListObjectsRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
req := grpcReq.(*mainflux.ListObjectsReq)
return listObjectsReq{Namespace: req.GetNamespace(),
return listObjectsReq{
Namespace: req.GetNamespace(),
SubjectType: req.GetSubjectType(),
Subject: req.GetSubject(),
Relation: req.GetRelation(),
@@ -303,7 +310,8 @@ func decodeListObjectsRequest(_ context.Context, grpcReq interface{}) (interface
ObjectType: req.GetObjectType(),
Object: req.GetObject(),
NextPageToken: req.GetNextPageToken(),
Limit: req.GetLimit()}, nil
Limit: req.GetLimit(),
}, nil
}
func encodeListObjectsResponse(_ context.Context, grpcRes interface{}) (interface{}, error) {
@@ -313,13 +321,15 @@ func encodeListObjectsResponse(_ context.Context, grpcRes interface{}) (interfac
func decodeCountObjectsRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
req := grpcReq.(*mainflux.CountObjectsReq)
return countObjectsReq{Namespace: req.GetNamespace(),
return countObjectsReq{
Namespace: req.GetNamespace(),
SubjectType: req.GetSubjectType(),
Subject: req.GetSubject(),
Relation: req.GetRelation(),
Permission: req.GetPermission(),
ObjectType: req.GetObjectType(),
Object: req.GetObject()}, nil
Object: req.GetObject(),
}, nil
}
func encodeCountObjectsResponse(_ context.Context, grpcRes interface{}) (interface{}, error) {
@@ -329,13 +339,15 @@ func encodeCountObjectsResponse(_ context.Context, grpcRes interface{}) (interfa
func decodeListSubjectsRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
req := grpcReq.(*mainflux.ListSubjectsReq)
return listSubjectsReq{Namespace: req.GetNamespace(),
return listSubjectsReq{
Namespace: req.GetNamespace(),
SubjectType: req.GetSubjectType(),
Subject: req.GetSubject(),
Relation: req.GetRelation(),
Permission: req.GetPermission(),
ObjectType: req.GetObjectType(),
Object: req.GetObject(), NextPageToken: req.GetNextPageToken(), Limit: req.GetLimit()}, nil
Object: req.GetObject(), NextPageToken: req.GetNextPageToken(), Limit: req.GetLimit(),
}, nil
}
func encodeListSubjectsResponse(_ context.Context, grpcRes interface{}) (interface{}, error) {
@@ -345,13 +357,15 @@ func encodeListSubjectsResponse(_ context.Context, grpcRes interface{}) (interfa
func decodeCountSubjectsRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
req := grpcReq.(*mainflux.CountSubjectsReq)
return countSubjectsReq{Namespace: req.GetNamespace(),
return countSubjectsReq{
Namespace: req.GetNamespace(),
SubjectType: req.GetSubjectType(),
Subject: req.GetSubject(),
Relation: req.GetRelation(),
Permission: req.GetPermission(),
ObjectType: req.GetObjectType(),
Object: req.GetObject()}, nil
Object: req.GetObject(),
}, nil
}
func encodeCountSubjectsResponse(_ context.Context, grpcRes interface{}) (interface{}, error) {
-1
View File
@@ -54,7 +54,6 @@ func retrieveEndpoint(svc auth.Service) endpoint.Endpoint {
}
key, err := svc.RetrieveKey(ctx, req.token, req.id)
if err != nil {
return nil, err
}
+6 -2
View File
@@ -80,7 +80,10 @@ func newServer(svc auth.Service) *httptest.Server {
}
func toJSON(data interface{}) string {
jsonData, _ := json.Marshal(data)
jsonData, err := json.Marshal(data)
if err != nil {
return ""
}
return string(jsonData)
}
@@ -278,7 +281,8 @@ func TestRevoke(t *testing.T) {
desc: "revoke key with invalid token",
id: k.AccessToken,
token: "wrong",
status: http.StatusUnauthorized},
status: http.StatusUnauthorized,
},
}
for _, tc := range cases {
+1 -2
View File
@@ -56,8 +56,7 @@ func (res retrieveKeyRes) Empty() bool {
return false
}
type revokeKeyRes struct {
}
type revokeKeyRes struct{}
func (res revokeKeyRes) Code() int {
return http.StatusNoContent
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package policies
import (
+4 -1
View File
@@ -77,7 +77,10 @@ func newServer(svc auth.Service) *httptest.Server {
}
func toJSON(data interface{}) string {
jsonData, _ := json.Marshal(data)
jsonData, err := json.Marshal(data)
if err != nil {
return ""
}
return string(jsonData)
}
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package policies
import "github.com/mainflux/mainflux/internal/apiutil"
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package policies
import "net/http"
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package policies
import (
+1 -1
View File
@@ -31,7 +31,7 @@ type Token struct {
type KeyType uint32
const (
// AccessKey is temporary User key received on successfull login.
// AccessKey is temporary User key received on successful login.
AccessKey KeyType = iota
// RefreshKey is a temporary User key used to generate a new access key.
RefreshKey
+7 -3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package mocks
import (
@@ -7,8 +10,10 @@ import (
"github.com/stretchr/testify/mock"
)
var _ auth.Authz = (*Authz)(nil)
var _ auth.PolicyAgent = (*PolicyAgent)(nil)
var (
_ auth.Authz = (*Authz)(nil)
_ auth.PolicyAgent = (*PolicyAgent)(nil)
)
type Authz struct {
mock.Mock
@@ -78,7 +83,6 @@ func (m *Authz) ListSubjects(ctx context.Context, pr auth.PolicyReq, nextPageTok
ret := m.Called(ctx, pr, nextPageToken, limit)
return ret.Get(0).(auth.PolicyPage), ret.Error(1)
}
type PolicyAgent struct {
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package mocks
import (
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package mocks
import (
+4 -1
View File
@@ -23,7 +23,10 @@ type PolicyReq struct {
}
func (pr PolicyReq) String() string {
data, _ := json.Marshal(pr)
data, err := json.Marshal(pr)
if err != nil {
return ""
}
return string(data)
}
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package postgres
import (
+3 -3
View File
@@ -163,7 +163,7 @@ func (svc service) Identify(ctx context.Context, token string) (string, error) {
case RecoveryKey, AccessKey:
return key.Subject, nil
case APIKey:
_, err := svc.keys.Retrieve(context.TODO(), key.Issuer, key.ID)
_, err := svc.keys.Retrieve(ctx, key.Issuer, key.ID)
if err != nil {
return "", errors.ErrAuthentication
}
@@ -206,7 +206,7 @@ func (svc service) AddPolicies(ctx context.Context, token, object string, subjec
for _, subjectID := range subjectIDs {
for _, relation := range relations {
if err := svc.AddPolicy(ctx, PolicyReq{Object: object, Relation: relation, Subject: subjectID}); err != nil {
errs = errors.Wrap(fmt.Errorf("cannot add '%s' policy on object '%s' for subject '%s': %s", relation, object, subjectID, err), errs)
errs = errors.Wrap(fmt.Errorf("cannot add '%s' policy on object '%s' for subject '%s': %w", relation, object, subjectID, err), errs)
}
}
}
@@ -233,7 +233,7 @@ func (svc service) DeletePolicies(ctx context.Context, token, object string, sub
for _, subjectID := range subjectIDs {
for _, relation := range relations {
if err := svc.DeletePolicy(ctx, PolicyReq{Object: object, Relation: relation, Subject: subjectID}); err != nil {
errs = errors.Wrap(fmt.Errorf("cannot delete '%s' policy on object '%s' for subject '%s': %s", relation, object, subjectID, err), errs)
errs = errors.Wrap(fmt.Errorf("cannot delete '%s' policy on object '%s' for subject '%s': %w", relation, object, subjectID, err), errs)
}
}
}
+4 -9
View File
@@ -33,6 +33,10 @@ const (
loginDuration = 30 * time.Minute
refreshDuration = 24 * time.Hour
accessToken = "access"
readPolicy = "read"
writePolicy = "write"
deletePolicy = "delete"
)
func newService() (auth.Service, *mocks.Keys) {
@@ -348,9 +352,6 @@ func TestAddPolicies(t *testing.T) {
assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err))
tmpID := "tmpid"
readPolicy := "read"
writePolicy := "write"
deletePolicy := "delete"
// Add read policy to users.
err = svc.AddPolicies(context.Background(), apiToken.AccessToken, thingID, []string{id, tmpID}, []string{readPolicy})
@@ -432,9 +433,6 @@ func TestDeletePolicies(t *testing.T) {
assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err))
tmpID := "tmpid"
readPolicy := "read"
writePolicy := "write"
deletePolicy := "delete"
memberPolicy := "member"
// Add read, write and delete policies to users.
@@ -516,8 +514,6 @@ func TestListPolicies(t *testing.T) {
apiToken, err := svc.Issue(context.Background(), secret.AccessToken, key)
assert.Nil(t, err, fmt.Sprintf("Issuing user's key expected to succeed: %s", err))
readPolicy := "read"
pageLen := 15
// Add arbitrary policies to the user.
@@ -529,5 +525,4 @@ func TestListPolicies(t *testing.T) {
page, err := svc.ListObjects(context.Background(), auth.PolicyReq{Subject: id, Relation: readPolicy}, "", 100)
assert.Nil(t, err, fmt.Sprintf("listing policies expected to succeed: %s", err))
assert.Equal(t, pageLen, len(page.Policies), fmt.Sprintf("unexpected listing page size, expected %d, got %d: %v", pageLen, len(page.Policies), err))
}
+10 -7
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package spicedb
import (
@@ -35,7 +38,7 @@ func (pa *policyAgent) CheckPolicy(ctx context.Context, pr auth.PolicyReq) error
Subject: &v1.SubjectReference{Object: &v1.ObjectReference{ObjectType: pr.SubjectType, ObjectId: pr.Subject}, OptionalRelation: pr.SubjectRelation},
}
resp, err := pa.permissionClient.CheckPermission(context.Background(), &checkReq)
resp, err := pa.permissionClient.CheckPermission(ctx, &checkReq)
if err != nil {
return errors.Wrap(errors.ErrMalformedEntity, fmt.Errorf("failed to check permission: %w", err))
}
@@ -68,6 +71,7 @@ func (pa *policyAgent) AddPolicies(ctx context.Context, prs []auth.PolicyReq) er
}
return nil
}
func (pa *policyAgent) AddPolicy(ctx context.Context, pr auth.PolicyReq) error {
updates := []*v1.RelationshipUpdate{
{
@@ -302,10 +306,10 @@ func subjectsToAuthPolicies(subjects []*v1.LookupSubjectsResponse) []auth.Policy
return policies
}
func (pa *policyAgent) Watch(continue_token string) {
func (pa *policyAgent) Watch(continueToken string) {
stream, err := pa.client.WatchServiceClient.Watch(context.Background(), &v1.WatchRequest{
OptionalObjectTypes: []string{},
OptionalStartCursor: &v1.ZedToken{Token: continue_token},
OptionalStartCursor: &v1.ZedToken{Token: continueToken},
})
if err != nil {
pa.logger.Error(fmt.Sprintf("got error while watching: %s", err.Error()))
@@ -332,15 +336,14 @@ func (pa *policyAgent) publishToStream(resp *v1.WatchResponse) {
for _, update := range resp.Updates {
operation := v1.RelationshipUpdate_Operation_name[int32(update.Operation)]
objectType := update.Relationship.Resource.ObjectType
objectId := update.Relationship.Resource.ObjectId
objectID := update.Relationship.Resource.ObjectId
relation := update.Relationship.Relation
subjectType := update.Relationship.Subject.Object.ObjectType
subjectRelation := update.Relationship.Subject.OptionalRelation
subjectId := update.Relationship.Subject.Object.ObjectId
subjectID := update.Relationship.Subject.Object.ObjectId
pa.logger.Info(fmt.Sprintf(`
Operation : %s object_type: %s object_id: %s relation: %s subject_type: %s subject_relation: %s subject_id: %s
`, operation, objectType, objectId, relation, subjectType, subjectRelation, subjectId))
`, operation, objectType, objectID, relation, subjectType, subjectRelation, subjectID))
}
}
-3
View File
@@ -53,7 +53,6 @@ func (cr certsRepository) RetrieveAll(ctx context.Context, ownerID string, offse
if err := rows.Scan(&c.ThingID, &c.OwnerID, &c.Serial, &c.Expire); err != nil {
cr.log.Error(fmt.Sprintf("Failed to read retrieved config due to %s", err))
return certs.Page{}, err
}
certificates = append(certificates, c)
}
@@ -130,7 +129,6 @@ func (cr certsRepository) RetrieveByThing(ctx context.Context, ownerID, thingID
if err := rows.Scan(&c.ThingID, &c.OwnerID, &c.Serial, &c.Expire); err != nil {
cr.log.Error(fmt.Sprintf("Failed to read retrieved config due to %s", err))
return certs.Page{}, err
}
certificates = append(certificates, c)
}
@@ -156,7 +154,6 @@ func (cr certsRepository) RetrieveBySerial(ctx context.Context, ownerID, serialI
var c certs.Cert
if err := cr.db.QueryRowxContext(ctx, q, ownerID, serialID).StructScan(&dbcrt); err != nil {
pqErr, ok := err.(*pgconn.PgError)
if err == sql.ErrNoRows || ok && pgerrcode.InvalidTextRepresentation == pqErr.Code {
return c, errors.Wrap(errors.ErrNotFound, err)
+13 -23
View File
@@ -7,22 +7,22 @@ import (
"context"
"fmt"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
"github.com/go-chi/chi/v5"
"github.com/mainflux/mainflux"
authmocks "github.com/mainflux/mainflux/auth/mocks"
"github.com/mainflux/mainflux/certs"
"github.com/mainflux/mainflux/certs/mocks"
chmocks "github.com/mainflux/mainflux/internal/groups/mocks"
"github.com/mainflux/mainflux/logger"
mfclients "github.com/mainflux/mainflux/pkg/clients"
"github.com/mainflux/mainflux/pkg/errors"
mfsdk "github.com/mainflux/mainflux/pkg/sdk/go"
"github.com/mainflux/mainflux/pkg/uuid"
"github.com/mainflux/mainflux/things"
httpapi "github.com/mainflux/mainflux/things/api"
httpapi "github.com/mainflux/mainflux/things/api/http"
thmocks "github.com/mainflux/mainflux/things/mocks"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -45,13 +45,9 @@ const (
instanceID = "5de9b29a-feb9-11ed-be56-0242ac120002"
)
var adminRelationKeys = []string{"c_update", "c_list", "c_delete", "c_share"}
func newService(tokens map[string]string) (certs.Service, error) {
server := newThingsServer(newThingsService(ac))
auth := new(authmocks.Service)
tsvc, auth := newThingsService()
server := newThingsServer(tsvc)
config := mfsdk.Config{
ThingsURL: server.URL,
@@ -75,20 +71,14 @@ func newService(tokens map[string]string) (certs.Service, error) {
return certs.New(auth, repo, sdk, pki), nil
}
func newThingsService(auth mainflux.AuthServiceClient) things.Service {
ths := make(map[string]mfclients.Client, thingsNum)
for i := 0; i < thingsNum; i++ {
id := strconv.Itoa(i + 1)
ths[id] = mfclients.Client{
ID: id,
Credentials: mfclients.Credentials{
Secret: thingKey,
},
Owner: email,
}
}
func newThingsService() (things.Service, *authmocks.Service) {
auth := new(authmocks.Service)
thingCache := thmocks.NewCache()
idProvider := uuid.NewMock()
cRepo := new(thmocks.Repository)
gRepo := new(chmocks.Repository)
return things.NewService(ths, auth)
return things.NewService(auth, cRepo, gRepo, thingCache, idProvider), auth
}
func TestIssueCert(t *testing.T) {
+4 -2
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package main
import (
@@ -24,9 +27,8 @@ import (
"github.com/mainflux/mainflux/internal"
jaegerclient "github.com/mainflux/mainflux/internal/clients/jaeger"
pgclient "github.com/mainflux/mainflux/internal/clients/postgres"
"github.com/mainflux/mainflux/internal/postgres"
"github.com/mainflux/mainflux/internal/env"
"github.com/mainflux/mainflux/internal/postgres"
"github.com/mainflux/mainflux/internal/server"
grpcserver "github.com/mainflux/mainflux/internal/server/grpc"
httpserver "github.com/mainflux/mainflux/internal/server/http"
+1 -3
View File
@@ -11,11 +11,10 @@ import (
"os"
"time"
callhome "github.com/mainflux/callhome/pkg/client"
"github.com/go-chi/chi/v5"
"github.com/go-redis/redis/v8"
"github.com/jmoiron/sqlx"
callhome "github.com/mainflux/callhome/pkg/client"
"github.com/mainflux/mainflux"
"github.com/mainflux/mainflux/internal"
authclient "github.com/mainflux/mainflux/internal/clients/grpc/auth"
@@ -41,7 +40,6 @@ import (
thcache "github.com/mainflux/mainflux/things/cache"
thevents "github.com/mainflux/mainflux/things/events"
thingspg "github.com/mainflux/mainflux/things/postgres"
localusers "github.com/mainflux/mainflux/things/standalone"
ctracing "github.com/mainflux/mainflux/things/tracing"
"go.opentelemetry.io/otel/trace"
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package tracing
import (
+4 -1
View File
@@ -81,7 +81,10 @@ func newServer(svc notifiers.Service) *httptest.Server {
}
func toJSON(data interface{}) string {
jsonData, _ := json.Marshal(data)
jsonData, err := json.Marshal(data)
if err != nil {
return ""
}
return string(jsonData)
}
@@ -67,7 +67,6 @@ func TestSave(t *testing.T) {
id, err := repo.Save(context.Background(), tc.sub)
assert.Equal(t, tc.id, id, fmt.Sprintf("%s: expected id %s got %s\n", tc.desc, tc.id, id))
assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err))
}
}
@@ -113,7 +112,6 @@ func TestView(t *testing.T) {
sub, err := repo.Retrieve(context.Background(), tc.id)
assert.Equal(t, tc.sub, sub, fmt.Sprintf("%s: expected sub %v got %v\n", tc.desc, tc.sub, sub))
assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err))
}
}
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package tracing
import (
+3 -3
View File
@@ -33,7 +33,7 @@ var (
|> count()
|> yield(name: "count")`, repoCfg.Bucket)
rowCountJson = fmt.Sprintf(`from(bucket: "%s")
rowCountJSON = fmt.Sprintf(`from(bucket: "%s")
|> range(start: -1h, stop: 1h)
|> filter(fn: (r) => r["_measurement"] == "some_json")
|> filter(fn: (r) => r["_field"] == "field_1" or r["_field"] == "field_2" or r["_field"] == "field_3" or r["_field"] == "field_4" or r["_field"] == "field_5/field_1" or r["_field"] == "field_5/field_2")
@@ -360,7 +360,7 @@ func TestAsyncSaveJSON(t *testing.T) {
}
switch err {
case nil:
count, err := queryDB(rowCountJson)
count, err := queryDB(rowCountJSON)
assert.Nil(t, err, fmt.Sprintf("Querying InfluxDB to retrieve data expected to succeed: %s.\n", err))
assert.Equal(t, streamsSize, count, fmt.Sprintf("Expected to have %d messages saved, found %d instead.\n", streamsSize, count))
default:
@@ -466,7 +466,7 @@ func TestBlockingSaveJSON(t *testing.T) {
switch err = syncRepo.ConsumeBlocking(context.TODO(), tc.msgs); err {
case nil:
count, err := queryDB(rowCountJson)
count, err := queryDB(rowCountJSON)
assert.Nil(t, err, fmt.Sprintf("Querying InfluxDB to retrieve data expected to succeed: %s.\n", err))
assert.Equal(t, streamsSize, count, fmt.Sprintf("Expected to have %d messages saved, found %d instead.\n", streamsSize, count))
default:
+6 -6
View File
@@ -39,7 +39,7 @@ func New(db *sqlx.DB) consumers.BlockingConsumer {
func (pr postgresRepo) ConsumeBlocking(ctx context.Context, message interface{}) (err error) {
switch m := message.(type) {
case mfjson.Messages:
return pr.saveJSON(m)
return pr.saveJSON(ctx, m)
default:
return pr.saveSenml(ctx, m)
}
@@ -94,21 +94,21 @@ func (pr postgresRepo) saveSenml(ctx context.Context, messages interface{}) (err
return err
}
func (pr postgresRepo) saveJSON(msgs mfjson.Messages) error {
if err := pr.insertJSON(msgs); err != nil {
func (pr postgresRepo) saveJSON(ctx context.Context, msgs mfjson.Messages) error {
if err := pr.insertJSON(ctx, msgs); err != nil {
if err == errNoTable {
if err := pr.createTable(msgs.Format); err != nil {
return err
}
return pr.insertJSON(msgs)
return pr.insertJSON(ctx, msgs)
}
return err
}
return nil
}
func (pr postgresRepo) insertJSON(msgs mfjson.Messages) error {
tx, err := pr.db.BeginTxx(context.Background(), nil)
func (pr postgresRepo) insertJSON(ctx context.Context, msgs mfjson.Messages) error {
tx, err := pr.db.BeginTxx(ctx, nil)
if err != nil {
return errors.Wrap(errSaveMessage, err)
}
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package tracing
import (
-2
View File
@@ -111,8 +111,6 @@ func Connect(cfg Config) (*grpc.ClientConn, security, error) {
// Setup load gRPC configuration from environment variable, creates new gRPC client and connect to gRPC server.
func Setup(config Config, svcName string) (*Client, ClientHandler, error) {
secure := withoutTLS
// connect to auth grpc server
grpcClient, secure, err := Connect(config)
if err != nil {
+1 -1
View File
@@ -23,7 +23,7 @@ type Config struct {
Port string `env:"PORT" envDefault:"8086"`
Username string `env:"ADMIN_USER" envDefault:"mainflux"`
Password string `env:"ADMIN_PASSWORD" envDefault:"mainflux"`
DbName string `env:"NAME" envDefault:"mainflux"`
DBName string `env:"NAME" envDefault:"mainflux"`
Bucket string `env:"BUCKET" envDefault:"mainflux-bucket"`
Org string `env:"ORG" envDefault:"mainflux"`
Token string `env:"TOKEN" envDefault:"mainflux-token"`
+1 -1
View File
@@ -17,7 +17,7 @@ import (
var (
errNoURL = errors.New("URL is empty")
errNoSvcName = errors.New("Service Name is empty")
errNoSvcName = errors.New("service Name is empty")
)
// NewProvider initializes Jaeger TraceProvider.
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package env
import (
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package env
import (
+3 -14
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package api
import (
@@ -19,20 +22,6 @@ const (
defPermission = "view"
)
func DecodeListMembershipRequest(_ context.Context, r *http.Request) (interface{}, error) {
memberKind, err := apiutil.ReadStringQuery(r, api.MemberKindKey, "")
if err != nil {
return nil, errors.Wrap(apiutil.ErrValidation, err)
}
req := listMembershipReq{
token: apiutil.ExtractBearerToken(r),
groupID: chi.URLParam(r, "groupID"),
memberKind: memberKind,
}
return req, nil
}
func DecodeListGroupsRequest(_ context.Context, r *http.Request) (interface{}, error) {
pm, err := decodePageMeta(r)
if err != nil {
+7 -8
View File
@@ -10,7 +10,6 @@ import (
"github.com/mainflux/mainflux/internal/apiutil"
"github.com/mainflux/mainflux/pkg/errors"
"github.com/mainflux/mainflux/pkg/groups"
mfgroups "github.com/mainflux/mainflux/pkg/groups"
)
func CreateGroupEndpoint(svc groups.Service) endpoint.Endpoint {
@@ -52,7 +51,7 @@ func UpdateGroupEndpoint(svc groups.Service) endpoint.Endpoint {
return updateGroupRes{}, errors.Wrap(apiutil.ErrValidation, err)
}
group := mfgroups.Group{
group := groups.Group{
ID: req.id,
Name: req.Name,
Description: req.Description,
@@ -183,14 +182,14 @@ func UnassignMembersEndpoint(svc groups.Service, relation string, memberKind str
}
}
func buildGroupsResponseTree(page mfgroups.Page) groupPageRes {
groupsMap := map[string]*mfgroups.Group{}
func buildGroupsResponseTree(page groups.Page) groupPageRes {
groupsMap := map[string]*groups.Group{}
// Parents' map keeps its array of children.
parentsMap := map[string][]*mfgroups.Group{}
parentsMap := map[string][]*groups.Group{}
for i := range page.Groups {
if _, ok := groupsMap[page.Groups[i].ID]; !ok {
groupsMap[page.Groups[i].ID] = &page.Groups[i]
parentsMap[page.Groups[i].ID] = make([]*mfgroups.Group, 0)
parentsMap[page.Groups[i].ID] = make([]*groups.Group, 0)
}
}
@@ -227,14 +226,14 @@ func buildGroupsResponseTree(page mfgroups.Page) groupPageRes {
return res
}
func toViewGroupRes(group mfgroups.Group) viewGroupRes {
func toViewGroupRes(group groups.Group) viewGroupRes {
view := viewGroupRes{
Group: group,
}
return view
}
func buildGroupsResponse(gp mfgroups.Page) groupPageRes {
func buildGroupsResponse(gp groups.Page) groupPageRes {
res := groupPageRes{
pageRes: pageRes{
Total: gp.Total,
+7 -8
View File
@@ -10,7 +10,6 @@ import (
mflog "github.com/mainflux/mainflux/logger"
"github.com/mainflux/mainflux/pkg/groups"
mfgroups "github.com/mainflux/mainflux/pkg/groups"
)
var _ groups.Service = (*loggingMiddleware)(nil)
@@ -27,7 +26,7 @@ func LoggingMiddleware(svc groups.Service, logger mflog.Logger) groups.Service {
// CreateGroup logs the create_group request. It logs the group name, id and token and the time it took to complete the request.
// If the request fails, it logs the error.
func (lm *loggingMiddleware) CreateGroup(ctx context.Context, token string, group mfgroups.Group) (g mfgroups.Group, err error) {
func (lm *loggingMiddleware) CreateGroup(ctx context.Context, token string, group groups.Group) (g groups.Group, err error) {
defer func(begin time.Time) {
message := fmt.Sprintf("Method create_group for group %s with id %s using token %s took %s to complete", g.Name, g.ID, token, time.Since(begin))
if err != nil {
@@ -41,7 +40,7 @@ func (lm *loggingMiddleware) CreateGroup(ctx context.Context, token string, grou
// UpdateGroup logs the update_group request. It logs the group name, id and token and the time it took to complete the request.
// If the request fails, it logs the error.
func (lm *loggingMiddleware) UpdateGroup(ctx context.Context, token string, group mfgroups.Group) (g mfgroups.Group, err error) {
func (lm *loggingMiddleware) UpdateGroup(ctx context.Context, token string, group groups.Group) (g groups.Group, err error) {
defer func(begin time.Time) {
message := fmt.Sprintf("Method update_group for group %s with id %s using token %s took %s to complete", g.Name, g.ID, token, time.Since(begin))
if err != nil {
@@ -55,7 +54,7 @@ func (lm *loggingMiddleware) UpdateGroup(ctx context.Context, token string, grou
// ViewGroup logs the view_group request. It logs the group name, id and token and the time it took to complete the request.
// If the request fails, it logs the error.
func (lm *loggingMiddleware) ViewGroup(ctx context.Context, token, id string) (g mfgroups.Group, err error) {
func (lm *loggingMiddleware) ViewGroup(ctx context.Context, token, id string) (g groups.Group, err error) {
defer func(begin time.Time) {
message := fmt.Sprintf("Method view_group for group %s with id %s using token %s took %s to complete", g.Name, g.ID, token, time.Since(begin))
if err != nil {
@@ -69,7 +68,7 @@ func (lm *loggingMiddleware) ViewGroup(ctx context.Context, token, id string) (g
// ListGroups logs the list_groups request. It logs the token and the time it took to complete the request.
// If the request fails, it logs the error.
func (lm *loggingMiddleware) ListGroups(ctx context.Context, token string, memberKind, memberID string, gp mfgroups.Page) (cg mfgroups.Page, err error) {
func (lm *loggingMiddleware) ListGroups(ctx context.Context, token string, memberKind, memberID string, gp groups.Page) (cg groups.Page, err error) {
defer func(begin time.Time) {
message := fmt.Sprintf("Method list_groups %d groups using token %s took %s to complete", cg.Total, token, time.Since(begin))
if err != nil {
@@ -83,7 +82,7 @@ func (lm *loggingMiddleware) ListGroups(ctx context.Context, token string, membe
// EnableGroup logs the enable_group request. It logs the group name, id and token and the time it took to complete the request.
// If the request fails, it logs the error.
func (lm *loggingMiddleware) EnableGroup(ctx context.Context, token, id string) (g mfgroups.Group, err error) {
func (lm *loggingMiddleware) EnableGroup(ctx context.Context, token, id string) (g groups.Group, err error) {
defer func(begin time.Time) {
message := fmt.Sprintf("Method enable_group for group with id %s using token %s took %s to complete", g.ID, token, time.Since(begin))
if err != nil {
@@ -97,7 +96,7 @@ func (lm *loggingMiddleware) EnableGroup(ctx context.Context, token, id string)
// DisableGroup logs the disable_group request. It logs the group name, id and token and the time it took to complete the request.
// If the request fails, it logs the error.
func (lm *loggingMiddleware) DisableGroup(ctx context.Context, token, id string) (g mfgroups.Group, err error) {
func (lm *loggingMiddleware) DisableGroup(ctx context.Context, token, id string) (g groups.Group, err error) {
defer func(begin time.Time) {
message := fmt.Sprintf("Method disable_group for group with id %s using token %s took %s to complete", g.ID, token, time.Since(begin))
if err != nil {
@@ -111,7 +110,7 @@ func (lm *loggingMiddleware) DisableGroup(ctx context.Context, token, id string)
// ListMembers logs the list_members request. It logs the groupID and token and the time it took to complete the request.
// If the request fails, it logs the error.
func (lm *loggingMiddleware) ListMembers(ctx context.Context, token, groupID, permission, memberKind string) (mp mfgroups.MembersPage, err error) {
func (lm *loggingMiddleware) ListMembers(ctx context.Context, token, groupID, permission, memberKind string) (mp groups.MembersPage, err error) {
defer func(begin time.Time) {
message := fmt.Sprintf("Method list_memberships for group with id %s using token %s took %s to complete", groupID, token, time.Since(begin))
if err != nil {
-21
View File
@@ -77,27 +77,6 @@ func (req listGroupsReq) validate() error {
return nil
}
type listMembershipReq struct {
mfgroups.Page
token string
groupID string
memberKind string
}
func (req listMembershipReq) validate() error {
if req.token == "" {
return apiutil.ErrBearerToken
}
if req.groupID == "" {
return apiutil.ErrMissingID
}
if req.memberKind == "" {
return apiutil.ErrMissingMemberKind
}
return nil
}
type groupReq struct {
token string
id string
+7 -8
View File
@@ -9,7 +9,6 @@ import (
"github.com/mainflux/mainflux"
"github.com/mainflux/mainflux/pkg/groups"
mfgroups "github.com/mainflux/mainflux/pkg/groups"
)
var (
@@ -25,7 +24,7 @@ var (
)
type viewMembershipRes struct {
mfgroups.Group `json:",inline"`
groups.Group `json:",inline"`
}
func (res viewMembershipRes) Code() int {
@@ -58,7 +57,7 @@ func (res membershipPageRes) Empty() bool {
}
type viewGroupRes struct {
mfgroups.Group `json:",inline"`
groups.Group `json:",inline"`
}
func (res viewGroupRes) Code() int {
@@ -74,8 +73,8 @@ func (res viewGroupRes) Empty() bool {
}
type createGroupRes struct {
mfgroups.Group `json:",inline"`
created bool
groups.Group `json:",inline"`
created bool
}
func (res createGroupRes) Code() int {
@@ -125,7 +124,7 @@ func (res groupPageRes) Empty() bool {
}
type updateGroupRes struct {
mfgroups.Group `json:",inline"`
groups.Group `json:",inline"`
}
func (res updateGroupRes) Code() int {
@@ -141,7 +140,7 @@ func (res updateGroupRes) Empty() bool {
}
type changeStatusRes struct {
mfgroups.Group `json:",inline"`
groups.Group `json:",inline"`
}
func (res changeStatusRes) Code() int {
@@ -186,7 +185,7 @@ func (res unassignRes) Empty() bool {
type listMembersRes struct {
pageRes
Members []mfgroups.Member `json:"members"`
Members []groups.Member `json:"members"`
}
func (res listMembersRes) Code() int {
+4
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package postgres
import (
@@ -243,6 +246,7 @@ func (repo groupRepository) RetrieveByIDs(ctx context.Context, gm mfgroups.Page,
return page, nil
}
func buildHierachy(gm mfgroups.Page) string {
query := ""
switch {
-1
View File
@@ -35,5 +35,4 @@ func Migration() *migrate.MemoryMigrationSource {
},
},
}
}
+1 -21
View File
@@ -17,16 +17,6 @@ import (
var errParentUnAuthz = errors.New("failed to authorize parent group")
// Possible token types are access and refresh tokens.
const (
RefreshToken = "refresh"
AccessToken = "access"
MyKey = "mine"
groupsObjectKey = "groups"
)
const (
ownerRelation = "owner"
channelRelation = "channel"
@@ -209,7 +199,6 @@ func (svc service) ListGroups(ctx context.Context, token string, memberKind, mem
Permission: gm.Permission,
ObjectType: groupType,
})
if err != nil {
return groups.Page{}, err
}
@@ -332,17 +321,12 @@ func (svc service) DisableGroup(ctx context.Context, token, id string) (groups.G
return group, nil
}
// Yet to do
func (svc service) Assign(ctx context.Context, token, groupID, relation, memberKind string, memberIDs ...string) error {
_, err := svc.authorize(ctx, userType, token, editPermission, groupType, groupID)
if err != nil {
return err
}
// if err := svc.groups.Assign(ctx, groupID, memberKind, memberIDs...); err != nil {
// return err
// }
prs := []*mainflux.AddPolicyReq{}
switch memberKind {
case thingsKind:
@@ -387,7 +371,6 @@ func (svc service) Assign(ctx context.Context, token, groupID, relation, memberK
return nil
}
// Yet to do
func (svc service) Unassign(ctx context.Context, token, groupID, relation, memberKind string, memberIDs ...string) error {
_, err := svc.authorize(ctx, userType, token, editPermission, groupType, groupID)
if err != nil {
@@ -436,9 +419,7 @@ func (svc service) Unassign(ctx context.Context, token, groupID, relation, membe
return fmt.Errorf("failed to delete policies : %w", err)
}
}
// if err := svc.groups.Unassign(ctx, groupID, memberIDs...); err != nil {
// return err
// }
return nil
}
@@ -466,7 +447,6 @@ func (svc service) listAllGroupsOfUserID(ctx context.Context, userID string, per
Permission: permission,
ObjectType: groupType,
})
if err != nil {
return []string{}, err
}
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package coap
import (
-1
View File
@@ -111,7 +111,6 @@ func (s *Server) Start() error {
}
default:
s.Logger.Info(fmt.Sprintf("%s service gRPC server listening at %s without TLS", s.Name, s.Address))
}
grpcServerOptions = append(grpcServerOptions, creds)
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package testsutil
import (
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package logger
import "os"
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package events
type createThingEvent struct {
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package mqtt
// LoraSubscribe subscribe to lora server messages.
+1 -1
View File
@@ -224,7 +224,7 @@ func (h *handler) Disconnect(ctx context.Context) error {
func (h *handler) authAccess(ctx context.Context, password, topic, action string) error {
// Topics are in the format:
// channels/<channel_id>/messages/<subtopic>/.../ct/<content_type>
if !channelRegExp.Match([]byte(topic)) {
if !channelRegExp.MatchString(topic) {
return ErrMalformedTopic
}
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package mocks
import (
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package mocks
import (
+2 -2
View File
@@ -97,7 +97,7 @@ func (c client) Subscribe(ctx context.Context, cfg opcua.Config) error {
}
oc := opcuagopcua.NewClient(cfg.ServerURI, opts...)
if err := oc.Connect(c.ctx); err != nil {
if err := oc.Connect(ctx); err != nil {
return errors.Wrap(errFailedConn, err)
}
defer oc.Close()
@@ -143,7 +143,7 @@ func (c client) runHandler(ctx context.Context, sub *opcuagopcua.Subscription, u
return errResponseStatus
}
go sub.Run(c.ctx)
go sub.Run(ctx)
c.logger.Info(fmt.Sprintf("subscribed to server %s and node_id %s", uri, node))
+1 -1
View File
@@ -13,6 +13,6 @@ type RouteMapRepository interface {
// Get returns the stored Mainflux route-map for a given OPC-UA pair.
Get(context.Context, string) (string, error)
// Remove Remove route-map from cache.
// Remove route-map from cache.
Remove(context.Context, string) error
}
+3 -1
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package postgres
import (
@@ -426,7 +429,6 @@ func pageQuery(pm clients.Page) (string, error) {
if len(query) > 0 {
emq = fmt.Sprintf("WHERE %s", strings.Join(query, " AND "))
}
return emq, nil
}
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package clients
import (
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package clients
import (
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package clients
// Metadata represents arbitrary JSON.
+2 -2
View File
@@ -33,7 +33,7 @@ type testEvent struct {
}
func (te testEvent) Encode() (map[string]interface{}, error) {
var data = make(map[string]interface{})
data := make(map[string]interface{})
for k, v := range te.Data {
switch v.(type) {
case string:
@@ -123,7 +123,7 @@ func TestPublish(t *testing.T) {
}
for _, tc := range cases {
var event = testEvent{Data: tc.event}
event := testEvent{Data: tc.event}
err := publisher.Publish(context.Background(), event)
switch tc.err {
+4 -1
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package redis
import (
@@ -99,7 +102,7 @@ func (re redisEvent) Encode() (map[string]interface{}, error) {
func (es *subEventStore) handle(ctx context.Context, msgs []redis.XMessage, h events.EventHandler) {
for _, msg := range msgs {
var event = redisEvent{
event := redisEvent{
Data: msg.Values,
}
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package groups
import "github.com/mainflux/mainflux/pkg/clients"
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package sdk_test
// import (
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package sdk
import (
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package sdk_test
// import (
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package sdk_test
// import (
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package sdk
import (
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package sdk_test
// import (
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package sdk
import (
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package sdk_test
// import (
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package sdk
import (
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package sdk_test
// import (
+4 -4
View File
@@ -18,7 +18,7 @@ const (
validPayload = `{"key1": "val1", "key2": 123, "key3": "val3", "key4": {"key5": "val5"}}`
tsPayload = `{"custom_ts_key": "1638310819", "key1": "val1", "key2": 123, "key3": "val3", "key4": {"key5": "val5"}}`
microsPayload = `{"custom_ts_micro_key": "1638310819000000", "key1": "val1", "key2": 123, "key3": "val3", "key4": {"key5": "val5"}}`
invalidTsPayload = `{"custom_ts_key": "abc", "key1": "val1", "key2": 123, "key3": "val3", "key4": {"key5": "val5"}}`
invalidTSPayload = `{"custom_ts_key": "abc", "key1": "val1", "key2": 123, "key3": "val3", "key4": {"key5": "val5"}}`
listPayload = `[{"key1": "val1", "key2": 123, "keylist3": "val3", "key4": {"key5": "val5"}}, {"key1": "val1", "key2": 123, "key3": "val3", "key4": {"key5": "val5"}}]`
invalidPayload = `{"key1": }`
)
@@ -93,7 +93,7 @@ func TestTransformJSON(t *testing.T) {
Subtopic: "subtopic-1",
Publisher: "publisher-1",
Protocol: "protocol",
Payload: []byte(invalidTsPayload),
Payload: []byte(invalidTSPayload),
Created: now,
}
@@ -118,7 +118,7 @@ func TestTransformJSON(t *testing.T) {
Format: msg.Subtopic,
}
jsonTsMsgs := json.Messages{
jsonTSMsgs := json.Messages{
Data: []json.Message{
{
Channel: msg.Channel,
@@ -231,7 +231,7 @@ func TestTransformJSON(t *testing.T) {
{
desc: "test transform JSON with timestamp transformation",
msg: &tsMsg,
json: jsonTsMsgs,
json: jsonTSMsgs,
err: nil,
},
{
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package api
import (
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package api
import (
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package api
import (
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package api
import (
+3 -1
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package provision
import (
@@ -243,7 +246,6 @@ func (ps *provisionService) Provision(token, name, externalID, externalKey strin
}
res.Whitelisted[thing.ID] = true
}
}
if err = ps.updateGateway(token, bsConfig, channels); err != nil {
+1 -2
View File
@@ -43,8 +43,7 @@ var (
vd = "dataValue"
sum float64 = 42
idProvider = uuid.New()
adminRelationKeys = []string{"c_update", "c_list", "c_delete", "c_share"}
idProvider = uuid.New()
)
func newServer(repo readers.MessageRepository) *httptest.Server {
+1 -4
View File
@@ -57,10 +57,7 @@ const (
viewPermission = "view"
)
var (
errThingAccess = errors.New("thing has no permission")
errUserAccess = errors.New("user has no permission")
)
var errUserAccess = errors.New("user has no permission")
// MakeHandler returns a HTTP handler for API endpoints.
func MakeHandler(svc readers.MessageRepository, ac mainflux.AuthServiceClient, svcName, instanceID string) http.Handler {
-1
View File
@@ -94,7 +94,6 @@ func (tr postgresRepository) ReadAll(chanID string, rpm readers.PageMetadata) (r
}
page.Messages = append(page.Messages, m)
}
}
q = fmt.Sprintf(`SELECT COUNT(*) FROM %s WHERE %s;`, format, cond)
-1
View File
@@ -92,7 +92,6 @@ func (tr timescaleRepository) ReadAll(chanID string, rpm readers.PageMetadata) (
}
page.Messages = append(page.Messages, m)
}
}
q = fmt.Sprintf(`SELECT COUNT(*) FROM %s WHERE %s;`, format, fmtCondition(chanID, rpm))
-1
View File
@@ -535,7 +535,6 @@ func TestReadJSON(t *testing.T) {
msgs1 := []map[string]interface{}{}
timeNow := time.Now().UnixMilli()
for i := 0; i < msgsNum; i++ {
m := json.Message{
Channel: id1,
Publisher: id1,
-1
View File
@@ -108,7 +108,6 @@ func clientsHandler(svc things.Service, r *chi.Mux, logger mflog.Logger) http.Ha
api.EncodeResponse,
opts...,
), "thing_delete_share").ServeHTTP)
})
// Ideal location: things service, channels endpoint
+1
View File
@@ -283,6 +283,7 @@ func unassignUsersGroupsEndpoint(svc groups.Service) endpoint.Endpoint {
return unassignUsersGroupsRes{}, nil
}
}
func assignUsersEndpoint(svc groups.Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(assignUsersRequest)
+8 -16
View File
@@ -155,8 +155,7 @@ func (res deleteClientRes) Empty() bool {
return false
}
type assignUsersGroupsRes struct {
}
type assignUsersGroupsRes struct{}
func (res assignUsersGroupsRes) Code() int {
return http.StatusOK
@@ -170,8 +169,7 @@ func (res assignUsersGroupsRes) Empty() bool {
return true
}
type unassignUsersGroupsRes struct {
}
type unassignUsersGroupsRes struct{}
func (res unassignUsersGroupsRes) Code() int {
return http.StatusNoContent
@@ -185,8 +183,7 @@ func (res unassignUsersGroupsRes) Empty() bool {
return true
}
type assignUsersRes struct {
}
type assignUsersRes struct{}
func (res assignUsersRes) Code() int {
return http.StatusOK
@@ -200,8 +197,7 @@ func (res assignUsersRes) Empty() bool {
return true
}
type unassignUsersRes struct {
}
type unassignUsersRes struct{}
func (res unassignUsersRes) Code() int {
return http.StatusNoContent
@@ -215,8 +211,7 @@ func (res unassignUsersRes) Empty() bool {
return true
}
type assignUserGroupsRes struct {
}
type assignUserGroupsRes struct{}
func (res assignUserGroupsRes) Code() int {
return http.StatusOK
@@ -230,8 +225,7 @@ func (res assignUserGroupsRes) Empty() bool {
return true
}
type unassignUserGroupsRes struct {
}
type unassignUserGroupsRes struct{}
func (res unassignUserGroupsRes) Code() int {
return http.StatusNoContent
@@ -245,8 +239,7 @@ func (res unassignUserGroupsRes) Empty() bool {
return true
}
type connectChannelThingRes struct {
}
type connectChannelThingRes struct{}
func (res connectChannelThingRes) Code() int {
return http.StatusOK
@@ -260,8 +253,7 @@ func (res connectChannelThingRes) Empty() bool {
return true
}
type disconnectChannelThingRes struct {
}
type disconnectChannelThingRes struct{}
func (res disconnectChannelThingRes) Code() int {
return http.StatusNoContent
+1 -1
View File
@@ -314,7 +314,7 @@ type authorizeClientEvent struct {
}
func (ice authorizeClientEvent) Encode() (map[string]interface{}, error) {
var val = map[string]interface{}{
val := map[string]interface{}{
"operation": clientAuthorize,
"thing_id": ice.thingID,
}
-45
View File
@@ -15,10 +15,6 @@ import (
)
const (
myKey = "mine"
listRelationKey = "c_list"
ownerRelation = "owner"
groupRelation = "group"
@@ -154,46 +150,6 @@ func (svc service) ListClients(ctx context.Context, token string, pm mfclients.P
}
pm.IDs = tids.Policies
// switch err {
// // If the user is admin, fetch all things from database.
// case nil:
// switch {
// // visibility = all
// case pm.SharedBy == myKey && pm.Owner == myKey:
// pm.SharedBy = ""
// pm.Owner = ""
// // visibility = shared
// case pm.SharedBy == myKey && pm.Owner != myKey:
// pm.SharedBy = userID
// pm.Owner = ""
// // visibility = mine
// case pm.Owner == myKey && pm.SharedBy != myKey:
// pm.Owner = userID
// pm.SharedBy = ""
// }
// default:
// // If the user is not admin, check 'sharedby' parameter from page metadata.
// // If user provides 'sharedby' key, fetch things from policies. Otherwise,
// // fetch things from the database based on thing's 'owner' field.
// switch {
// // visibility = all
// case pm.SharedBy == myKey && pm.Owner == myKey:
// pm.SharedBy = userID
// pm.Owner = userID
// // visibility = shared
// case pm.SharedBy == myKey && pm.Owner != myKey:
// pm.SharedBy = userID
// pm.Owner = ""
// // visibility = mine
// case pm.Owner == myKey && pm.SharedBy != myKey:
// pm.Owner = userID
// pm.SharedBy = ""
// default:
// pm.Owner = userID
// }
// pm.Action = listRelationKey
// }
return svc.clients.RetrieveAllByIDs(ctx, pm)
}
@@ -377,7 +333,6 @@ func (svc service) ListClientsByGroup(ctx context.Context, token, groupID string
})
if err != nil {
return mfclients.MembersPage{}, err
}
pm.IDs = tids.Policies
+8
View File
@@ -29,6 +29,7 @@ func NewAuthService(id, token string) mainflux.AuthServiceClient {
func (repo singleUserRepo) Login(ctx context.Context, in *mainflux.LoginReq, opts ...grpc.CallOption) (*mainflux.Token, error) {
return nil, nil
}
func (repo singleUserRepo) Refresh(ctx context.Context, in *mainflux.RefreshReq, opts ...grpc.CallOption) (*mainflux.Token, error) {
return nil, nil
}
@@ -56,24 +57,31 @@ func (repo singleUserRepo) Authorize(ctx context.Context, in *mainflux.Authorize
func (repo singleUserRepo) AddPolicy(ctx context.Context, in *mainflux.AddPolicyReq, opts ...grpc.CallOption) (*mainflux.AddPolicyRes, error) {
return nil, nil
}
func (repo singleUserRepo) DeletePolicy(ctx context.Context, in *mainflux.DeletePolicyReq, opts ...grpc.CallOption) (*mainflux.DeletePolicyRes, error) {
return nil, nil
}
func (repo singleUserRepo) ListObjects(ctx context.Context, in *mainflux.ListObjectsReq, opts ...grpc.CallOption) (*mainflux.ListObjectsRes, error) {
return nil, nil
}
func (repo singleUserRepo) ListAllObjects(ctx context.Context, in *mainflux.ListObjectsReq, opts ...grpc.CallOption) (*mainflux.ListObjectsRes, error) {
return nil, nil
}
func (repo singleUserRepo) CountObjects(ctx context.Context, in *mainflux.CountObjectsReq, opts ...grpc.CallOption) (*mainflux.CountObjectsRes, error) {
return nil, nil
}
func (repo singleUserRepo) ListSubjects(ctx context.Context, in *mainflux.ListSubjectsReq, opts ...grpc.CallOption) (*mainflux.ListSubjectsRes, error) {
return nil, nil
}
func (repo singleUserRepo) ListAllSubjects(ctx context.Context, in *mainflux.ListSubjectsReq, opts ...grpc.CallOption) (*mainflux.ListSubjectsRes, error) {
return nil, nil
}
func (repo singleUserRepo) CountSubjects(ctx context.Context, in *mainflux.CountSubjectsReq, opts ...grpc.CallOption) (*mainflux.CountSubjectsRes, error) {
return nil, nil
}
+5 -5
View File
@@ -180,7 +180,7 @@ func createUsers(s sdk.SDK, conf Config, token string) ([]sdk.User, error) {
user, err = s.CreateUser(user, token)
if err != nil {
return []sdk.User{}, fmt.Errorf("Failed to create the users: %w", err)
return []sdk.User{}, fmt.Errorf("failed to create the users: %w", err)
}
users = append(users, user)
}
@@ -202,7 +202,7 @@ func createGroups(s sdk.SDK, conf Config, token string) ([]sdk.Group, error) {
group, err = s.CreateGroup(group, token)
if err != nil {
return []sdk.Group{}, fmt.Errorf("Failed to create the group: %w", err)
return []sdk.Group{}, fmt.Errorf("failed to create the group: %w", err)
}
groups = append(groups, group)
parentID = group.ID
@@ -223,7 +223,7 @@ func createThings(s sdk.SDK, conf Config, token string) ([]sdk.Thing, error) {
}
things, err = s.CreateThings(things, token)
if err != nil {
return []sdk.Thing{}, fmt.Errorf("Failed to create the things: %w", err)
return []sdk.Thing{}, fmt.Errorf("failed to create the things: %w", err)
}
return things, nil
@@ -240,7 +240,7 @@ func createChannels(s sdk.SDK, conf Config, token string) ([]sdk.Channel, error)
}
channels[i], err = s.CreateChannel(channels[i], token)
if err != nil {
return []sdk.Channel{}, fmt.Errorf("Failed to create the channels: %w", err)
return []sdk.Channel{}, fmt.Errorf("failed to create the channels: %w", err)
}
}
@@ -462,7 +462,7 @@ func messaging(s sdk.SDK, conf Config, token string, things []sdk.Thing, channel
for _, thing := range things {
for _, channel := range channels {
var conn = sdk.Connection{
conn := sdk.Connection{
ThingID: thing.ID,
ChannelID: channel.ID,
Permission: "publish",
+3 -3
View File
@@ -45,12 +45,12 @@ func Benchmark(cfg Config) error {
data, err := os.ReadFile(cfg.Mf.ConnFile)
if err != nil {
return fmt.Errorf("Error loading connections file: %s", err)
return fmt.Errorf("error loading connections file: %s", err)
}
mf := mainflux{}
if err := toml.Unmarshal(data, &mf); err != nil {
return fmt.Errorf("Cannot load Mainflux connections config %s \nUse tools/provision to create file", cfg.Mf.ConnFile)
return fmt.Errorf("cannot load Mainflux connections config %s \nUse tools/provision to create file", cfg.Mf.ConnFile)
}
resCh := make(chan *runResults)
@@ -76,7 +76,7 @@ func Benchmark(cfg Config) error {
}
c, err := makeClient(i, cfg, mfChan, mfThing, startStamp, caByte, cert)
if err != nil {
return fmt.Errorf("Unable to create message payload %s", err.Error())
return fmt.Errorf("unable to create message payload %s", err.Error())
}
errorChan := make(chan error)
+4 -4
View File
@@ -83,7 +83,7 @@ func (c *Client) publish(r chan *runResults, errChan chan<- error) {
}
payload, err := c.SendMsg(&m)
if err != nil {
errChan <- fmt.Errorf("Failed to marshal payload - %s", err.Error())
errChan <- fmt.Errorf("failed to marshal payload - %s", err.Error())
}
for i := 0; i < c.MsgCount; i++ {
@@ -168,7 +168,7 @@ func (c *Client) connect() error {
func checkConnection(broker string, timeoutSecs int) error {
s := strings.Split(broker, ":")
if len(s) != 3 {
return errors.New("Wrong host address format")
return errors.New("wrong host address format")
}
network := s[0]
@@ -186,11 +186,11 @@ func checkConnection(broker string, timeoutSecs int) error {
defer conClose()
if err, ok := err.(*net.OpError); ok && err.Timeout() {
return fmt.Errorf("Timeout error: %s\n", err.Error())
return fmt.Errorf("timeout error: %s", err.Error())
}
if err != nil {
return fmt.Errorf("Error: %s\n", err.Error())
return fmt.Errorf("error: %s", err.Error())
}
log.Printf("Connection to %s://%s:%s looks OK\n", network, host, port)
-1
View File
@@ -93,7 +93,6 @@ func calculateTotalResults(results []*runResults, totalTime time.Duration, sr su
totals.MsgTimeMin = results[0].MsgTimeMin
for i, res := range results {
totals.Successes += res.Successes
totals.Failures += res.Failures
totals.TotalMsgsPerSec += res.MsgsPerSec
+23 -19
View File
@@ -84,7 +84,7 @@ func Provision(conf Config) error {
// Create new user
if _, err := s.CreateUser(user, ""); err != nil {
return fmt.Errorf("Unable to create new user: %s", err.Error())
return fmt.Errorf("unable to create new user: %s", err.Error())
}
var err error
@@ -92,7 +92,7 @@ func Provision(conf Config) error {
// Login user
token, err := s.CreateToken(user)
if err != nil {
return fmt.Errorf("Unable to login user: %s", err.Error())
return fmt.Errorf("unable to login user: %s", err.Error())
}
var tlsCert tls.Certificate
@@ -101,22 +101,22 @@ func Provision(conf Config) error {
if conf.SSL {
tlsCert, err = tls.LoadX509KeyPair(conf.CA, conf.CAKey)
if err != nil {
return fmt.Errorf("Failed to load CA cert")
return fmt.Errorf("failed to load CA cert")
}
b, err := os.ReadFile(conf.CA)
if err != nil {
return fmt.Errorf("Failed to load CA cert")
return fmt.Errorf("failed to load CA cert")
}
block, _ := pem.Decode(b)
if block == nil {
return fmt.Errorf("No PEM data found, failed to decode CA")
return fmt.Errorf("no PEM data found, failed to decode CA")
}
caCert, err = x509.ParseCertificate(block.Bytes)
if err != nil {
return fmt.Errorf("Failed to decode certificate - %s", err.Error())
return fmt.Errorf("failed to decode certificate - %s", err.Error())
}
}
@@ -135,12 +135,12 @@ func Provision(conf Config) error {
things, err = s.CreateThings(things, token.AccessToken)
if err != nil {
return fmt.Errorf("Failed to create the things: %s", err.Error())
return fmt.Errorf("failed to create the things: %s", err.Error())
}
channels, err = s.CreateChannels(channels, token.AccessToken)
if err != nil {
return fmt.Errorf("Failed to create the chennels: %s", err.Error())
return fmt.Errorf("failed to create the chennels: %s", err.Error())
}
for _, t := range things {
@@ -162,14 +162,14 @@ func Provision(conf Config) error {
notBefore := time.Now()
validFor, err := time.ParseDuration(ttl)
if err != nil {
return fmt.Errorf("Failed to set date %v", validFor)
return fmt.Errorf("failed to set date %v", validFor)
}
notAfter := notBefore.Add(validFor)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return fmt.Errorf("Failed to generate serial number: %s", err)
return fmt.Errorf("failed to generate serial number: %s", err)
}
tmpl := x509.Certificate{
@@ -189,7 +189,7 @@ func Provision(conf Config) error {
derBytes, err := x509.CreateCertificate(rand.Reader, &tmpl, caCert, publicKey(priv), tlsCert.PrivateKey)
if err != nil {
return fmt.Errorf("Failed to create certificate: %s", err)
return fmt.Errorf("failed to create certificate: %s", err)
}
var bw, keyOut bytes.Buffer
@@ -197,13 +197,13 @@ func Provision(conf Config) error {
buffKeyOut := bufio.NewWriter(&keyOut)
if err := pem.Encode(buffWriter, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
return fmt.Errorf("Failed to write cert pem data: %s", err)
return fmt.Errorf("failed to write cert pem data: %s", err)
}
buffWriter.Flush()
cert = bw.String()
if err := pem.Encode(buffKeyOut, pemBlockForKey(priv)); err != nil {
return fmt.Errorf("Failed to write key pem data: %s", err)
return fmt.Errorf("failed to write key pem data: %s", err)
}
buffKeyOut.Flush()
key = keyOut.String()
@@ -224,13 +224,17 @@ func Provision(conf Config) error {
fmt.Printf("[[channels]]\nchannel_id = \"%s\"\n\n", cIDs[i])
}
conIDs := sdk.ConnectionIDs{
ChannelIDs: cIDs,
ThingIDs: tIDs,
}
if err := s.Connect(conIDs, token.AccessToken); err != nil {
log.Fatalf("Failed to connect things %s to channels %s: %s", conIDs.ThingIDs, conIDs.ChannelIDs, err)
for i := 0; i < conf.Num; i++ {
conIDs := sdk.Connection{
ChannelID: cIDs[i],
ThingID: tIDs[i],
}
if err := s.Connect(conIDs, token.AccessToken); err != nil {
log.Fatalf("Failed to connect thing %s to channel %s: %s", conIDs.ThingID, conIDs.ChannelID, err)
}
}
return nil
}
+3
View File
@@ -1,3 +1,6 @@
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package mocks
import (
+1 -1
View File
@@ -243,7 +243,7 @@ func decodeListClients(_ context.Context, r *http.Request) (interface{}, error)
sharedBy: sharedID,
owner: ownerID,
}
return req, nil
}
-2
View File
@@ -17,7 +17,6 @@ import (
"github.com/mainflux/mainflux/logger"
"github.com/mainflux/mainflux/pkg/errors"
"github.com/mainflux/mainflux/pkg/groups"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
@@ -115,7 +114,6 @@ func groupsHandler(svc groups.Service, r *chi.Mux, logger logger.Logger) http.Ha
api.EncodeResponse,
opts...,
), "unassign_users").ServeHTTP)
})
// The ideal placeholder name should be {channelID}, but gapi.DecodeListGroupsRequest uses {memberID} as a placeholder for the ID.

Some files were not shown because too many files have changed in this diff Show More