-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
getDevices.go
64 lines (57 loc) · 1.95 KB
/
getDevices.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package service
import (
"github.com/plgd-dev/hub/v2/identity-store/pb"
"github.com/plgd-dev/hub/v2/identity-store/persistence"
"github.com/plgd-dev/hub/v2/pkg/log"
"github.com/plgd-dev/hub/v2/pkg/net/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// hasMatchDeviceID returns true if device id match filter.
// An empty deviceIdFilter matches all device ids.
func hasMatchDeviceID(deviceID string, deviceIDFilter map[string]bool) bool {
if len(deviceIDFilter) == 0 {
return true
}
if _, ok := deviceIDFilter[deviceID]; ok {
return true
}
return false
}
func sendDevices(request *pb.GetDevicesRequest, srv pb.IdentityStore_GetDevicesServer, createIter func() persistence.Iterator) error {
deviceIdFilter := make(map[string]bool)
for _, deviceID := range request.GetDeviceIdsFilter() {
deviceIdFilter[deviceID] = true
}
ids := make([]string, 0, 16)
var d persistence.AuthorizedDevice
it := createIter()
for it.Next(&d) {
if hasMatchDeviceID(d.DeviceID, deviceIdFilter) {
ids = append(ids, d.DeviceID)
}
}
it.Close()
if it.Err() != nil {
return log.LogAndReturnError(status.Errorf(codes.Internal, "cannot get user devices: %v", it.Err()))
}
for _, deviceID := range ids {
err := srv.Send(&pb.Device{DeviceId: deviceID})
if err != nil {
return log.LogAndReturnError(status.Errorf(status.Convert(err).Code(), "cannot get user devices: %v", err))
}
}
return nil
}
// GetDevices returns a list of user's devices if the access token is valid.
func (s *Service) GetDevices(request *pb.GetDevicesRequest, srv pb.IdentityStore_GetDevicesServer) error {
tx := s.persistence.NewTransaction(srv.Context())
defer tx.Close()
owner, err := grpc.OwnerFromTokenMD(srv.Context(), s.ownerClaim)
if err != nil {
return log.LogAndReturnError(grpc.ForwardErrorf(codes.InvalidArgument, "cannot get owner devices: %v", err))
}
return sendDevices(request, srv, func() persistence.Iterator {
return tx.RetrieveByOwner(owner)
})
}