diff --git a/api/openapi/things.yml b/api/openapi/things.yml index 6460d8f37..4ed91b8cd 100644 --- a/api/openapi/things.yml +++ b/api/openapi/things.yml @@ -79,7 +79,6 @@ paths: - $ref: "#/components/parameters/Status" - $ref: "#/components/parameters/ThingName" - $ref: "#/components/parameters/Tags" - - $ref: "#/components/parameters/Owner" security: - bearerAuth: [] responses: @@ -382,8 +381,7 @@ paths: - Channels summary: Creates new channel description: | - Creates new channel. User identified by the provided access token will - be the channel's owner. + Creates new channel in domain. requestBody: $ref: "#/components/requestBodies/ChannelCreateReq" security: @@ -418,7 +416,6 @@ paths: - $ref: "#/components/parameters/Offset" - $ref: "#/components/parameters/Metadata" - $ref: "#/components/parameters/ChannelName" - - $ref: "#/components/parameters/OwnerId" responses: "200": $ref: "#/components/responses/ChannelPageRes" @@ -880,14 +877,9 @@ components: example: bb7edb32-2eac-4aad-aebe-ed96fe073879 minimum: 8 description: Free-form account secret used for acquiring auth token(s). - owner: - type: string - format: uuid - example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - description: Thing owner must be exsiting in the databse. metadata: type: object - example: { "domain": "example.com" } + example: { "model": "example" } description: Arbitrary, object-encoded thing's data. status: type: string @@ -914,18 +906,13 @@ components: description: Id of parent channel, it must be existing channel. metadata: type: object - example: { "domain": "example.com" } + example: { "location": "example" } description: Arbitrary, object-encoded channels's data. status: type: string description: Channel Status format: string example: enabled - owner_id: - type: string - format: uuid - example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - description: Channel owner ID must be exsiting in the databse. required: - name @@ -1039,11 +1026,11 @@ components: type: string example: ["tag1", "tag2"] description: Thing tags. - owner: + domain_id: type: string format: uuid example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - description: Thing owner identifier. + description: ID of the domain to which thing belongs. credentials: type: object properties: @@ -1057,7 +1044,7 @@ components: description: Thing secret password. metadata: type: object - example: { "domain": "example.com" } + example: { "model": "example" } description: Arbitrary, object-encoded thing's data. status: type: string @@ -1096,11 +1083,11 @@ components: type: string example: ["tag1", "tag2"] description: Thing tags. - owner: + domain_id: type: string format: uuid example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - description: Thing owner identifier. + description: ID of the domain to which thing belongs. credentials: type: object properties: @@ -1114,7 +1101,7 @@ components: description: Thing secret password. metadata: type: object - example: { "domain": "example.com" } + example: { "model": "example" } description: Arbitrary, object-encoded thing's data. status: type: string @@ -1146,11 +1133,11 @@ components: type: string example: channelName description: Free-form channel name. Channel name is unique on the given hierarchy level. - owner_id: + domain_id: type: string format: uuid example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - description: Channel owner identifier of thing that created the channel.. + description: ID of the domain to which the group belongs. parent_id: type: string format: uuid @@ -1342,16 +1329,6 @@ components: required: - secret - ThingOwner: - type: object - properties: - owner: - type: string - example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - description: Thing owner for example email address. - required: - - owner - ChannelUpdate: type: object properties: @@ -1468,35 +1445,6 @@ components: required: false example: "thingName" - ThingIdentity: - name: identity - description: Thing's identity. - in: query - schema: - type: string - required: false - example: "admin@example.com" - - Owner: - name: owner_id - description: Thing's owner. - in: query - schema: - type: string - format: uuid - required: false - example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - - ThingOwner: - name: owner - description: Unique owner identifier for a thing. - in: query - schema: - type: string - format: uuid - required: false - example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - Status: name: status description: Thing account status. @@ -1577,16 +1525,6 @@ components: type: boolean default: false - OwnerId: - name: ownerId - description: Unique owner identifier for a channel. - in: query - schema: - type: string - format: uuid - required: false - example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - Metadata: name: metadata description: Metadata filter. Filtering is performed matching the parameter with metadata on top level. Parameter is json. diff --git a/api/openapi/users.yml b/api/openapi/users.yml index 4868c08e9..e4dd97b3b 100644 --- a/api/openapi/users.yml +++ b/api/openapi/users.yml @@ -73,8 +73,6 @@ paths: - $ref: "#/components/parameters/UserName" - $ref: "#/components/parameters/UserIdentity" - $ref: "#/components/parameters/Tags" - - $ref: "#/components/parameters/Owner" - - $ref: "#/components/parameters/UserVisibility" security: - bearerAuth: [] responses: @@ -376,7 +374,6 @@ paths: - $ref: "#/components/parameters/Metadata" - $ref: "#/components/parameters/GroupName" - $ref: "#/components/parameters/ParentID" - - $ref: "#/components/parameters/OwnerID" responses: "200": $ref: "#/components/responses/MembersPageRes" @@ -412,7 +409,6 @@ paths: - $ref: "#/components/parameters/Metadata" - $ref: "#/components/parameters/ChannelName" - $ref: "#/components/parameters/ParentID" - - $ref: "#/components/parameters/OwnerID" responses: "200": $ref: "#/components/responses/MembersPageRes" @@ -512,7 +508,6 @@ paths: - $ref: "#/components/parameters/Metadata" - $ref: "#/components/parameters/GroupName" - $ref: "#/components/parameters/ParentID" - - $ref: "#/components/parameters/OwnerID" responses: "200": $ref: "#/components/responses/GroupPageRes" @@ -613,7 +608,6 @@ paths: - $ref: "#/components/parameters/Metadata" - $ref: "#/components/parameters/GroupName" - $ref: "#/components/parameters/ParentID" - - $ref: "#/components/parameters/OwnerID" responses: "200": $ref: "#/components/responses/GroupPageRes" @@ -647,7 +641,6 @@ paths: - $ref: "#/components/parameters/Metadata" - $ref: "#/components/parameters/GroupName" - $ref: "#/components/parameters/ParentID" - - $ref: "#/components/parameters/OwnerID" responses: "200": $ref: "#/components/responses/GroupPageRes" @@ -890,11 +883,6 @@ components: example: password minimum: 8 description: Free-form account secret used for acquiring auth token(s). - owner: - type: string - format: uuid - example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - description: User owner must be exsiting in the databse. metadata: type: object example: { "domain": "example.com" } @@ -931,11 +919,6 @@ components: description: Group Status format: string example: enabled - owner_id: - type: string - format: uuid - example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - description: Group owner ID must be exsiting in the databse. required: - name @@ -958,11 +941,6 @@ components: type: string example: ["tag1", "tag2"] description: User tags. - owner: - type: string - format: uuid - example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - description: User owner identifier. credentials: type: object properties: @@ -972,7 +950,7 @@ components: description: User Identity for example email address. metadata: type: object - example: { "domain": "example.com" } + example: { "address": "example" } description: Arbitrary, object-encoded user's data. status: type: string @@ -1004,11 +982,11 @@ components: type: string example: groupName description: Free-form group name. Group name is unique on the given hierarchy level. - owner_id: + domain_id: type: string format: uuid example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - description: Group owner identifier of user that created the group.. + description: ID of the domain to which the group belongs.. parent_id: type: string format: uuid @@ -1050,58 +1028,6 @@ components: xml: name: group - Memberships: - type: object - properties: - id: - type: string - format: uuid - example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - description: Unique group identifier generated by the service. - name: - type: string - example: groupName - description: Free-form group name. Group name is unique on the given hierarchy level. - owner_id: - type: string - format: uuid - example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - description: Group owner identifier of user that created the group.. - parent_id: - type: string - format: uuid - example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - description: Group parent identifier. - description: - type: string - example: long group description - description: Group description, free form text. - metadata: - type: object - example: { "role": "general" } - description: Arbitrary, object-encoded groups's data. - path: - type: string - example: bb7edb32-2eac-4aad-aebe-ed96fe073879.bb7edb32-2eac-4aad-aebe-ed96fe073879 - description: Hierarchy path, concatenated ids of group ancestors. - level: - type: integer - description: Level in hierarchy, distance from the root group. - format: int32 - example: 2 - created_at: - type: string - format: date-time - example: "2019-11-26 13:31:52" - description: Datetime when the group was created. - updated_at: - type: string - format: date-time - example: "2019-11-26 13:31:52" - description: Datetime when the group was created. - xml: - name: memberships - Members: type: object properties: @@ -1121,11 +1047,6 @@ components: type: string example: ["computations", "datasets"] description: User tags. - owner: - type: string - format: uuid - example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - description: User owner identifier. credentials: type: object properties: @@ -1209,31 +1130,6 @@ components: - total - level - MembershipsPage: - type: object - properties: - memberships: - type: array - minItems: 0 - uniqueItems: true - items: - $ref: "#/components/schemas/Memberships" - total: - type: integer - example: 1 - description: Total number of items. - offset: - type: integer - description: Number of items to skip during retrieval. - limit: - type: integer - example: 10 - description: Maximum number of items to return in one page. - required: - - memberships - - total - - level - MembersPage: type: object properties: @@ -1320,7 +1216,7 @@ components: example: user description: User role example. required: - - owner + - role GroupUpdate: type: object @@ -1476,26 +1372,6 @@ components: required: false example: "admin@example.com" - Owner: - name: owner_id - description: User's owner. - in: query - schema: - type: string - format: uuid - required: false - example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - - UserOwner: - name: owner - description: Unique owner identifier for a user. - in: query - schema: - type: string - format: uuid - required: false - example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - Status: name: status description: User account status. @@ -1605,16 +1481,6 @@ components: type: boolean default: false - OwnerID: - name: ownerID - description: Unique owner identifier for a group. - in: query - schema: - type: string - format: uuid - required: false - example: bb7edb32-2eac-4aad-aebe-ed96fe073879 - Metadata: name: metadata description: Metadata filter. Filtering is performed matching the parameter with metadata on top level. Parameter is json. @@ -1816,13 +1682,6 @@ components: schema: $ref: "#/components/schemas/UsersPage" - MembershipsPageRes: - description: Memberships associated with the user. - content: - application/json: - schema: - $ref: "#/components/schemas/MembershipsPage" - GroupCreateRes: description: Registered new group. headers: diff --git a/cli/things.go b/cli/things.go index 0faf5e6d5..f7c1f4b4b 100644 --- a/cli/things.go +++ b/cli/things.go @@ -121,9 +121,9 @@ var cmdThings = []cobra.Command{ }, }, { - Use: "update [ | tags | secret | owner ] ", + Use: "update [ | tags | secret ] ", Short: "Update thing", - Long: "Updates thing with provided id, name and metadata, or updates thing tags, secret or owner\n" + + Long: "Updates thing with provided id, name and metadata, or updates thing tags, secret\n" + "Usage:\n" + "\tmagistrala-cli things update '{\"name\":\"new name\", \"metadata\":{\"key\": \"value\"}}' $USERTOKEN\n" + "\tmagistrala-cli things update tags '{\"tag1\":\"value1\", \"tag2\":\"value2\"}' $USERTOKEN\n" + diff --git a/cli/users.go b/cli/users.go index 3439ef00e..3857f5f28 100644 --- a/cli/users.go +++ b/cli/users.go @@ -142,9 +142,9 @@ var cmdUsers = []cobra.Command{ }, }, { - Use: "update [ | tags | identity | owner ] ", + Use: "update [ | tags | identity ] ", Short: "Update user", - Long: "Updates either user name and metadata or user tags or user identity or user owner\n" + + Long: "Updates either user name and metadata or user tags or user identity\n" + "Usage:\n" + "\tmagistrala-cli users update '{\"name\":\"new name\", \"metadata\":{\"key\": \"value\"}}' $USERTOKEN - updates user name and metadata\n" + "\tmagistrala-cli users update tags '[\"tag1\", \"tag2\"]' $USERTOKEN - updates user tags\n" + diff --git a/internal/groups/api/decode.go b/internal/groups/api/decode.go index 97377ebd6..e4b618a03 100644 --- a/internal/groups/api/decode.go +++ b/internal/groups/api/decode.go @@ -268,10 +268,6 @@ func decodePageMeta(r *http.Request) (mggroups.PageMeta, error) { if err != nil { return mggroups.PageMeta{}, errors.Wrap(apiutil.ErrValidation, err) } - ownerID, err := apiutil.ReadStringQuery(r, api.OwnerKey, "") - if err != nil { - return mggroups.PageMeta{}, errors.Wrap(apiutil.ErrValidation, err) - } name, err := apiutil.ReadStringQuery(r, api.NameKey, "") if err != nil { return mggroups.PageMeta{}, errors.Wrap(apiutil.ErrValidation, err) @@ -285,7 +281,6 @@ func decodePageMeta(r *http.Request) (mggroups.PageMeta, error) { Offset: offset, Limit: limit, Name: name, - OwnerID: ownerID, Metadata: meta, Status: st, } diff --git a/internal/groups/api/decode_test.go b/internal/groups/api/decode_test.go index b8ec6e7cd..3e2e392b3 100644 --- a/internal/groups/api/decode_test.go +++ b/internal/groups/api/decode_test.go @@ -44,18 +44,17 @@ func TestDecodeListGroupsRequest(t *testing.T) { }, { desc: "valid request with all parameters", - url: "http://localhost:8080?status=enabled&offset=10&limit=10&owner_id=random&name=random&metadata={\"test\":\"test\"}&level=2&parent_id=random&tree=true&dir=-1&member_kind=random&permission=random&list_perms=true", + url: "http://localhost:8080?status=enabled&offset=10&limit=10&name=random&metadata={\"test\":\"test\"}&level=2&parent_id=random&tree=true&dir=-1&member_kind=random&permission=random&list_perms=true", header: map[string][]string{ "Authorization": {"Bearer 123"}, }, resp: listGroupsReq{ Page: groups.Page{ PageMeta: groups.PageMeta{ - Status: clients.EnabledStatus, - Offset: 10, - Limit: 10, - OwnerID: "random", - Name: "random", + Status: clients.EnabledStatus, + Offset: 10, + Limit: 10, + Name: "random", Metadata: clients.Metadata{ "test": "test", }, @@ -161,18 +160,17 @@ func TestDecodeListParentsRequest(t *testing.T) { }, { desc: "valid request with all parameters", - url: "http://localhost:8080?status=enabled&offset=10&limit=10&owner_id=random&name=random&metadata={\"test\":\"test\"}&level=2&parent_id=random&tree=true&dir=-1&member_kind=random&permission=random&list_perms=true", + url: "http://localhost:8080?status=enabled&offset=10&limit=10&name=random&metadata={\"test\":\"test\"}&level=2&parent_id=random&tree=true&dir=-1&member_kind=random&permission=random&list_perms=true", header: map[string][]string{ "Authorization": {"Bearer 123"}, }, resp: listGroupsReq{ Page: groups.Page{ PageMeta: groups.PageMeta{ - Status: clients.EnabledStatus, - Offset: 10, - Limit: 10, - OwnerID: "random", - Name: "random", + Status: clients.EnabledStatus, + Offset: 10, + Limit: 10, + Name: "random", Metadata: clients.Metadata{ "test": "test", }, @@ -258,18 +256,17 @@ func TestDecodeListChildrenRequest(t *testing.T) { }, { desc: "valid request with all parameters", - url: "http://localhost:8080?status=enabled&offset=10&limit=10&owner_id=random&name=random&metadata={\"test\":\"test\"}&level=2&parent_id=random&tree=true&dir=-1&member_kind=random&permission=random&list_perms=true", + url: "http://localhost:8080?status=enabled&offset=10&limit=10&name=random&metadata={\"test\":\"test\"}&level=2&parent_id=random&tree=true&dir=-1&member_kind=random&permission=random&list_perms=true", header: map[string][]string{ "Authorization": {"Bearer 123"}, }, resp: listGroupsReq{ Page: groups.Page{ PageMeta: groups.PageMeta{ - Status: clients.EnabledStatus, - Offset: 10, - Limit: 10, - OwnerID: "random", - Name: "random", + Status: clients.EnabledStatus, + Offset: 10, + Limit: 10, + Name: "random", Metadata: clients.Metadata{ "test": "test", }, @@ -405,13 +402,12 @@ func TestDecodePageMeta(t *testing.T) { }, { desc: "valid request with all parameters", - url: "http://localhost:8080?status=enabled&offset=10&limit=10&owner_id=random&name=random&metadata={\"test\":\"test\"}", + url: "http://localhost:8080?status=enabled&offset=10&limit=10&name=random&metadata={\"test\":\"test\"}", resp: groups.PageMeta{ - Status: clients.EnabledStatus, - Offset: 10, - Limit: 10, - OwnerID: "random", - Name: "random", + Status: clients.EnabledStatus, + Offset: 10, + Limit: 10, + Name: "random", Metadata: clients.Metadata{ "test": "test", }, @@ -442,12 +438,6 @@ func TestDecodePageMeta(t *testing.T) { resp: groups.PageMeta{}, err: apiutil.ErrValidation, }, - { - desc: "valid request with invalid owner_id", - url: "http://localhost:8080?owner_id=random&owner_id=random", - resp: groups.PageMeta{}, - err: apiutil.ErrValidation, - }, { desc: "valid request with invalid name", url: "http://localhost:8080?name=random&name=random", diff --git a/internal/groups/api/endpoint_test.go b/internal/groups/api/endpoint_test.go index 6444d16f9..04d4612e9 100644 --- a/internal/groups/api/endpoint_test.go +++ b/internal/groups/api/endpoint_test.go @@ -24,7 +24,7 @@ var validGroupResp = groups.Group{ ID: testsutil.GenerateUUID(&testing.T{}), Name: valid, Description: valid, - Owner: testsutil.GenerateUUID(&testing.T{}), + Domain: testsutil.GenerateUUID(&testing.T{}), Parent: testsutil.GenerateUUID(&testing.T{}), Metadata: clients.Metadata{ "name": "test", diff --git a/internal/groups/events/events.go b/internal/groups/events/events.go index 118a4fd88..880c7eddf 100644 --- a/internal/groups/events/events.go +++ b/internal/groups/events/events.go @@ -46,8 +46,8 @@ func (cge createGroupEvent) Encode() (map[string]interface{}, error) { "created_at": cge.CreatedAt, } - if cge.Owner != "" { - val["owner"] = cge.Owner + if cge.Domain != "" { + val["domain"] = cge.Domain } if cge.Parent != "" { val["parent"] = cge.Parent @@ -87,8 +87,8 @@ func (uge updateGroupEvent) Encode() (map[string]interface{}, error) { if uge.ID != "" { val["id"] = uge.ID } - if uge.Owner != "" { - val["owner"] = uge.Owner + if uge.Domain != "" { + val["domain"] = uge.Domain } if uge.Parent != "" { val["parent"] = uge.Parent @@ -144,8 +144,8 @@ func (vge viewGroupEvent) Encode() (map[string]interface{}, error) { "id": vge.ID, } - if vge.Owner != "" { - val["owner"] = vge.Owner + if vge.Domain != "" { + val["domain"] = vge.Domain } if vge.Parent != "" { val["parent"] = vge.Parent @@ -207,8 +207,8 @@ func (lge listGroupEvent) Encode() (map[string]interface{}, error) { if lge.Name != "" { val["name"] = lge.Name } - if lge.OwnerID != "" { - val["owner_id"] = lge.OwnerID + if lge.DomainID != "" { + val["domain_id"] = lge.DomainID } if lge.Tag != "" { val["tag"] = lge.Tag diff --git a/internal/groups/postgres/groups.go b/internal/groups/postgres/groups.go index 4077bf593..b653fb701 100644 --- a/internal/groups/postgres/groups.go +++ b/internal/groups/postgres/groups.go @@ -34,9 +34,9 @@ func New(db postgres.Database) mggroups.Repository { } func (repo groupRepository) Save(ctx context.Context, g mggroups.Group) (mggroups.Group, error) { - q := `INSERT INTO groups (name, description, id, owner_id, parent_id, metadata, created_at, status) - VALUES (:name, :description, :id, :owner_id, :parent_id, :metadata, :created_at, :status) - RETURNING id, name, description, owner_id, COALESCE(parent_id, '') AS parent_id, metadata, created_at, status;` + q := `INSERT INTO groups (name, description, id, domain_id, parent_id, metadata, created_at, status) + VALUES (:name, :description, :id, :domain_id, :parent_id, :metadata, :created_at, :status) + RETURNING id, name, description, domain_id, COALESCE(parent_id, '') AS parent_id, metadata, created_at, status;` dbg, err := toDBGroup(g) if err != nil { return mggroups.Group{}, err @@ -74,7 +74,7 @@ func (repo groupRepository) Update(ctx context.Context, g mggroups.Group) (mggro g.Status = mgclients.EnabledStatus q := fmt.Sprintf(`UPDATE groups SET %s updated_at = :updated_at, updated_by = :updated_by WHERE id = :id AND status = :status - RETURNING id, name, description, owner_id, COALESCE(parent_id, '') AS parent_id, metadata, created_at, updated_at, updated_by, status`, upq) + RETURNING id, name, description, domain_id, COALESCE(parent_id, '') AS parent_id, metadata, created_at, updated_at, updated_by, status`, upq) dbu, err := toDBGroup(g) if err != nil { @@ -99,7 +99,7 @@ func (repo groupRepository) Update(ctx context.Context, g mggroups.Group) (mggro func (repo groupRepository) ChangeStatus(ctx context.Context, group mggroups.Group) (mggroups.Group, error) { qc := `UPDATE groups SET status = :status, updated_at = :updated_at, updated_by = :updated_by WHERE id = :id - RETURNING id, name, description, owner_id, COALESCE(parent_id, '') AS parent_id, metadata, created_at, updated_at, updated_by, status` + RETURNING id, name, description, domain_id, COALESCE(parent_id, '') AS parent_id, metadata, created_at, updated_at, updated_by, status` dbg, err := toDBGroup(group) if err != nil { @@ -122,7 +122,7 @@ func (repo groupRepository) ChangeStatus(ctx context.Context, group mggroups.Gro } func (repo groupRepository) RetrieveByID(ctx context.Context, id string) (mggroups.Group, error) { - q := `SELECT id, name, owner_id, COALESCE(parent_id, '') AS parent_id, description, metadata, created_at, updated_at, updated_by, status FROM groups + q := `SELECT id, name, domain_id, COALESCE(parent_id, '') AS parent_id, description, metadata, created_at, updated_at, updated_by, status FROM groups WHERE id = :id` dbg := dbGroup{ @@ -153,7 +153,7 @@ func (repo groupRepository) RetrieveAll(ctx context.Context, gm mggroups.Page) ( q = buildHierachy(gm) } if gm.ID == "" { - q = `SELECT DISTINCT g.id, g.owner_id, COALESCE(g.parent_id, '') AS parent_id, g.name, g.description, + q = `SELECT DISTINCT g.id, g.domain_id, COALESCE(g.parent_id, '') AS parent_id, g.name, g.description, g.metadata, g.created_at, g.updated_at, g.updated_by, g.status FROM groups g` } q = fmt.Sprintf("%s %s ORDER BY g.created_at LIMIT :limit OFFSET :offset;", q, query) @@ -192,7 +192,7 @@ func (repo groupRepository) RetrieveAll(ctx context.Context, gm mggroups.Page) ( func (repo groupRepository) RetrieveByIDs(ctx context.Context, gm mggroups.Page, ids ...string) (mggroups.Page, error) { var q string - if (len(ids) <= 0) && (gm.PageMeta.OwnerID == "") { + if (len(ids) <= 0) && (gm.PageMeta.DomainID == "") { return mggroups.Page{PageMeta: mggroups.PageMeta{Offset: gm.Offset, Limit: gm.Limit}}, nil } query := buildQuery(gm, ids...) @@ -201,7 +201,7 @@ func (repo groupRepository) RetrieveByIDs(ctx context.Context, gm mggroups.Page, q = buildHierachy(gm) } if gm.ID == "" { - q = `SELECT DISTINCT g.id, g.owner_id, COALESCE(g.parent_id, '') AS parent_id, g.name, g.description, + q = `SELECT DISTINCT g.id, g.domain_id, COALESCE(g.parent_id, '') AS parent_id, g.name, g.description, g.metadata, g.created_at, g.updated_at, g.updated_by, g.status FROM groups g` } q = fmt.Sprintf("%s %s ORDER BY g.created_at LIMIT :limit OFFSET :offset;", q, query) @@ -310,15 +310,15 @@ func buildHierachy(gm mggroups.Page) string { switch { case gm.Direction >= 0: // ancestors query = `WITH RECURSIVE groups_cte as ( - SELECT id, COALESCE(parent_id, '') AS parent_id, owner_id, name, description, metadata, created_at, updated_at, updated_by, status, 0 as level from groups WHERE id = :id - UNION SELECT x.id, COALESCE(x.parent_id, '') AS parent_id, x.owner_id, x.name, x.description, x.metadata, x.created_at, x.updated_at, x.updated_by, x.status, level - 1 from groups x + SELECT id, COALESCE(parent_id, '') AS parent_id, domain_id, name, description, metadata, created_at, updated_at, updated_by, status, 0 as level from groups WHERE id = :id + UNION SELECT x.id, COALESCE(x.parent_id, '') AS parent_id, x.domain_id, x.name, x.description, x.metadata, x.created_at, x.updated_at, x.updated_by, x.status, level - 1 from groups x INNER JOIN groups_cte a ON a.parent_id = x.id ) SELECT * FROM groups_cte g` case gm.Direction < 0: // descendants query = `WITH RECURSIVE groups_cte as ( - SELECT id, COALESCE(parent_id, '') AS parent_id, owner_id, name, description, metadata, created_at, updated_at, updated_by, status, 0 as level, CONCAT('', '', id) as path from groups WHERE id = :id - UNION SELECT x.id, COALESCE(x.parent_id, '') AS parent_id, x.owner_id, x.name, x.description, x.metadata, x.created_at, x.updated_at, x.updated_by, x.status, level + 1, CONCAT(path, '.', x.id) as path from groups x + SELECT id, COALESCE(parent_id, '') AS parent_id, domain_id, name, description, metadata, created_at, updated_at, updated_by, status, 0 as level, CONCAT('', '', id) as path from groups WHERE id = :id + UNION SELECT x.id, COALESCE(x.parent_id, '') AS parent_id, x.domain_id, x.name, x.description, x.metadata, x.created_at, x.updated_at, x.updated_by, x.status, level + 1, CONCAT(path, '.', x.id) as path from groups x INNER JOIN groups_cte d ON d.id = x.parent_id ) SELECT * FROM groups_cte g` } @@ -337,8 +337,8 @@ func buildQuery(gm mggroups.Page, ids ...string) string { if gm.Status != mgclients.AllStatus { queries = append(queries, "g.status = :status") } - if gm.OwnerID != "" { - queries = append(queries, "g.owner_id = :owner_id") + if gm.DomainID != "" { + queries = append(queries, "g.domain_id = :domain_id") } if len(gm.Metadata) > 0 { queries = append(queries, "g.metadata @> :metadata") @@ -353,7 +353,7 @@ func buildQuery(gm mggroups.Page, ids ...string) string { type dbGroup struct { ID string `db:"id"` ParentID *string `db:"parent_id,omitempty"` - OwnerID string `db:"owner_id,omitempty"` + DomainID string `db:"domain_id,omitempty"` Name string `db:"name"` Description string `db:"description,omitempty"` Level int `db:"level"` @@ -390,7 +390,7 @@ func toDBGroup(g mggroups.Group) (dbGroup, error) { ID: g.ID, Name: g.Name, ParentID: parentID, - OwnerID: g.Owner, + DomainID: g.Domain, Description: g.Description, Metadata: data, Path: g.Path, @@ -425,7 +425,7 @@ func toGroup(g dbGroup) (mggroups.Group, error) { ID: g.ID, Name: g.Name, Parent: parentID, - Owner: g.OwnerID, + Domain: g.DomainID, Description: g.Description, Metadata: metadata, Level: g.Level, @@ -460,7 +460,7 @@ func toDBGroupPage(pm mggroups.Page) (dbGroupPage, error) { Offset: pm.Offset, Limit: pm.Limit, ParentID: pm.ID, - OwnerID: pm.OwnerID, + DomainID: pm.DomainID, Status: pm.Status, }, nil } @@ -470,7 +470,7 @@ type dbGroupPage struct { ID string `db:"id"` Name string `db:"name"` ParentID string `db:"parent_id"` - OwnerID string `db:"owner_id"` + DomainID string `db:"domain_id"` Metadata []byte `db:"metadata"` Path string `db:"path"` Level uint64 `db:"level"` diff --git a/internal/groups/postgres/groups_test.go b/internal/groups/postgres/groups_test.go index e29745cfe..7ade7e219 100644 --- a/internal/groups/postgres/groups_test.go +++ b/internal/groups/postgres/groups_test.go @@ -26,7 +26,7 @@ var ( invalidID = strings.Repeat("a", 37) validGroup = mggroups.Group{ ID: testsutil.GenerateUUID(&testing.T{}), - Owner: testsutil.GenerateUUID(&testing.T{}), + Domain: testsutil.GenerateUUID(&testing.T{}), Name: namegen.Generate(), Description: strings.Repeat("a", 64), Metadata: map[string]interface{}{"key": "value"}, @@ -62,7 +62,7 @@ func TestSave(t *testing.T) { desc: "add group with invalid ID", group: mggroups.Group{ ID: invalidID, - Owner: testsutil.GenerateUUID(t), + Domain: testsutil.GenerateUUID(t), Name: namegen.Generate(), Description: strings.Repeat("a", 64), Metadata: map[string]interface{}{"key": "value"}, @@ -72,10 +72,10 @@ func TestSave(t *testing.T) { err: repoerr.ErrMalformedEntity, }, { - desc: "add group with invalid owner", + desc: "add group with invalid domain", group: mggroups.Group{ ID: testsutil.GenerateUUID(t), - Owner: invalidID, + Domain: invalidID, Name: namegen.Generate(), Description: strings.Repeat("a", 64), Metadata: map[string]interface{}{"key": "value"}, @@ -101,7 +101,7 @@ func TestSave(t *testing.T) { desc: "add group with invalid name", group: mggroups.Group{ ID: testsutil.GenerateUUID(t), - Owner: testsutil.GenerateUUID(t), + Domain: testsutil.GenerateUUID(t), Name: strings.Repeat("a", 1025), Description: strings.Repeat("a", 64), Metadata: map[string]interface{}{"key": "value"}, @@ -114,7 +114,7 @@ func TestSave(t *testing.T) { desc: "add group with invalid description", group: mggroups.Group{ ID: testsutil.GenerateUUID(t), - Owner: testsutil.GenerateUUID(t), + Domain: testsutil.GenerateUUID(t), Name: namegen.Generate(), Description: strings.Repeat("a", 1025), Metadata: map[string]interface{}{"key": "value"}, @@ -127,7 +127,7 @@ func TestSave(t *testing.T) { desc: "add group with invalid metadata", group: mggroups.Group{ ID: testsutil.GenerateUUID(t), - Owner: testsutil.GenerateUUID(t), + Domain: testsutil.GenerateUUID(t), Name: namegen.Generate(), Description: strings.Repeat("a", 64), Metadata: map[string]interface{}{ @@ -139,7 +139,7 @@ func TestSave(t *testing.T) { err: repoerr.ErrMalformedEntity, }, { - desc: "add group with empty owner", + desc: "add group with empty domain", group: mggroups.Group{ ID: testsutil.GenerateUUID(t), Name: namegen.Generate(), @@ -154,7 +154,7 @@ func TestSave(t *testing.T) { desc: "add group with empty name", group: mggroups.Group{ ID: testsutil.GenerateUUID(t), - Owner: testsutil.GenerateUUID(t), + Domain: testsutil.GenerateUUID(t), Description: strings.Repeat("a", 64), Metadata: map[string]interface{}{"key": "value"}, CreatedAt: time.Now().UTC().Truncate(time.Microsecond), @@ -394,7 +394,7 @@ func TestRetrieveAll(t *testing.T) { name := namegen.Generate() group := mggroups.Group{ ID: testsutil.GenerateUUID(t), - Owner: testsutil.GenerateUUID(t), + Domain: testsutil.GenerateUUID(t), Parent: parentID, Name: name, Description: strings.Repeat("a", 64), @@ -573,12 +573,12 @@ func TestRetrieveAll(t *testing.T) { err: nil, }, { - desc: "retrieve groups with owner", + desc: "retrieve groups with domain", page: mggroups.Page{ PageMeta: mggroups.PageMeta{ - Offset: 0, - Limit: 10, - OwnerID: items[0].Owner, + Offset: 0, + Limit: 10, + DomainID: items[0].Domain, }, }, response: mggroups.Page{ @@ -706,7 +706,7 @@ func TestRetrieveByIDs(t *testing.T) { name := namegen.Generate() group := mggroups.Group{ ID: testsutil.GenerateUUID(t), - Owner: testsutil.GenerateUUID(t), + Domain: testsutil.GenerateUUID(t), Parent: parentID, Name: name, Description: strings.Repeat("a", 64), @@ -765,12 +765,12 @@ func TestRetrieveByIDs(t *testing.T) { err: nil, }, { - desc: "retrieve groups with empty ids but with owner", + desc: "retrieve groups with empty ids but with domain", page: mggroups.Page{ PageMeta: mggroups.PageMeta{ - Offset: 0, - Limit: 10, - OwnerID: items[0].Owner, + Offset: 0, + Limit: 10, + DomainID: items[0].Domain, }, }, ids: []string{}, @@ -881,12 +881,12 @@ func TestRetrieveByIDs(t *testing.T) { err: nil, }, { - desc: "retrieve groups with owner", + desc: "retrieve groups with domain", page: mggroups.Page{ PageMeta: mggroups.PageMeta{ - Offset: 0, - Limit: 10, - OwnerID: items[0].Owner, + Offset: 0, + Limit: 10, + DomainID: items[0].Domain, }, }, ids: getIDs(items[0:20]), @@ -1063,7 +1063,7 @@ func TestAssignParentGroup(t *testing.T) { name := namegen.Generate() group := mggroups.Group{ ID: testsutil.GenerateUUID(t), - Owner: testsutil.GenerateUUID(t), + Domain: testsutil.GenerateUUID(t), Parent: parentID, Name: name, Description: strings.Repeat("a", 64), @@ -1141,7 +1141,7 @@ func TestUnassignParentGroup(t *testing.T) { name := namegen.Generate() group := mggroups.Group{ ID: testsutil.GenerateUUID(t), - Owner: testsutil.GenerateUUID(t), + Domain: testsutil.GenerateUUID(t), Parent: parentID, Name: name, Description: strings.Repeat("a", 64), diff --git a/internal/groups/postgres/init.go b/internal/groups/postgres/init.go index 0cff683e5..0b799c46c 100644 --- a/internal/groups/postgres/init.go +++ b/internal/groups/postgres/init.go @@ -17,7 +17,7 @@ func Migration() *migrate.MemoryMigrationSource { `CREATE TABLE IF NOT EXISTS groups ( id VARCHAR(36) PRIMARY KEY, parent_id VARCHAR(36), - owner_id VARCHAR(36) NOT NULL, + domain_id VARCHAR(36) NOT NULL, name VARCHAR(1024) NOT NULL, description VARCHAR(1024), metadata JSONB, @@ -25,7 +25,7 @@ func Migration() *migrate.MemoryMigrationSource { updated_at TIMESTAMP, updated_by VARCHAR(254), status SMALLINT NOT NULL DEFAULT 0 CHECK (status >= 0), - UNIQUE (owner_id, name), + UNIQUE (domain_id, name), FOREIGN KEY (parent_id) REFERENCES groups (id) ON DELETE SET NULL )`, }, diff --git a/internal/groups/service.go b/internal/groups/service.go index 44297b73b..8dd6d08f0 100644 --- a/internal/groups/service.go +++ b/internal/groups/service.go @@ -60,7 +60,7 @@ func (svc service) CreateGroup(ctx context.Context, token, kind string, g groups g.ID = groupID g.CreatedAt = time.Now() - g.Owner = res.GetDomainId() + g.Domain = res.GetDomainId() if g.Parent != "" { _, err := svc.authorizeToken(ctx, auth.UserType, token, auth.EditPermission, auth.GroupType, g.Parent) if err != nil { @@ -210,7 +210,7 @@ func (svc service) ListGroups(ctx context.Context, token, memberKind, memberID s default: switch svc.checkSuperAdmin(ctx, res.GetUserId()) { case nil: - gm.PageMeta.OwnerID = res.GetDomainId() + gm.PageMeta.DomainID = res.GetDomainId() default: // If domain is disabled , then this authorization will fail for all non-admin domain users if _, err := svc.authorizeKind(ctx, "", auth.UserType, auth.UsersKind, res.GetId(), auth.MembershipPermission, auth.DomainType, res.GetDomainId()); err != nil { diff --git a/internal/groups/service_test.go b/internal/groups/service_test.go index c6a3ecf70..d28b92ef1 100644 --- a/internal/groups/service_test.go +++ b/internal/groups/service_test.go @@ -85,7 +85,7 @@ func TestCreateGroup(t *testing.T) { repoResp: mggroups.Group{ ID: testsutil.GenerateUUID(t), CreatedAt: time.Now(), - Owner: testsutil.GenerateUUID(t), + Domain: testsutil.GenerateUUID(t), }, addPolResp: &magistrala.AddPoliciesRes{ Added: true, @@ -179,7 +179,7 @@ func TestCreateGroup(t *testing.T) { repoResp: mggroups.Group{ ID: testsutil.GenerateUUID(t), CreatedAt: time.Now(), - Owner: testsutil.GenerateUUID(t), + Domain: testsutil.GenerateUUID(t), Parent: testsutil.GenerateUUID(t), }, addPolResp: &magistrala.AddPoliciesRes{ @@ -283,7 +283,7 @@ func TestCreateGroup(t *testing.T) { if err == nil { assert.NotEmpty(t, got.ID) assert.NotEmpty(t, got.CreatedAt) - assert.NotEmpty(t, got.Owner) + assert.NotEmpty(t, got.Domain) assert.WithinDuration(t, time.Now(), got.CreatedAt, 2*time.Second) ok := repocall3.Parent.AssertCalled(t, "Save", context.Background(), mock.Anything) assert.True(t, ok, fmt.Sprintf("Save was not called on %s", tc.desc)) diff --git a/pkg/clients/clients.go b/pkg/clients/clients.go index 2fed8e67e..8d16fe913 100644 --- a/pkg/clients/clients.go +++ b/pkg/clients/clients.go @@ -42,7 +42,7 @@ type Client struct { ID string `json:"id"` Name string `json:"name,omitempty"` Tags []string `json:"tags,omitempty"` - Owner string `json:"owner,omitempty"` // nullable + Domain string `json:"domain,omitempty"` Credentials Credentials `json:"credentials,omitempty"` Metadata Metadata `json:"metadata,omitempty"` CreatedAt time.Time `json:"created_at,omitempty"` @@ -96,9 +96,6 @@ type Repository interface { // UpdateSecret updates secret for client with given identity. UpdateSecret(ctx context.Context, client Client) (Client, error) - // UpdateOwner updates owner for client with given id. - UpdateOwner(ctx context.Context, client Client) (Client, error) - // UpdateRole updates role for client with given id. UpdateRole(ctx context.Context, client Client) (Client, error) diff --git a/pkg/clients/page.go b/pkg/clients/page.go index d0321f0a8..378049fa3 100644 --- a/pkg/clients/page.go +++ b/pkg/clients/page.go @@ -12,7 +12,7 @@ type Page struct { Order string `json:"order,omitempty"` Dir string `json:"dir,omitempty"` Metadata Metadata `json:"metadata,omitempty"` - Owner string `json:"owner,omitempty"` + Domain string `json:"domain,omitempty"` Tag string `json:"tag,omitempty"` Permission string `json:"permission,omitempty"` Status Status `json:"status,omitempty"` diff --git a/pkg/clients/postgres/clients.go b/pkg/clients/postgres/clients.go index 59144c0e1..6ca5255d1 100644 --- a/pkg/clients/postgres/clients.go +++ b/pkg/clients/postgres/clients.go @@ -39,7 +39,7 @@ func (repo *Repository) Update(ctx context.Context, client clients.Client) (clie q := fmt.Sprintf(`UPDATE clients SET %s updated_at = :updated_at, updated_by = :updated_by WHERE id = :id AND status = :status - RETURNING id, name, tags, identity, secret, metadata, COALESCE(owner_id, '') AS owner_id, status, created_at, updated_at, updated_by`, + RETURNING id, name, tags, identity, secret, metadata, COALESCE(domain_id, '') AS domain_id, status, created_at, updated_at, updated_by`, upq) client.Status = clients.EnabledStatus return repo.update(ctx, client, q) @@ -48,7 +48,7 @@ func (repo *Repository) Update(ctx context.Context, client clients.Client) (clie func (repo *Repository) UpdateTags(ctx context.Context, client clients.Client) (clients.Client, error) { q := `UPDATE clients SET tags = :tags, updated_at = :updated_at, updated_by = :updated_by WHERE id = :id AND status = :status - RETURNING id, name, tags, identity, metadata, COALESCE(owner_id, '') AS owner_id, status, created_at, updated_at, updated_by` + RETURNING id, name, tags, identity, metadata, COALESCE(domain_id, '') AS domain_id, status, created_at, updated_at, updated_by` client.Status = clients.EnabledStatus return repo.update(ctx, client, q) } @@ -56,7 +56,7 @@ func (repo *Repository) UpdateTags(ctx context.Context, client clients.Client) ( func (repo *Repository) UpdateIdentity(ctx context.Context, client clients.Client) (clients.Client, error) { q := `UPDATE clients SET identity = :identity, updated_at = :updated_at, updated_by = :updated_by WHERE id = :id AND status = :status - RETURNING id, name, tags, identity, metadata, COALESCE(owner_id, '') AS owner_id, status, created_at, updated_at, updated_by` + RETURNING id, name, tags, identity, metadata, COALESCE(domain_id, '') AS domain_id, status, created_at, updated_at, updated_by` client.Status = clients.EnabledStatus return repo.update(ctx, client, q) } @@ -64,15 +64,7 @@ func (repo *Repository) UpdateIdentity(ctx context.Context, client clients.Clien func (repo *Repository) UpdateSecret(ctx context.Context, client clients.Client) (clients.Client, error) { q := `UPDATE clients SET secret = :secret, updated_at = :updated_at, updated_by = :updated_by WHERE id = :id AND status = :status - RETURNING id, name, tags, identity, metadata, COALESCE(owner_id, '') AS owner_id, status, created_at, updated_at, updated_by` - client.Status = clients.EnabledStatus - return repo.update(ctx, client, q) -} - -func (repo *Repository) UpdateOwner(ctx context.Context, client clients.Client) (clients.Client, error) { - q := `UPDATE clients SET owner_id = :owner_id, updated_at = :updated_at, updated_by = :updated_by - WHERE id = :id AND status = :status - RETURNING id, name, tags, identity, metadata, COALESCE(owner_id, '') AS owner_id, status, created_at, updated_at, updated_by` + RETURNING id, name, tags, identity, metadata, COALESCE(domain_id, '') AS domain_id, status, created_at, updated_at, updated_by` client.Status = clients.EnabledStatus return repo.update(ctx, client, q) } @@ -80,7 +72,7 @@ func (repo *Repository) UpdateOwner(ctx context.Context, client clients.Client) func (repo *Repository) UpdateRole(ctx context.Context, client clients.Client) (clients.Client, error) { q := `UPDATE clients SET role = :role, updated_at = :updated_at, updated_by = :updated_by WHERE id = :id AND status = :status - RETURNING id, name, tags, identity, metadata, COALESCE(owner_id, '') AS owner_id, status, role, created_at, updated_at, updated_by` + RETURNING id, name, tags, identity, metadata, COALESCE(domain_id, '') AS domain_id, status, role, created_at, updated_at, updated_by` client.Status = clients.EnabledStatus return repo.update(ctx, client, q) } @@ -88,13 +80,13 @@ func (repo *Repository) UpdateRole(ctx context.Context, client clients.Client) ( func (repo *Repository) ChangeStatus(ctx context.Context, client clients.Client) (clients.Client, error) { q := `UPDATE clients SET status = :status, updated_at = :updated_at, updated_by = :updated_by WHERE id = :id - RETURNING id, name, tags, identity, metadata, COALESCE(owner_id, '') AS owner_id, status, created_at, updated_at, updated_by` + RETURNING id, name, tags, identity, metadata, COALESCE(domain_id, '') AS domain_id, status, created_at, updated_at, updated_by` return repo.update(ctx, client, q) } func (repo *Repository) RetrieveByID(ctx context.Context, id string) (clients.Client, error) { - q := `SELECT id, name, tags, COALESCE(owner_id, '') AS owner_id, identity, secret, metadata, created_at, updated_at, updated_by, status + q := `SELECT id, name, tags, COALESCE(domain_id, '') AS domain_id, identity, secret, metadata, created_at, updated_at, updated_by, status FROM clients WHERE id = :id` dbc := DBClient{ @@ -120,7 +112,7 @@ func (repo *Repository) RetrieveByID(ctx context.Context, id string) (clients.Cl } func (repo *Repository) RetrieveByIdentity(ctx context.Context, identity string) (clients.Client, error) { - q := `SELECT id, name, tags, COALESCE(owner_id, '') AS owner_id, identity, secret, metadata, created_at, updated_at, updated_by, status + q := `SELECT id, name, tags, COALESCE(domain_id, '') AS domain_id, identity, secret, metadata, created_at, updated_at, updated_by, status FROM clients WHERE identity = :identity AND status = :status` dbc := DBClient{ @@ -152,7 +144,7 @@ func (repo *Repository) RetrieveAll(ctx context.Context, pm clients.Page) (clien return clients.ClientsPage{}, errors.Wrap(repoerr.ErrViewEntity, err) } - q := fmt.Sprintf(`SELECT c.id, c.name, c.tags, c.identity, c.metadata, COALESCE(c.owner_id, '') AS owner_id, c.status, + q := fmt.Sprintf(`SELECT c.id, c.name, c.tags, c.identity, c.metadata, COALESCE(c.domain_id, '') AS domain_id, c.status, c.created_at, c.updated_at, COALESCE(c.updated_by, '') AS updated_by FROM clients c %s ORDER BY c.created_at LIMIT :limit OFFSET :offset;`, query) dbPage, err := ToDBClientsPage(pm) @@ -248,7 +240,7 @@ func (repo *Repository) RetrieveAllBasicInfo(ctx context.Context, pm clients.Pag } func (repo *Repository) RetrieveAllByIDs(ctx context.Context, pm clients.Page) (clients.ClientsPage, error) { - if (len(pm.IDs) <= 0) && (pm.Owner == "") { + if (len(pm.IDs) == 0) && (pm.Domain == "") { return clients.ClientsPage{ Page: clients.Page{Total: pm.Total, Offset: pm.Offset, Limit: pm.Limit}, }, nil @@ -258,7 +250,7 @@ func (repo *Repository) RetrieveAllByIDs(ctx context.Context, pm clients.Page) ( return clients.ClientsPage{}, errors.Wrap(repoerr.ErrViewEntity, err) } - q := fmt.Sprintf(`SELECT c.id, c.name, c.tags, c.identity, c.metadata, COALESCE(c.owner_id, '') AS owner_id, c.status, + q := fmt.Sprintf(`SELECT c.id, c.name, c.tags, c.identity, c.metadata, COALESCE(c.domain_id, '') AS domain_id, c.status, c.created_at, c.updated_at, COALESCE(c.updated_by, '') AS updated_by FROM clients c %s ORDER BY c.created_at LIMIT :limit OFFSET :offset;`, query) dbPage, err := ToDBClientsPage(pm) @@ -333,7 +325,7 @@ type DBClient struct { Name string `db:"name,omitempty"` Tags pgtype.TextArray `db:"tags,omitempty"` Identity string `db:"identity"` - Owner *string `db:"owner_id,omitempty"` // nullable + Domain string `db:"domain_id"` Secret string `db:"secret"` Metadata []byte `db:"metadata,omitempty"` CreatedAt time.Time `db:"created_at,omitempty"` @@ -357,10 +349,6 @@ func ToDBClient(c clients.Client) (DBClient, error) { if err := tags.Set(c.Tags); err != nil { return DBClient{}, err } - var owner *string - if c.Owner != "" { - owner = &c.Owner - } var updatedBy *string if c.UpdatedBy != "" { updatedBy = &c.UpdatedBy @@ -374,7 +362,7 @@ func ToDBClient(c clients.Client) (DBClient, error) { ID: c.ID, Name: c.Name, Tags: tags, - Owner: owner, + Domain: c.Domain, Identity: c.Credentials.Identity, Secret: c.Credentials.Secret, Metadata: data, @@ -397,10 +385,6 @@ func ToClient(c DBClient) (clients.Client, error) { for _, e := range c.Tags.Elements { tags = append(tags, e.String) } - var owner string - if c.Owner != nil { - owner = *c.Owner - } var updatedBy string if c.UpdatedBy != nil { updatedBy = *c.UpdatedBy @@ -411,10 +395,10 @@ func ToClient(c DBClient) (clients.Client, error) { } cli := clients.Client{ - ID: c.ID, - Name: c.Name, - Tags: tags, - Owner: owner, + ID: c.ID, + Name: c.Name, + Tags: tags, + Domain: c.Domain, Credentials: clients.Credentials{ Identity: c.Identity, Secret: c.Secret, @@ -440,7 +424,7 @@ func ToDBClientsPage(pm clients.Page) (dbClientsPage, error) { Name: pm.Name, Identity: pm.Identity, Metadata: data, - Owner: pm.Owner, + Domain: pm.Domain, Total: pm.Total, Offset: pm.Offset, Limit: pm.Limit, @@ -455,7 +439,7 @@ type dbClientsPage struct { Limit uint64 `db:"limit"` Offset uint64 `db:"offset"` Name string `db:"name"` - Owner string `db:"owner_id"` + Domain string `db:"domain_id"` Identity string `db:"identity"` Metadata []byte `db:"metadata"` Tag string `db:"tag"` @@ -489,8 +473,8 @@ func PageQuery(pm clients.Page) (string, error) { if pm.Status != clients.AllStatus { query = append(query, "c.status = :status") } - if pm.Owner != "" { - query = append(query, "c.owner_id = :owner_id") + if pm.Domain != "" { + query = append(query, "c.domain_id = :domain_id") } if pm.Role != clients.AllRole { diff --git a/pkg/clients/postgres/clients_test.go b/pkg/clients/postgres/clients_test.go index 4ec8ab86b..178e628ac 100644 --- a/pkg/clients/postgres/clients_test.go +++ b/pkg/clients/postgres/clients_test.go @@ -143,9 +143,9 @@ func TestRetrieveAll(t *testing.T) { disabledClients := []mgclients.Client{} for i := uint64(0); i < nClients; i++ { client := mgclients.Client{ - ID: testsutil.GenerateUUID(t), - Owner: testsutil.GenerateUUID(t), - Name: namegen.Generate(), + ID: testsutil.GenerateUUID(t), + Domain: testsutil.GenerateUUID(t), + Name: namegen.Generate(), Credentials: mgclients.Credentials{ Identity: namegen.Generate() + emailSuffix, Secret: password, @@ -420,11 +420,11 @@ func TestRetrieveAll(t *testing.T) { }, }, { - desc: "with owner", + desc: "with domain", pm: mgclients.Page{ Offset: 0, Limit: nClients, - Owner: expectedClients[0].Owner, + Domain: expectedClients[0].Domain, Status: mgclients.AllStatus, Role: mgclients.AllRole, }, @@ -438,11 +438,11 @@ func TestRetrieveAll(t *testing.T) { }, }, { - desc: "with wrong owner", + desc: "with wrong domain", pm: mgclients.Page{ Offset: 0, Limit: nClients, - Owner: testsutil.GenerateUUID(t), + Domain: testsutil.GenerateUUID(t), Status: mgclients.AllStatus, Role: mgclients.AllRole, }, @@ -635,7 +635,7 @@ func TestRetrieveAll(t *testing.T) { Name: expectedClients[0].Name, Tag: expectedClients[0].Tags[0], Identity: expectedClients[0].Credentials.Identity, - Owner: expectedClients[0].Owner, + Domain: expectedClients[0].Domain, Status: mgclients.AllStatus, Role: mgclients.AllRole, }, @@ -676,9 +676,9 @@ func TestRetrieveByIDs(t *testing.T) { for i := 0; i < num; i++ { name := namegen.Generate() client := mgclients.Client{ - ID: testsutil.GenerateUUID(t), - Owner: testsutil.GenerateUUID(t), - Name: name, + ID: testsutil.GenerateUUID(t), + Domain: testsutil.GenerateUUID(t), + Name: name, Credentials: mgclients.Credentials{ Identity: name + emailSuffix, Secret: password, @@ -737,11 +737,11 @@ func TestRetrieveByIDs(t *testing.T) { err: nil, }, { - desc: "with empty ids but with owner", + desc: "with empty ids but with domain id", page: mgclients.Page{ Offset: 0, Limit: 10, - Owner: items[0].Owner, + Domain: items[0].Domain, IDs: []string{}, }, response: mgclients.ClientsPage{ @@ -856,11 +856,11 @@ func TestRetrieveByIDs(t *testing.T) { err: nil, }, { - desc: "with owner", + desc: "with domain id", page: mgclients.Page{ Offset: 0, Limit: 10, - Owner: items[0].Owner, + Domain: items[0].Domain, IDs: getIDs(items[0:20]), }, response: mgclients.ClientsPage{ @@ -1676,66 +1676,6 @@ func TestUpdateIdentity(t *testing.T) { } } -func TestUpdateOwner(t *testing.T) { - t.Cleanup(func() { - _, err := db.Exec("DELETE FROM clients") - require.Nil(t, err, fmt.Sprintf("clean clients unexpected error: %s", err)) - }) - repo := &postgres.Repository{database} - - client1 := generateClient(t, mgclients.EnabledStatus, mgclients.UserRole, repo) - client2 := generateClient(t, mgclients.DisabledStatus, mgclients.UserRole, repo) - - cases := []struct { - desc string - client mgclients.Client - err error - }{ - { - desc: "for enabled client", - client: mgclients.Client{ - ID: client1.ID, - Owner: testsutil.GenerateUUID(t), - }, - err: nil, - }, - { - desc: "for disabled client", - client: mgclients.Client{ - ID: client2.ID, - Owner: testsutil.GenerateUUID(t), - }, - err: errors.ErrNotFound, - }, - { - desc: "for invalid client", - client: mgclients.Client{ - ID: testsutil.GenerateUUID(t), - Owner: testsutil.GenerateUUID(t), - }, - err: errors.ErrNotFound, - }, - { - desc: "for empty client", - client: mgclients.Client{}, - err: errors.ErrNotFound, - }, - } - for _, c := range cases { - t.Run(c.desc, func(t *testing.T) { - c.client.UpdatedAt = time.Now().UTC().Truncate(time.Millisecond) - c.client.UpdatedBy = testsutil.GenerateUUID(t) - expected, err := repo.UpdateOwner(context.Background(), c.client) - assert.True(t, errors.Contains(err, c.err), fmt.Sprintf("expected %s to contain %s\n", err, c.err)) - if err == nil { - assert.Equal(t, c.client.Owner, expected.Owner) - assert.Equal(t, c.client.UpdatedAt, expected.UpdatedAt) - assert.Equal(t, c.client.UpdatedBy, expected.UpdatedBy) - } - }) - } -} - func TestChangeStatus(t *testing.T) { t.Cleanup(func() { _, err := db.Exec("DELETE FROM clients") @@ -1900,9 +1840,9 @@ func generateClient(t *testing.T, status mgclients.Status, role mgclients.Role, } func save(ctx context.Context, repo *postgres.Repository, c mgclients.Client) (mgclients.Client, error) { - q := `INSERT INTO clients (id, name, tags, owner_id, identity, secret, metadata, created_at, status, role) - VALUES (:id, :name, :tags, :owner_id, :identity, :secret, :metadata, :created_at, :status, :role) - RETURNING id, name, tags, identity, metadata, COALESCE(owner_id, '') AS owner_id, status, created_at` + q := `INSERT INTO clients (id, name, tags, domain_id, identity, secret, metadata, created_at, status, role) + VALUES (:id, :name, :tags, :domain_id, :identity, :secret, :metadata, :created_at, :status, :role) + RETURNING id, name, tags, identity, metadata, COALESCE(domain_id, '') AS domain_id, status, created_at` dbc, err := pgclients.ToDBClient(c) if err != nil { return mgclients.Client{}, errors.Wrap(repoerr.ErrCreateEntity, err) diff --git a/pkg/groups/groups.go b/pkg/groups/groups.go index aa24ad5d6..ef3f503d1 100644 --- a/pkg/groups/groups.go +++ b/pkg/groups/groups.go @@ -16,10 +16,10 @@ const MaxLevel = uint64(5) // Group represents the group of Clients. // Indicates a level in tree hierarchy. Root node is level 1. // Path in a tree consisting of group IDs -// Paths are unique per owner. +// Paths are unique per domain. type Group struct { ID string `json:"id"` - Owner string `json:"owner_id,omitempty"` + Domain string `json:"domain_id,omitempty"` Parent string `json:"parent_id,omitempty"` Name string `json:"name"` Description string `json:"description,omitempty"` diff --git a/pkg/groups/page.go b/pkg/groups/page.go index e0155aa5d..2f8fc8fdd 100644 --- a/pkg/groups/page.go +++ b/pkg/groups/page.go @@ -11,7 +11,7 @@ type PageMeta struct { Offset uint64 `json:"offset"` Limit uint64 `json:"limit"` Name string `json:"name,omitempty"` - OwnerID string `json:"identity,omitempty"` + DomainID string `json:"domain_id,omitempty"` Tag string `json:"tag,omitempty"` Metadata clients.Metadata `json:"metadata,omitempty"` Status clients.Status `json:"status,omitempty"` diff --git a/pkg/sdk/go/channels.go b/pkg/sdk/go/channels.go index dbdd121b9..c41802361 100644 --- a/pkg/sdk/go/channels.go +++ b/pkg/sdk/go/channels.go @@ -17,7 +17,7 @@ const channelsEndpoint = "channels" // Channel represents magistrala channel. type Channel struct { ID string `json:"id,omitempty"` - OwnerID string `json:"owner_id,omitempty"` + DomainID string `json:"domain_id,omitempty"` ParentID string `json:"parent_id,omitempty"` Name string `json:"name,omitempty"` Description string `json:"description,omitempty"` diff --git a/pkg/sdk/go/channels_test.go b/pkg/sdk/go/channels_test.go index b4232344f..a64749028 100644 --- a/pkg/sdk/go/channels_test.go +++ b/pkg/sdk/go/channels_test.go @@ -111,16 +111,6 @@ func TestCreateChannel(t *testing.T) { token: token, err: errors.NewSDKErrorWithStatus(errors.ErrCreateEntity, http.StatusInternalServerError), }, - { - desc: "create channel with invalid owner", - channel: sdk.Channel{ - Name: gName, - OwnerID: wrongID, - Status: mgclients.EnabledStatus.String(), - }, - token: token, - err: errors.NewSDKErrorWithStatus(sdk.ErrFailedCreation, http.StatusInternalServerError), - }, { desc: "create channel with missing name", channel: sdk.Channel{ @@ -133,7 +123,6 @@ func TestCreateChannel(t *testing.T) { desc: "create a channel with every field defined", channel: sdk.Channel{ ID: generateUUID(t), - OwnerID: "owner", ParentID: "parent", Name: "name", Description: description, @@ -194,7 +183,6 @@ func TestListChannels(t *testing.T) { limit uint64 level int name string - ownerID string metadata sdk.Metadata err errors.SDKError response []sdk.Channel @@ -661,7 +649,6 @@ func TestEnableChannel(t *testing.T) { channel := sdk.Channel{ ID: generateUUID(t), Name: gName, - OwnerID: generateUUID(t), CreatedAt: creationTime, UpdatedAt: creationTime, Status: mgclients.Disabled, @@ -681,7 +668,6 @@ func TestEnableChannel(t *testing.T) { ch := mggroups.Group{ ID: channel.ID, Name: channel.Name, - Owner: channel.OwnerID, CreatedAt: creationTime, UpdatedAt: creationTime, Status: mgclients.DisabledStatus, @@ -714,7 +700,7 @@ func TestDisableChannel(t *testing.T) { channel := sdk.Channel{ ID: generateUUID(t), Name: gName, - OwnerID: generateUUID(t), + DomainID: generateUUID(t), CreatedAt: creationTime, UpdatedAt: creationTime, Status: mgclients.Enabled, @@ -734,7 +720,7 @@ func TestDisableChannel(t *testing.T) { ch := mggroups.Group{ ID: channel.ID, Name: channel.Name, - Owner: channel.OwnerID, + Domain: channel.DomainID, CreatedAt: creationTime, UpdatedAt: creationTime, Status: mgclients.EnabledStatus, @@ -768,7 +754,6 @@ func TestDeleteChannel(t *testing.T) { channel := sdk.Channel{ ID: generateUUID(t), Name: gName, - OwnerID: generateUUID(t), CreatedAt: creationTime, UpdatedAt: creationTime, Status: mgclients.Enabled, diff --git a/pkg/sdk/go/groups.go b/pkg/sdk/go/groups.go index f808e5bf6..cbc6f794b 100644 --- a/pkg/sdk/go/groups.go +++ b/pkg/sdk/go/groups.go @@ -24,7 +24,7 @@ const ( // Paths are unique per owner. type Group struct { ID string `json:"id,omitempty"` - OwnerID string `json:"owner_id,omitempty"` + DomainID string `json:"domain_id,omitempty"` ParentID string `json:"parent_id,omitempty"` Name string `json:"name,omitempty"` Description string `json:"description,omitempty"` diff --git a/pkg/sdk/go/groups_test.go b/pkg/sdk/go/groups_test.go index 9e251cba1..ca6f49a25 100644 --- a/pkg/sdk/go/groups_test.go +++ b/pkg/sdk/go/groups_test.go @@ -96,16 +96,6 @@ func TestCreateGroup(t *testing.T) { }, err: errors.NewSDKErrorWithStatus(svcerr.ErrCreateEntity, http.StatusInternalServerError), }, - { - desc: "create group with invalid owner", - token: token, - group: sdk.Group{ - Name: gName, - OwnerID: wrongID, - Status: clients.EnabledStatus.String(), - }, - err: errors.NewSDKErrorWithStatus(sdk.ErrFailedCreation, http.StatusInternalServerError), - }, { desc: "create group with missing name", token: token, @@ -119,7 +109,6 @@ func TestCreateGroup(t *testing.T) { token: token, group: sdk.Group{ ID: generateUUID(t), - OwnerID: "owner", ParentID: "parent", Name: "name", Description: description, @@ -192,7 +181,6 @@ func TestListGroups(t *testing.T) { limit uint64 level int name string - ownerID string metadata sdk.Metadata err errors.SDKError response []sdk.Group @@ -323,7 +311,6 @@ func TestListParentGroups(t *testing.T) { limit uint64 level int name string - ownerID string metadata sdk.Metadata err errors.SDKError response []sdk.Group @@ -455,7 +442,6 @@ func TestListChildrenGroups(t *testing.T) { limit uint64 level int name string - ownerID string metadata sdk.Metadata err errors.SDKError response []sdk.Group @@ -796,7 +782,7 @@ func TestEnableGroup(t *testing.T) { group := sdk.Group{ ID: generateUUID(t), Name: gName, - OwnerID: generateUUID(t), + DomainID: generateUUID(t), CreatedAt: creationTime, UpdatedAt: creationTime, Status: clients.Disabled, @@ -816,7 +802,7 @@ func TestEnableGroup(t *testing.T) { g := mggroups.Group{ ID: group.ID, Name: group.Name, - Owner: group.OwnerID, + Domain: group.DomainID, CreatedAt: creationTime, UpdatedAt: creationTime, Status: clients.DisabledStatus, @@ -849,7 +835,7 @@ func TestDisableGroup(t *testing.T) { group := sdk.Group{ ID: generateUUID(t), Name: gName, - OwnerID: generateUUID(t), + DomainID: generateUUID(t), CreatedAt: creationTime, UpdatedAt: creationTime, Status: clients.Enabled, @@ -869,7 +855,7 @@ func TestDisableGroup(t *testing.T) { g := mggroups.Group{ ID: group.ID, Name: group.Name, - Owner: group.OwnerID, + Domain: group.DomainID, CreatedAt: creationTime, UpdatedAt: creationTime, Status: clients.EnabledStatus, @@ -903,7 +889,6 @@ func TestDeleteGroup(t *testing.T) { group := sdk.Group{ ID: generateUUID(t), Name: gName, - OwnerID: generateUUID(t), CreatedAt: creationTime, UpdatedAt: creationTime, Status: clients.Enabled, diff --git a/pkg/sdk/go/setup_test.go b/pkg/sdk/go/setup_test.go index 4c5631a11..0f15596c2 100644 --- a/pkg/sdk/go/setup_test.go +++ b/pkg/sdk/go/setup_test.go @@ -148,7 +148,7 @@ func convertGroup(g sdk.Group) mggroups.Group { return mggroups.Group{ ID: g.ID, - Owner: g.OwnerID, + Domain: g.DomainID, Parent: g.ParentID, Name: g.Name, Description: g.Description, @@ -190,7 +190,7 @@ func convertClient(c sdk.User) mgclients.Client { ID: c.ID, Name: c.Name, Tags: c.Tags, - Owner: c.Owner, + Domain: c.Domain, Credentials: mgclients.Credentials(c.Credentials), Metadata: mgclients.Metadata(c.Metadata), CreatedAt: c.CreatedAt, @@ -211,7 +211,7 @@ func convertThing(c sdk.Thing) mgclients.Client { ID: c.ID, Name: c.Name, Tags: c.Tags, - Owner: c.Owner, + Domain: c.DomainID, Credentials: mgclients.Credentials(c.Credentials), Metadata: mgclients.Metadata(c.Metadata), CreatedAt: c.CreatedAt, @@ -230,7 +230,7 @@ func convertChannel(g sdk.Channel) mggroups.Group { } return mggroups.Group{ ID: g.ID, - Owner: g.OwnerID, + Domain: g.DomainID, Parent: g.ParentID, Name: g.Name, Description: g.Description, diff --git a/pkg/sdk/go/things.go b/pkg/sdk/go/things.go index 0593d7b33..16f629416 100644 --- a/pkg/sdk/go/things.go +++ b/pkg/sdk/go/things.go @@ -28,7 +28,7 @@ type Thing struct { Name string `json:"name,omitempty"` Credentials Credentials `json:"credentials"` Tags []string `json:"tags,omitempty"` - Owner string `json:"owner,omitempty"` + DomainID string `json:"domain_id,omitempty"` Metadata map[string]interface{} `json:"metadata,omitempty"` CreatedAt time.Time `json:"created_at,omitempty"` UpdatedAt time.Time `json:"updated_at,omitempty"` diff --git a/pkg/sdk/go/things_test.go b/pkg/sdk/go/things_test.go index 17fa2f897..98defd07e 100644 --- a/pkg/sdk/go/things_test.go +++ b/pkg/sdk/go/things_test.go @@ -162,7 +162,6 @@ func TestCreateThing(t *testing.T) { ID: id, Name: "name", Tags: []string{"tag1", "tag2"}, - Owner: id, Credentials: user.Credentials, Metadata: validMetadata, CreatedAt: time.Now(), @@ -173,7 +172,6 @@ func TestCreateThing(t *testing.T) { ID: id, Name: "name", Tags: []string{"tag1", "tag2"}, - Owner: id, Credentials: user.Credentials, Metadata: validMetadata, CreatedAt: time.Now(), @@ -193,7 +191,6 @@ func TestCreateThing(t *testing.T) { rThing, err := mgsdk.CreateThing(tc.client, tc.token) tc.response.ID = rThing.ID - tc.response.Owner = rThing.Owner tc.response.CreatedAt = rThing.CreatedAt tc.response.UpdatedAt = rThing.UpdatedAt rThing.Credentials.Secret = tc.response.Credentials.Secret @@ -284,7 +281,6 @@ func TestCreateThings(t *testing.T) { rThing, err := mgsdk.CreateThings(tc.things, tc.token) for i, t := range rThing { tc.response[i].ID = t.ID - tc.response[i].Owner = t.Owner tc.response[i].CreatedAt = t.CreatedAt tc.response[i].UpdatedAt = t.UpdatedAt tc.response[i].Credentials.Secret = t.Credentials.Secret @@ -319,7 +315,6 @@ func TestListThings(t *testing.T) { } mgsdk := sdk.NewSDK(conf) - owner := generateUUID(t) for i := 10; i < 100; i++ { th := sdk.Thing{ ID: generateUUID(t), @@ -332,7 +327,6 @@ func TestListThings(t *testing.T) { Status: mgclients.EnabledStatus.String(), } if i == 50 { - th.Owner = owner th.Status = mgclients.DisabledStatus.String() th.Tags = []string{"tag1", "tag2"} } @@ -348,7 +342,6 @@ func TestListThings(t *testing.T) { limit uint64 name string identifier string - ownerID string tag string metadata sdk.Metadata err errors.SDKError @@ -437,15 +430,6 @@ func TestListThings(t *testing.T) { response: []sdk.Thing{ths[0]}, err: nil, }, - { - desc: "list things with given owner", - token: validToken, - offset: 0, - limit: 1, - ownerID: owner, - response: []sdk.Thing{ths[50]}, - err: nil, - }, { desc: "list things with given status", token: validToken, @@ -473,7 +457,6 @@ func TestListThings(t *testing.T) { Offset: tc.offset, Limit: tc.limit, Name: tc.name, - OwnerID: tc.ownerID, Metadata: tc.metadata, Tag: tc.tag, } @@ -560,19 +543,6 @@ func TestListThingsByChannel(t *testing.T) { response: aThings[6:], err: nil, }, - - { - desc: "list things with given ownerID", - token: validToken, - channelID: testsutil.GenerateUUID(t), - page: sdk.PageMetadata{ - OwnerID: user.Owner, - Offset: 6, - Limit: nThing, - }, - response: aThings[6:], - err: nil, - }, { desc: "list things with given subject", token: validToken, diff --git a/pkg/sdk/go/users.go b/pkg/sdk/go/users.go index b7a4c583d..24ceb35c2 100644 --- a/pkg/sdk/go/users.go +++ b/pkg/sdk/go/users.go @@ -30,7 +30,7 @@ type User struct { Name string `json:"name,omitempty"` Credentials Credentials `json:"credentials"` Tags []string `json:"tags,omitempty"` - Owner string `json:"owner,omitempty"` + Domain string `json:"-"` // ignoring Domain Field, since it will be always empty for users Metadata Metadata `json:"metadata,omitempty"` CreatedAt time.Time `json:"created_at,omitempty"` UpdatedAt time.Time `json:"updated_at,omitempty"` diff --git a/pkg/sdk/go/users_test.go b/pkg/sdk/go/users_test.go index 97a2e5a17..39d6aeacf 100644 --- a/pkg/sdk/go/users_test.go +++ b/pkg/sdk/go/users_test.go @@ -159,7 +159,6 @@ func TestCreateClient(t *testing.T) { ID: id, Name: "name", Tags: []string{"tag1", "tag2"}, - Owner: id, Credentials: user.Credentials, Metadata: validMetadata, CreatedAt: time.Now(), @@ -170,7 +169,6 @@ func TestCreateClient(t *testing.T) { ID: id, Name: "name", Tags: []string{"tag1", "tag2"}, - Owner: id, Credentials: user.Credentials, Metadata: validMetadata, CreatedAt: time.Now(), @@ -191,7 +189,6 @@ func TestCreateClient(t *testing.T) { repoCall3 := crepo.On("Save", mock.Anything, mock.Anything).Return(convertClient(tc.response), tc.err) rClient, err := mgsdk.CreateUser(tc.client, tc.token) tc.response.ID = rClient.ID - tc.response.Owner = rClient.Owner tc.response.CreatedAt = rClient.CreatedAt tc.response.UpdatedAt = rClient.UpdatedAt rClient.Credentials.Secret = tc.response.Credentials.Secret @@ -230,7 +227,6 @@ func TestListClients(t *testing.T) { Status: mgclients.EnabledStatus.String(), } if i == 50 { - cl.Owner = "clientowner" cl.Status = mgclients.DisabledStatus.String() cl.Tags = []string{"tag1", "tag2"} } @@ -246,7 +242,6 @@ func TestListClients(t *testing.T) { limit uint64 name string identifier string - ownerID string tag string metadata sdk.Metadata err errors.SDKError @@ -335,15 +330,7 @@ func TestListClients(t *testing.T) { response: []sdk.User{cls[0]}, err: nil, }, - { - desc: "list users with given owner", - token: validToken, - offset: 0, - limit: 1, - ownerID: "clientowner", - response: []sdk.User{cls[50]}, - err: nil, - }, + { desc: "list users with given status", token: validToken, @@ -371,7 +358,6 @@ func TestListClients(t *testing.T) { Offset: tc.offset, Limit: tc.limit, Name: tc.name, - OwnerID: tc.ownerID, Metadata: tc.metadata, Tag: tc.tag, } @@ -888,7 +874,6 @@ func TestUpdateClientRole(t *testing.T) { Credentials: sdk.Credentials{Identity: "clientidentity", Secret: secret}, Metadata: validMetadata, Status: mgclients.EnabledStatus.String(), - Owner: "owner", } client2 := user @@ -920,7 +905,7 @@ func TestUpdateClientRole(t *testing.T) { client: client2, response: sdk.User{}, token: validToken, - err: errors.NewSDKErrorWithStatus(errors.Wrap(users.ErrFailedOwnerUpdate, users.ErrFailedOwnerUpdate), http.StatusInternalServerError), + err: errors.NewSDKErrorWithStatus(errors.Wrap(users.ErrFailedUpdateRole, users.ErrFailedUpdateRole), http.StatusInternalServerError), }, { desc: "update a user that can't be marshalled", diff --git a/things/api/http/clients.go b/things/api/http/clients.go index 4f3d8a1a3..33c5ec903 100644 --- a/things/api/http/clients.go +++ b/things/api/http/clients.go @@ -157,7 +157,6 @@ func decodeViewClientPerms(_ context.Context, r *http.Request) (interface{}, err } func decodeListClients(_ context.Context, r *http.Request) (interface{}, error) { - var ownerID string s, err := apiutil.ReadStringQuery(r, api.StatusKey, api.DefClientStatus) if err != nil { return nil, errors.Wrap(apiutil.ErrValidation, err) @@ -182,11 +181,6 @@ func decodeListClients(_ context.Context, r *http.Request) (interface{}, error) if err != nil { return nil, errors.Wrap(apiutil.ErrValidation, err) } - oid, err := apiutil.ReadStringQuery(r, api.OwnerKey, "") - if err != nil { - return nil, err - } - p, err := apiutil.ReadStringQuery(r, api.PermissionKey, api.DefPermission) if err != nil { return nil, errors.Wrap(apiutil.ErrValidation, err) @@ -196,10 +190,6 @@ func decodeListClients(_ context.Context, r *http.Request) (interface{}, error) if err != nil { return nil, errors.Wrap(apiutil.ErrValidation, err) } - - if oid != "" { - ownerID = oid - } st, err := mgclients.ToStatus(s) if err != nil { return nil, errors.Wrap(apiutil.ErrValidation, err) @@ -215,7 +205,6 @@ func decodeListClients(_ context.Context, r *http.Request) (interface{}, error) permission: p, listPerms: lp, userID: chi.URLParam(r, "userID"), - owner: ownerID, } return req, nil } diff --git a/things/api/http/endpoints.go b/things/api/http/endpoints.go index a84e01204..244cf71d9 100644 --- a/things/api/http/endpoints.go +++ b/things/api/http/endpoints.go @@ -103,7 +103,6 @@ func listClientsEndpoint(svc things.Service) endpoint.Endpoint { Status: req.status, Offset: req.offset, Limit: req.limit, - Owner: req.owner, Name: req.name, Tag: req.tag, Permission: req.permission, diff --git a/things/api/http/endpoints_test.go b/things/api/http/endpoints_test.go index fc44c3e5a..cbe12647c 100644 --- a/things/api/http/endpoints_test.go +++ b/things/api/http/endpoints_test.go @@ -456,33 +456,6 @@ func TestListThings(t *testing.T) { status: http.StatusBadRequest, err: apiutil.ErrValidation, }, - { - desc: "list things with owner_id", - token: validToken, - listThingsResponse: mgclients.ClientsPage{ - Page: mgclients.Page{ - Total: 1, - }, - Clients: []mgclients.Client{client}, - }, - query: fmt.Sprintf("owner_id=%s", validID), - status: http.StatusOK, - err: nil, - }, - { - desc: "list things with duplicate owner_id", - token: validToken, - query: "owner_id=1&owner_id=2", - status: http.StatusBadRequest, - err: apiutil.ErrInvalidQueryParams, - }, - { - desc: "list things with invalid owner_id", - token: validToken, - query: "owner_id=invalid", - status: http.StatusBadRequest, - err: apiutil.ErrValidation, - }, { desc: "list things with name", token: validToken, diff --git a/things/api/http/requests.go b/things/api/http/requests.go index c1f0a1049..687127757 100644 --- a/things/api/http/requests.go +++ b/things/api/http/requests.go @@ -92,7 +92,6 @@ type listClientsReq struct { limit uint64 name string tag string - owner string permission string visibility string userID string diff --git a/things/events/events.go b/things/events/events.go index a709838c4..3d2cd953d 100644 --- a/things/events/events.go +++ b/things/events/events.go @@ -60,8 +60,8 @@ func (cce createClientEvent) Encode() (map[string]interface{}, error) { tags := fmt.Sprintf("[%s]", strings.Join(cce.Tags, ",")) val["tags"] = tags } - if cce.Owner != "" { - val["owner"] = cce.Owner + if cce.Domain != "" { + val["domain"] = cce.Domain } if cce.Metadata != nil { metadata, err := json.Marshal(cce.Metadata) @@ -103,8 +103,8 @@ func (uce updateClientEvent) Encode() (map[string]interface{}, error) { tags := fmt.Sprintf("[%s]", strings.Join(uce.Tags, ",")) val["tags"] = tags } - if uce.Owner != "" { - val["owner"] = uce.Owner + if uce.Domain != "" { + val["domain"] = uce.Domain } if uce.Credentials.Identity != "" { val["identity"] = uce.Credentials.Identity @@ -161,8 +161,8 @@ func (vce viewClientEvent) Encode() (map[string]interface{}, error) { tags := fmt.Sprintf("[%s]", strings.Join(vce.Tags, ",")) val["tags"] = tags } - if vce.Owner != "" { - val["owner"] = vce.Owner + if vce.Domain != "" { + val["domain"] = vce.Domain } if vce.Credentials.Identity != "" { val["identity"] = vce.Credentials.Identity @@ -234,8 +234,8 @@ func (lce listClientEvent) Encode() (map[string]interface{}, error) { val["metadata"] = metadata } - if lce.Owner != "" { - val["owner"] = lce.Owner + if lce.Domain != "" { + val["domain"] = lce.Domain } if lce.Tag != "" { val["tag"] = lce.Tag @@ -288,8 +288,8 @@ func (lcge listClientByGroupEvent) Encode() (map[string]interface{}, error) { val["metadata"] = metadata } - if lcge.Owner != "" { - val["owner"] = lcge.Owner + if lcge.Domain != "" { + val["domain"] = lcge.Domain } if lcge.Tag != "" { val["tag"] = lcge.Tag diff --git a/things/mocks/repository.go b/things/mocks/repository.go index 14429f163..d347b4209 100644 --- a/things/mocks/repository.go +++ b/things/mocks/repository.go @@ -324,34 +324,6 @@ func (_m *Repository) UpdateIdentity(ctx context.Context, client clients.Client) return r0, r1 } -// UpdateOwner provides a mock function with given fields: ctx, client -func (_m *Repository) UpdateOwner(ctx context.Context, client clients.Client) (clients.Client, error) { - ret := _m.Called(ctx, client) - - if len(ret) == 0 { - panic("no return value specified for UpdateOwner") - } - - var r0 clients.Client - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, clients.Client) (clients.Client, error)); ok { - return rf(ctx, client) - } - if rf, ok := ret.Get(0).(func(context.Context, clients.Client) clients.Client); ok { - r0 = rf(ctx, client) - } else { - r0 = ret.Get(0).(clients.Client) - } - - if rf, ok := ret.Get(1).(func(context.Context, clients.Client) error); ok { - r1 = rf(ctx, client) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - // UpdateRole provides a mock function with given fields: ctx, client func (_m *Repository) UpdateRole(ctx context.Context, client clients.Client) (clients.Client, error) { ret := _m.Called(ctx, client) diff --git a/things/postgres/clients.go b/things/postgres/clients.go index a9ca6b94a..69e9f066f 100644 --- a/things/postgres/clients.go +++ b/things/postgres/clients.go @@ -54,9 +54,9 @@ func (repo clientRepo) Save(ctx context.Context, cs ...mgclients.Client) ([]mgcl var clients []mgclients.Client for _, cli := range cs { - q := `INSERT INTO clients (id, name, tags, owner_id, identity, secret, metadata, created_at, updated_at, updated_by, status) - VALUES (:id, :name, :tags, :owner_id, :identity, :secret, :metadata, :created_at, :updated_at, :updated_by, :status) - RETURNING id, name, tags, identity, secret, metadata, COALESCE(owner_id, '') AS owner_id, status, created_at, updated_at, updated_by` + q := `INSERT INTO clients (id, name, tags, domain_id, identity, secret, metadata, created_at, updated_at, updated_by, status) + VALUES (:id, :name, :tags, :domain_id, :identity, :secret, :metadata, :created_at, :updated_at, :updated_by, :status) + RETURNING id, name, tags, identity, secret, metadata, COALESCE(domain_id, '') AS domain_id, status, created_at, updated_at, updated_by` dbcli, err := pgclients.ToDBClient(cli) if err != nil { @@ -94,7 +94,7 @@ func (repo clientRepo) Save(ctx context.Context, cs ...mgclients.Client) ([]mgcl } func (repo clientRepo) RetrieveBySecret(ctx context.Context, key string) (mgclients.Client, error) { - q := fmt.Sprintf(`SELECT id, name, tags, COALESCE(owner_id, '') AS owner_id, identity, secret, metadata, created_at, updated_at, updated_by, status + q := fmt.Sprintf(`SELECT id, name, tags, COALESCE(domain_id, '') AS domain_id, identity, secret, metadata, created_at, updated_at, updated_by, status FROM clients WHERE secret = :secret AND status = %d`, mgclients.EnabledStatus) diff --git a/things/postgres/clients_test.go b/things/postgres/clients_test.go index 2e6b83421..fa191d32a 100644 --- a/things/postgres/clients_test.go +++ b/things/postgres/clients_test.go @@ -26,6 +26,7 @@ var ( clientIdentity = "client-identity@example.com" clientName = "client name" invalidClientID = "invalidClientID" + invalidDomainID = strings.Repeat("m", maxNameSize+10) namesgen = namegenerator.NewNameGenerator() ) @@ -37,6 +38,8 @@ func TestClientsSave(t *testing.T) { repo := postgres.NewRepository(database) uid := testsutil.GenerateUUID(t) + domainID := testsutil.GenerateUUID(t) + secret := testsutil.GenerateUUID(t) cases := []struct { desc string @@ -46,11 +49,12 @@ func TestClientsSave(t *testing.T) { { desc: "add new client successfully", client: clients.Client{ - ID: uid, - Name: clientName, + ID: uid, + Domain: domainID, + Name: clientName, Credentials: clients.Credentials{ Identity: clientIdentity, - Secret: testsutil.GenerateUUID(t), + Secret: secret, }, Metadata: clients.Metadata{}, Status: clients.EnabledStatus, @@ -58,13 +62,42 @@ func TestClientsSave(t *testing.T) { err: nil, }, { - desc: "add new client with an owner", + desc: "add new client with duplicate secret", + client: clients.Client{ + ID: uid, + Domain: domainID, + Name: clientName, + Credentials: clients.Credentials{ + Identity: clientIdentity, + Secret: secret, + }, + Metadata: clients.Metadata{}, + Status: clients.EnabledStatus, + }, + err: errors.ErrCreateEntity, + }, + { + desc: "add new client with duplicate secret", client: clients.Client{ - ID: testsutil.GenerateUUID(t), - Owner: uid, - Name: clientName, + ID: uid, + Domain: domainID, + Name: clientName, Credentials: clients.Credentials{ - Identity: "withowner-client@example.com", + Identity: clientIdentity, + Secret: testsutil.GenerateUUID(t), + }, + Metadata: clients.Metadata{}, + Status: clients.EnabledStatus, + }, + err: errors.ErrCreateEntity, + }, + { + desc: "add new client without domain id", + client: clients.Client{ + ID: testsutil.GenerateUUID(t), + Name: clientName, + Credentials: clients.Credentials{ + Identity: "withoutdomain-client@example.com", Secret: testsutil.GenerateUUID(t), }, Metadata: clients.Metadata{}, @@ -75,8 +108,9 @@ func TestClientsSave(t *testing.T) { { desc: "add client with invalid client id", client: clients.Client{ - ID: invalidName, - Name: clientName, + ID: invalidName, + Domain: domainID, + Name: clientName, Credentials: clients.Credentials{ Identity: "invalidid-client@example.com", Secret: testsutil.GenerateUUID(t), @@ -89,8 +123,9 @@ func TestClientsSave(t *testing.T) { { desc: "add client with invalid client name", client: clients.Client{ - ID: testsutil.GenerateUUID(t), - Name: invalidName, + ID: testsutil.GenerateUUID(t), + Name: invalidName, + Domain: domainID, Credentials: clients.Credentials{ Identity: "invalidname-client@example.com", Secret: testsutil.GenerateUUID(t), @@ -101,12 +136,12 @@ func TestClientsSave(t *testing.T) { err: errors.ErrCreateEntity, }, { - desc: "add client with invalid client owner", + desc: "add client with invalid client domain id", client: clients.Client{ - ID: testsutil.GenerateUUID(t), - Owner: invalidName, + ID: testsutil.GenerateUUID(t), + Domain: invalidDomainID, Credentials: clients.Credentials{ - Identity: "invalidowner-client@example.com", + Identity: "invaliddomainid-client@example.com", Secret: testsutil.GenerateUUID(t), }, Metadata: clients.Metadata{}, @@ -131,7 +166,9 @@ func TestClientsSave(t *testing.T) { { desc: "add client with a missing client identity", client: clients.Client{ - ID: testsutil.GenerateUUID(t), + ID: testsutil.GenerateUUID(t), + Domain: testsutil.GenerateUUID(t), + Name: "missing-client-identity", Credentials: clients.Credentials{ Identity: "", Secret: testsutil.GenerateUUID(t), @@ -143,7 +180,8 @@ func TestClientsSave(t *testing.T) { { desc: "add client with a missing client secret", client: clients.Client{ - ID: testsutil.GenerateUUID(t), + ID: testsutil.GenerateUUID(t), + Domain: testsutil.GenerateUUID(t), Credentials: clients.Credentials{ Identity: "missing-client-secret@example.com", Secret: "", diff --git a/things/postgres/init.go b/things/postgres/init.go index d59627e9c..28e07a2cc 100644 --- a/things/postgres/init.go +++ b/things/postgres/init.go @@ -19,7 +19,7 @@ func Migration() *migrate.MemoryMigrationSource { `CREATE TABLE IF NOT EXISTS clients ( id VARCHAR(36) PRIMARY KEY, name VARCHAR(1024), - owner_id VARCHAR(36), + domain_id VARCHAR(36) NOT NULL, identity VARCHAR(254), secret VARCHAR(4096) NOT NULL, tags TEXT[], @@ -28,8 +28,8 @@ func Migration() *migrate.MemoryMigrationSource { updated_at TIMESTAMP, updated_by VARCHAR(254), status SMALLINT NOT NULL DEFAULT 0 CHECK (status >= 0), - UNIQUE (owner_id, secret), - UNIQUE (owner_id, name) + UNIQUE (domain_id, secret), + UNIQUE (domain_id, name) )`, }, Down: []string{ diff --git a/things/service.go b/things/service.go index 3799c3b8c..8130609c6 100644 --- a/things/service.go +++ b/things/service.go @@ -94,7 +94,7 @@ func (svc service) CreateThings(ctx context.Context, token string, cls ...mgclie if c.Status != mgclients.DisabledStatus && c.Status != mgclients.EnabledStatus { return []mgclients.Client{}, svcerr.ErrInvalidStatus } - c.Owner = user.GetDomainId() + c.Domain = user.GetDomainId() c.CreatedAt = time.Now() clients = append(clients, c) } @@ -185,7 +185,7 @@ func (svc service) ListClients(ctx context.Context, token, reqUserID string, pm err := svc.checkSuperAdmin(ctx, res.GetUserId()) switch { case err == nil: - pm.Owner = res.GetDomainId() + pm.Domain = res.GetDomainId() default: // If domain is disabled , then this authorization will fail for all non-admin domain users if _, err := svc.authorize(ctx, "", auth.UserType, auth.UsersKind, res.GetId(), auth.MembershipPermission, auth.DomainType, res.GetDomainId()); err != nil { diff --git a/things/service_test.go b/things/service_test.go index 798a19723..644bd6c0b 100644 --- a/things/service_test.go +++ b/things/service_test.go @@ -37,7 +37,6 @@ var ( Metadata: validCMetadata, Status: mgclients.EnabledStatus, } - adminEmail = "admin@example.com" validToken = "token" inValidToken = invalid valid = "valid" @@ -88,6 +87,34 @@ func TestCreateThings(t *testing.T) { saveErr: errors.ErrConflict, err: svcerr.ErrConflict, }, + { + desc: "create a new thing without secret", + thing: mgclients.Client{ + Name: "clientWithoutSecret", + Credentials: mgclients.Credentials{ + Identity: "newclientwithoutsecret@example.com", + }, + Status: mgclients.EnabledStatus, + }, + token: validToken, + authResponse: &magistrala.AuthorizeRes{Authorized: true}, + addPolicyResponse: &magistrala.AddPoliciesRes{Added: true}, + err: nil, + }, + { + desc: "create a new thing without identity", + thing: mgclients.Client{ + Name: "clientWithoutIdentity", + Credentials: mgclients.Credentials{ + Identity: "newclientwithoutsecret@example.com", + }, + Status: mgclients.EnabledStatus, + }, + token: validToken, + authResponse: &magistrala.AuthorizeRes{Authorized: true}, + addPolicyResponse: &magistrala.AddPoliciesRes{Added: true}, + err: nil, + }, { desc: "create a new enabled thing with name", thing: mgclients.Client{ @@ -103,6 +130,7 @@ func TestCreateThings(t *testing.T) { addPolicyResponse: &magistrala.AddPoliciesRes{Added: true}, err: nil, }, + { desc: "create a new disabled thing with name", thing: mgclients.Client{ @@ -222,35 +250,6 @@ func TestCreateThings(t *testing.T) { addPolicyResponse: &magistrala.AddPoliciesRes{Added: true}, err: nil, }, - { - desc: "create a new thing with invalid owner", - thing: mgclients.Client{ - Owner: wrongID, - Credentials: mgclients.Credentials{ - Identity: "newclientwithinvalidowner@example.com", - Secret: secret, - }, - }, - token: validToken, - authResponse: &magistrala.AuthorizeRes{Authorized: true}, - addPolicyResponse: &magistrala.AddPoliciesRes{Added: true}, - saveErr: repoerr.ErrMalformedEntity, - err: repoerr.ErrCreateEntity, - }, - { - desc: "create a new thing with empty secret", - thing: mgclients.Client{ - Owner: testsutil.GenerateUUID(t), - Credentials: mgclients.Credentials{ - Identity: "newclientwithemptysecret@example.com", - }, - }, - token: validToken, - authResponse: &magistrala.AuthorizeRes{Authorized: true}, - addPolicyResponse: &magistrala.AddPoliciesRes{Added: true}, - saveErr: repoerr.ErrMissingSecret, - err: repoerr.ErrCreateEntity, - }, { desc: "create a new thing with invalid status", thing: mgclients.Client{ @@ -321,7 +320,7 @@ func TestCreateThings(t *testing.T) { tc.thing.CreatedAt = expected[0].CreatedAt tc.thing.UpdatedAt = expected[0].UpdatedAt tc.thing.Credentials.Secret = expected[0].Credentials.Secret - tc.thing.Owner = expected[0].Owner + tc.thing.Domain = expected[0].Domain tc.thing.UpdatedBy = expected[0].UpdatedBy assert.Equal(t, tc.thing, expected[0], fmt.Sprintf("%s: expected %v got %v\n", tc.desc, tc.thing, expected[0])) } @@ -1361,12 +1360,13 @@ func TestListMembers(t *testing.T) { nClients := uint64(10) aClients := []mgclients.Client{} - owner := testsutil.GenerateUUID(t) + domainID := testsutil.GenerateUUID(t) for i := uint64(0); i < nClients; i++ { identity := fmt.Sprintf("member_%d@example.com", i) client := mgclients.Client{ - ID: testsutil.GenerateUUID(t), - Name: identity, + ID: testsutil.GenerateUUID(t), + Domain: domainID, + Name: identity, Credentials: mgclients.Credentials{ Identity: identity, Secret: "password", @@ -1374,9 +1374,6 @@ func TestListMembers(t *testing.T) { Tags: []string{"tag1", "tag2"}, Metadata: mgclients.Metadata{"role": "client"}, } - if i%3 == 0 { - client.Owner = owner - } aClients = append(aClients, client) } aClients[0].Permissions = []string{"admin"} @@ -1400,12 +1397,9 @@ func TestListMembers(t *testing.T) { err error }{ { - desc: "list members with authorized token", - token: validToken, - groupID: testsutil.GenerateUUID(t), - page: mgclients.Page{ - Owner: adminEmail, - }, + desc: "list members with authorized token", + token: validToken, + groupID: testsutil.GenerateUUID(t), identifyResponse: &magistrala.IdentityRes{Id: validID, DomainId: testsutil.GenerateUUID(t)}, authorizeResponse: &magistrala.AuthorizeRes{Authorized: true}, listObjectsResponse: &magistrala.ListObjectsRes{}, @@ -1436,7 +1430,6 @@ func TestListMembers(t *testing.T) { Offset: 6, Limit: nClients, Status: mgclients.AllStatus, - Owner: adminEmail, }, identifyResponse: &magistrala.IdentityRes{Id: validID, DomainId: testsutil.GenerateUUID(t)}, authorizeResponse: &magistrala.AuthorizeRes{Authorized: true}, @@ -1457,12 +1450,9 @@ func TestListMembers(t *testing.T) { err: nil, }, { - desc: "list members with an invalid token", - token: authmocks.InvalidValue, - groupID: testsutil.GenerateUUID(t), - page: mgclients.Page{ - Owner: adminEmail, - }, + desc: "list members with an invalid token", + token: authmocks.InvalidValue, + groupID: testsutil.GenerateUUID(t), identifyResponse: &magistrala.IdentityRes{}, response: mgclients.MembersPage{ Page: mgclients.Page{ @@ -1475,12 +1465,9 @@ func TestListMembers(t *testing.T) { err: svcerr.ErrAuthentication, }, { - desc: "list members with an invalid id", - token: validToken, - groupID: wrongID, - page: mgclients.Page{ - Owner: adminEmail, - }, + desc: "list members with an invalid id", + token: validToken, + groupID: wrongID, identifyResponse: &magistrala.IdentityRes{Id: validID, DomainId: testsutil.GenerateUUID(t)}, authorizeResponse: &magistrala.AuthorizeRes{Authorized: true}, listObjectsResponse: &magistrala.ListObjectsRes{}, @@ -1497,36 +1484,10 @@ func TestListMembers(t *testing.T) { err: svcerr.ErrNotFound, }, { - desc: "list members for an owner", - token: validToken, - groupID: testsutil.GenerateUUID(t), - page: mgclients.Page{ - Owner: adminEmail, - }, - identifyResponse: &magistrala.IdentityRes{Id: validID, DomainId: testsutil.GenerateUUID(t)}, - authorizeResponse: &magistrala.AuthorizeRes{Authorized: true}, - listObjectsResponse: &magistrala.ListObjectsRes{}, - listPermissionsResponse: &magistrala.ListPermissionsRes{}, - retreiveAllByIDsResponse: mgclients.ClientsPage{ - Page: mgclients.Page{ - Total: 4, - }, - Clients: []mgclients.Client{aClients[0], aClients[3], aClients[6], aClients[9]}, - }, - response: mgclients.MembersPage{ - Page: mgclients.Page{ - Total: 4, - }, - Members: []mgclients.Client{aClients[0], aClients[3], aClients[6], aClients[9]}, - }, - err: nil, - }, - { - desc: "list members for an owner with permissions", + desc: "list members with permissions", token: validToken, groupID: testsutil.GenerateUUID(t), page: mgclients.Page{ - Owner: adminEmail, ListPerms: true, }, identifyResponse: &magistrala.IdentityRes{Id: validID, DomainId: testsutil.GenerateUUID(t)}, @@ -1552,7 +1513,6 @@ func TestListMembers(t *testing.T) { token: validToken, groupID: testsutil.GenerateUUID(t), page: mgclients.Page{ - Owner: adminEmail, ListPerms: true, }, identifyResponse: &magistrala.IdentityRes{Id: validID, DomainId: testsutil.GenerateUUID(t)}, @@ -1565,7 +1525,6 @@ func TestListMembers(t *testing.T) { token: validToken, groupID: testsutil.GenerateUUID(t), page: mgclients.Page{ - Owner: adminEmail, ListPerms: true, }, identifyResponse: &magistrala.IdentityRes{Id: validID, DomainId: testsutil.GenerateUUID(t)}, @@ -1579,7 +1538,6 @@ func TestListMembers(t *testing.T) { token: validToken, groupID: testsutil.GenerateUUID(t), page: mgclients.Page{ - Owner: adminEmail, ListPerms: true, }, retreiveAllByIDsResponse: mgclients.ClientsPage{ diff --git a/users/api/clients.go b/users/api/clients.go index 0f9075c3e..84283d4e7 100644 --- a/users/api/clients.go +++ b/users/api/clients.go @@ -217,10 +217,7 @@ func decodeListClients(_ context.Context, r *http.Request) (interface{}, error) if err != nil { return nil, errors.Wrap(apiutil.ErrValidation, err) } - oid, err := apiutil.ReadStringQuery(r, api.OwnerKey, "") - if err != nil { - return nil, err - } + order, err := apiutil.ReadStringQuery(r, api.OrderKey, api.DefOrder) if err != nil { return nil, errors.Wrap(apiutil.ErrValidation, err) @@ -229,6 +226,7 @@ func decodeListClients(_ context.Context, r *http.Request) (interface{}, error) if err != nil { return nil, errors.Wrap(apiutil.ErrValidation, err) } + st, err := mgclients.ToStatus(s) if err != nil { return nil, errors.Wrap(apiutil.ErrValidation, err) @@ -242,7 +240,6 @@ func decodeListClients(_ context.Context, r *http.Request) (interface{}, error) name: n, identity: i, tag: t, - owner: oid, order: order, dir: dir, } @@ -494,10 +491,6 @@ func queryPageParams(r *http.Request, defPermission string) (mgclients.Page, err if err != nil { return mgclients.Page{}, errors.Wrap(apiutil.ErrValidation, err) } - oid, err := apiutil.ReadStringQuery(r, api.OwnerKey, "") - if err != nil { - return mgclients.Page{}, errors.Wrap(apiutil.ErrValidation, err) - } st, err := mgclients.ToStatus(s) if err != nil { return mgclients.Page{}, errors.Wrap(apiutil.ErrValidation, err) @@ -518,7 +511,6 @@ func queryPageParams(r *http.Request, defPermission string) (mgclients.Page, err Identity: i, Name: n, Tag: t, - Owner: oid, Permission: p, ListPerms: lp, }, nil diff --git a/users/api/endpoint_test.go b/users/api/endpoint_test.go index 742bddff7..0691810aa 100644 --- a/users/api/endpoint_test.go +++ b/users/api/endpoint_test.go @@ -439,33 +439,6 @@ func TestListClients(t *testing.T) { status: http.StatusBadRequest, err: apiutil.ErrValidation, }, - { - desc: "list users with owner_id", - token: validToken, - listUsersResponse: mgclients.ClientsPage{ - Page: mgclients.Page{ - Total: 1, - }, - Clients: []mgclients.Client{client}, - }, - query: fmt.Sprintf("owner_id=%s", validID), - status: http.StatusOK, - err: nil, - }, - { - desc: "list users with duplicate owner_id", - token: validToken, - query: "owner_id=1&owner_id=2", - status: http.StatusBadRequest, - err: apiutil.ErrInvalidQueryParams, - }, - { - desc: "list users with invalid owner_id", - token: validToken, - query: "owner_id=invalid", - status: http.StatusBadRequest, - err: apiutil.ErrValidation, - }, { desc: "list users with name", token: validToken, @@ -1898,36 +1871,6 @@ func TestListUsersByUserGroupId(t *testing.T) { status: http.StatusBadRequest, err: apiutil.ErrValidation, }, - { - desc: "list users with owner_id", - token: validToken, - groupID: validID, - listUsersResponse: mgclients.ClientsPage{ - Page: mgclients.Page{ - Total: 1, - }, - Clients: []mgclients.Client{client}, - }, - query: fmt.Sprintf("owner_id=%s", validID), - status: http.StatusOK, - err: nil, - }, - { - desc: "list users with duplicate owner_id", - token: validToken, - groupID: validID, - query: "owner_id=1&owner_id=2", - status: http.StatusBadRequest, - err: apiutil.ErrInvalidQueryParams, - }, - { - desc: "list users with invalid owner_id", - token: validToken, - groupID: validID, - query: "owner_id=invalid", - status: http.StatusBadRequest, - err: apiutil.ErrValidation, - }, { desc: "list users with name", token: validToken, @@ -2220,33 +2163,6 @@ func TestListUsersByChannelID(t *testing.T) { status: http.StatusBadRequest, err: apiutil.ErrValidation, }, - { - desc: "list users with owner_id", - token: validToken, - listUsersResponse: mgclients.ClientsPage{ - Page: mgclients.Page{ - Total: 1, - }, - Clients: []mgclients.Client{client}, - }, - query: fmt.Sprintf("owner_id=%s", validID), - status: http.StatusOK, - err: nil, - }, - { - desc: "list users with duplicate owner_id", - token: validToken, - query: "owner_id=1&owner_id=2", - status: http.StatusBadRequest, - err: apiutil.ErrInvalidQueryParams, - }, - { - desc: "list users with invalid owner_id", - token: validToken, - query: "owner_id=invalid", - status: http.StatusBadRequest, - err: apiutil.ErrValidation, - }, { desc: "list users with name", token: validToken, @@ -2542,33 +2458,6 @@ func TestListUsersByDomainID(t *testing.T) { status: http.StatusBadRequest, err: apiutil.ErrValidation, }, - { - desc: "list users with owner_id", - token: validToken, - listUsersResponse: mgclients.ClientsPage{ - Page: mgclients.Page{ - Total: 1, - }, - Clients: []mgclients.Client{client}, - }, - query: fmt.Sprintf("owner_id=%s", validID), - status: http.StatusOK, - err: nil, - }, - { - desc: "list users with duplicate owner_id", - token: validToken, - query: "owner_id=1&owner_id=2", - status: http.StatusBadRequest, - err: apiutil.ErrInvalidQueryParams, - }, - { - desc: "list users with invalid owner_id", - token: validToken, - query: "owner_id=invalid", - status: http.StatusBadRequest, - err: apiutil.ErrValidation, - }, { desc: "list users with name", token: validToken, @@ -2872,33 +2761,6 @@ func TestListUsersByThingID(t *testing.T) { status: http.StatusBadRequest, err: apiutil.ErrValidation, }, - { - desc: "list users with owner_id", - token: validToken, - listUsersResponse: mgclients.ClientsPage{ - Page: mgclients.Page{ - Total: 1, - }, - Clients: []mgclients.Client{client}, - }, - query: fmt.Sprintf("owner_id=%s", validID), - status: http.StatusOK, - err: nil, - }, - { - desc: "list users with duplicate owner_id", - token: validToken, - query: "owner_id=1&owner_id=2", - status: http.StatusBadRequest, - err: apiutil.ErrInvalidQueryParams, - }, - { - desc: "list users with invalid owner_id", - token: validToken, - query: "owner_id=invalid", - status: http.StatusBadRequest, - err: apiutil.ErrValidation, - }, { desc: "list users with name", token: validToken, diff --git a/users/api/endpoints.go b/users/api/endpoints.go index 50f7d91c8..b8bb81101 100644 --- a/users/api/endpoints.go +++ b/users/api/endpoints.go @@ -75,7 +75,6 @@ func listClientsEndpoint(svc users.Service) endpoint.Endpoint { Status: req.status, Offset: req.offset, Limit: req.limit, - Owner: req.owner, Name: req.name, Tag: req.tag, Metadata: req.metadata, diff --git a/users/api/requests.go b/users/api/requests.go index 9c52064f3..394cca124 100644 --- a/users/api/requests.go +++ b/users/api/requests.go @@ -60,7 +60,6 @@ type listClientsReq struct { name string tag string identity string - owner string metadata mgclients.Metadata order string dir string diff --git a/users/events/events.go b/users/events/events.go index b02d18ddf..95bba4790 100644 --- a/users/events/events.go +++ b/users/events/events.go @@ -65,8 +65,8 @@ func (cce createClientEvent) Encode() (map[string]interface{}, error) { tags := fmt.Sprintf("[%s]", strings.Join(cce.Tags, ",")) val["tags"] = tags } - if cce.Owner != "" { - val["owner"] = cce.Owner + if cce.Domain != "" { + val["domain"] = cce.Domain } if cce.Metadata != nil { metadata, err := json.Marshal(cce.Metadata) @@ -163,8 +163,8 @@ func (vce viewClientEvent) Encode() (map[string]interface{}, error) { tags := fmt.Sprintf("[%s]", strings.Join(vce.Tags, ",")) val["tags"] = tags } - if vce.Owner != "" { - val["owner"] = vce.Owner + if vce.Domain != "" { + val["domain"] = vce.Domain } if vce.Credentials.Identity != "" { val["identity"] = vce.Credentials.Identity @@ -210,8 +210,8 @@ func (vpe viewProfileEvent) Encode() (map[string]interface{}, error) { tags := fmt.Sprintf("[%s]", strings.Join(vpe.Tags, ",")) val["tags"] = tags } - if vpe.Owner != "" { - val["owner"] = vpe.Owner + if vpe.Domain != "" { + val["domain"] = vpe.Domain } if vpe.Credentials.Identity != "" { val["identity"] = vpe.Credentials.Identity @@ -269,8 +269,8 @@ func (lce listClientEvent) Encode() (map[string]interface{}, error) { val["metadata"] = metadata } - if lce.Owner != "" { - val["owner"] = lce.Owner + if lce.Domain != "" { + val["domain"] = lce.Domain } if lce.Tag != "" { val["tag"] = lce.Tag @@ -321,8 +321,8 @@ func (lcge listClientByGroupEvent) Encode() (map[string]interface{}, error) { val["metadata"] = metadata } - if lcge.Owner != "" { - val["owner"] = lcge.Owner + if lcge.Domain != "" { + val["domain"] = lcge.Domain } if lcge.Tag != "" { val["tag"] = lcge.Tag diff --git a/users/events/streams.go b/users/events/streams.go index 4e0da1f36..c810413c2 100644 --- a/users/events/streams.go +++ b/users/events/streams.go @@ -68,7 +68,7 @@ func (es *eventStore) UpdateClientRole(ctx context.Context, token string, user m return user, err } - return es.update(ctx, "owner", user) + return es.update(ctx, "role", user) } func (es *eventStore) UpdateClientTags(ctx context.Context, token string, user mgclients.Client) (mgclients.Client, error) { diff --git a/users/mocks/repository.go b/users/mocks/repository.go index 6a71d302f..2bc4c6509 100644 --- a/users/mocks/repository.go +++ b/users/mocks/repository.go @@ -287,34 +287,6 @@ func (_m *Repository) UpdateIdentity(ctx context.Context, client clients.Client) return r0, r1 } -// UpdateOwner provides a mock function with given fields: ctx, client -func (_m *Repository) UpdateOwner(ctx context.Context, client clients.Client) (clients.Client, error) { - ret := _m.Called(ctx, client) - - if len(ret) == 0 { - panic("no return value specified for UpdateOwner") - } - - var r0 clients.Client - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, clients.Client) (clients.Client, error)); ok { - return rf(ctx, client) - } - if rf, ok := ret.Get(0).(func(context.Context, clients.Client) clients.Client); ok { - r0 = rf(ctx, client) - } else { - r0 = ret.Get(0).(clients.Client) - } - - if rf, ok := ret.Get(1).(func(context.Context, clients.Client) error); ok { - r1 = rf(ctx, client) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - // UpdateRole provides a mock function with given fields: ctx, client func (_m *Repository) UpdateRole(ctx context.Context, client clients.Client) (clients.Client, error) { ret := _m.Called(ctx, client) diff --git a/users/postgres/clients.go b/users/postgres/clients.go index dd1abfae9..5a65de691 100644 --- a/users/postgres/clients.go +++ b/users/postgres/clients.go @@ -46,9 +46,9 @@ func NewRepository(db postgres.Database) Repository { } func (repo clientRepo) Save(ctx context.Context, c mgclients.Client) (mgclients.Client, error) { - q := `INSERT INTO clients (id, name, tags, owner_id, identity, secret, metadata, created_at, status, role) - VALUES (:id, :name, :tags, :owner_id, :identity, :secret, :metadata, :created_at, :status, :role) - RETURNING id, name, tags, identity, metadata, COALESCE(owner_id, '') AS owner_id, status, created_at` + q := `INSERT INTO clients (id, name, tags, identity, secret, metadata, created_at, status, role) + VALUES (:id, :name, :tags, :identity, :secret, :metadata, :created_at, :status, :role) + RETURNING id, name, tags, identity, metadata, status, created_at` dbc, err := pgclients.ToDBClient(c) if err != nil { return mgclients.Client{}, errors.Wrap(repoerr.ErrCreateEntity, err) @@ -92,7 +92,7 @@ func (repo clientRepo) CheckSuperAdmin(ctx context.Context, adminID string) erro } func (repo clientRepo) RetrieveByID(ctx context.Context, id string) (mgclients.Client, error) { - q := `SELECT id, name, tags, COALESCE(owner_id, '') AS owner_id, identity, secret, metadata, created_at, updated_at, updated_by, status, role + q := `SELECT id, name, tags, identity, secret, metadata, created_at, updated_at, updated_by, status, role FROM clients WHERE id = :id` dbc := pgclients.DBClient{ @@ -128,7 +128,7 @@ func (repo clientRepo) RetrieveAll(ctx context.Context, pm mgclients.Page) (mgcl return mgclients.ClientsPage{}, errors.Wrap(errors.ErrViewEntity, err) } - q := fmt.Sprintf(`SELECT c.id, c.name, c.tags, c.identity, c.metadata, COALESCE(c.owner_id, '') AS owner_id, c.status, c.role, + q := fmt.Sprintf(`SELECT c.id, c.name, c.tags, c.identity, c.metadata, c.status, c.role, c.created_at, c.updated_at, COALESCE(c.updated_by, '') AS updated_by FROM clients c %s ORDER BY c.created_at LIMIT :limit OFFSET :offset;`, query) dbPage, err := pgclients.ToDBClientsPage(pm) @@ -177,7 +177,7 @@ func (repo clientRepo) RetrieveAll(ctx context.Context, pm mgclients.Page) (mgcl func (repo clientRepo) UpdateRole(ctx context.Context, client mgclients.Client) (mgclients.Client, error) { query := `UPDATE clients SET role = :role, updated_at = :updated_at, updated_by = :updated_by WHERE id = :id AND status = :status - RETURNING id, name, tags, identity, metadata, COALESCE(owner_id, '') AS owner_id, status, role, created_at, updated_at, updated_by` + RETURNING id, name, tags, identity, metadata, status, role, created_at, updated_at, updated_by` dbc, err := pgclients.ToDBClient(client) if err != nil { diff --git a/users/postgres/clients_test.go b/users/postgres/clients_test.go index 4a5d7f045..29d723960 100644 --- a/users/postgres/clients_test.go +++ b/users/postgres/clients_test.go @@ -57,21 +57,6 @@ func TestClientsSave(t *testing.T) { }, err: nil, }, - { - desc: "add new client with an owner", - client: mgclients.Client{ - ID: testsutil.GenerateUUID(t), - Owner: uid, - Name: namesgen.Generate(), - Credentials: mgclients.Credentials{ - Identity: fmt.Sprintf("%s@example.com", namesgen.Generate()), - Secret: password, - }, - Metadata: mgclients.Metadata{}, - Status: mgclients.EnabledStatus, - }, - err: nil, - }, { desc: "add client with duplicate client identity", client: mgclients.Client{ @@ -128,20 +113,6 @@ func TestClientsSave(t *testing.T) { }, err: errors.ErrMalformedEntity, }, - { - desc: "add client with invalid client owner", - client: mgclients.Client{ - ID: testsutil.GenerateUUID(t), - Owner: invalidName, - Credentials: mgclients.Credentials{ - Identity: fmt.Sprintf("%s@example.com", namesgen.Generate()), - Secret: password, - }, - Metadata: mgclients.Metadata{}, - Status: mgclients.EnabledStatus, - }, - err: errors.ErrMalformedEntity, - }, { desc: "add client with invalid client identity", client: mgclients.Client{ @@ -328,8 +299,6 @@ func TestRetrieveAll(t *testing.T) { repo := cpostgres.NewRepository(database) - ownerID := testsutil.GenerateUUID(t) - num := 200 var items, enabledClients []mgclients.Client for i := 0; i < num; i++ { @@ -345,7 +314,6 @@ func TestRetrieveAll(t *testing.T) { Tags: []string{"tag1"}, } if i%50 == 0 { - client.Owner = ownerID client.Metadata = map[string]interface{}{ "key": "value", } @@ -577,43 +545,6 @@ func TestRetrieveAll(t *testing.T) { Clients: items, }, }, - { - desc: "retrieve with owner id", - pageMeta: mgclients.Page{ - Owner: ownerID, - Offset: 0, - Limit: 5, - Role: mgclients.AllRole, - Status: mgclients.AllStatus, - }, - page: mgclients.ClientsPage{ - Page: mgclients.Page{ - Total: 4, - Offset: 0, - Limit: 5, - }, - Clients: []mgclients.Client{items[0], items[50], items[100], items[150]}, - }, - err: nil, - }, - { - desc: "retrieve with invalid owner id", - pageMeta: mgclients.Page{ - Owner: invalidName, - Offset: 0, - Limit: 200, - Role: mgclients.AllRole, - }, - page: mgclients.ClientsPage{ - Page: mgclients.Page{ - Total: 0, - Offset: 0, - Limit: 200, - }, - Clients: []mgclients.Client{}, - }, - err: nil, - }, { desc: "retrieve by tags", pageMeta: mgclients.Page{ diff --git a/users/postgres/init.go b/users/postgres/init.go index 3edda715f..9e8a4903f 100644 --- a/users/postgres/init.go +++ b/users/postgres/init.go @@ -21,7 +21,7 @@ func Migration() *migrate.MemoryMigrationSource { `CREATE TABLE IF NOT EXISTS clients ( id VARCHAR(36) PRIMARY KEY, name VARCHAR(254) NOT NULL UNIQUE, - owner_id VARCHAR(36), + domain_id VARCHAR(36), identity VARCHAR(254) NOT NULL UNIQUE, secret TEXT NOT NULL, tags TEXT[], diff --git a/users/service.go b/users/service.go index 3e059a4a6..ae057b03f 100644 --- a/users/service.go +++ b/users/service.go @@ -28,8 +28,8 @@ var ( // ErrFailedPolicyUpdate indicates a failure to update user policy. ErrFailedPolicyUpdate = errors.New("failed to update user policy") - // ErrFailedOwnerUpdate indicates a failure to update user policy. - ErrFailedOwnerUpdate = errors.New("failed to update user owner") + // ErrFailedUpdateRole indicates a failure to update user role. + ErrFailedUpdateRole = errors.New("failed to update user role") // ErrAddPolicies indictaed a failre to add policies. errAddPolicies = errors.New("failed to add policies") @@ -392,7 +392,7 @@ func (svc service) UpdateClientRole(ctx context.Context, token string, cli mgcli if errRollback := svc.updateClientPolicy(ctx, cli.ID, mgclients.UserRole); errRollback != nil { return mgclients.Client{}, errors.Wrap(err, errors.Wrap(repoerr.ErrRollbackTx, errRollback)) } - return mgclients.Client{}, errors.Wrap(ErrFailedOwnerUpdate, err) + return mgclients.Client{}, errors.Wrap(ErrFailedUpdateRole, err) } return client, nil } diff --git a/users/service_test.go b/users/service_test.go index 2dbbc7580..ba54c53d8 100644 --- a/users/service_test.go +++ b/users/service_test.go @@ -286,7 +286,6 @@ func TestRegisterClient(t *testing.T) { tc.client.CreatedAt = expected.CreatedAt tc.client.UpdatedAt = expected.UpdatedAt tc.client.Credentials.Secret = expected.Credentials.Secret - tc.client.Owner = expected.Owner tc.client.UpdatedBy = expected.UpdatedBy assert.Equal(t, tc.client, expected, fmt.Sprintf("%s: expected %v got %v\n", tc.desc, tc.client, expected)) ok := repoCall2.Parent.AssertCalled(t, "Save", context.Background(), mock.Anything) @@ -363,7 +362,6 @@ func TestRegisterClient(t *testing.T) { tc.client.CreatedAt = expected.CreatedAt tc.client.UpdatedAt = expected.UpdatedAt tc.client.Credentials.Secret = expected.Credentials.Secret - tc.client.Owner = expected.Owner tc.client.UpdatedBy = expected.UpdatedBy assert.Equal(t, tc.client, expected, fmt.Sprintf("%s: expected %v got %v\n", tc.desc, tc.client, expected)) ok := repoCall5.Parent.AssertCalled(t, "Save", context.Background(), mock.Anything)