/
removeDevice.go
51 lines (40 loc) · 1.45 KB
/
removeDevice.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
package service
import (
"context"
grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
"github.com/plgd-dev/cloud/authorization/pb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// RemoveDevice remove a device from user. It is used by cloud2cloud connector.
func (s *Service) RemoveDevice(ctx context.Context, request *pb.RemoveDeviceRequest) (*pb.RemoveDeviceResponse, error) {
tx := s.persistence.NewTransaction(ctx)
defer tx.Close()
userID := request.UserId
token, err := grpc_auth.AuthFromMD(ctx, "bearer")
if err != nil {
uid, err := parseSubFromJwtToken(token)
if err == nil {
userID = uid
}
}
if userID == "" {
return nil, logAndReturnError(status.Errorf(codes.InvalidArgument, "cannot remove device: invalid UserId"))
}
if request.DeviceId == "" {
return nil, logAndReturnError(status.Errorf(codes.InvalidArgument, "cannot remove device: invalid DeviceId"))
}
// TODO validate jwt token -> only jwt token is supported
_, ok, err := tx.Retrieve(request.DeviceId, userID)
if err != nil {
return nil, logAndReturnError(status.Errorf(codes.Internal, "cannot remove device: %v", err.Error()))
}
if !ok {
return nil, logAndReturnError(status.Errorf(codes.NotFound, "cannot remove device: not found"))
}
err = tx.Delete(request.DeviceId, userID)
if err != nil {
return nil, logAndReturnError(status.Errorf(codes.NotFound, "cannot remove device: not found"))
}
return &pb.RemoveDeviceResponse{}, nil
}