-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfetch.go
More file actions
107 lines (86 loc) · 2.31 KB
/
fetch.go
File metadata and controls
107 lines (86 loc) · 2.31 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package fetch
import (
"context"
"encoding/json"
"io"
"iter"
"github.com/aserto-dev/ds-load/plugins/cognito/pkg/cognitoclient"
"github.com/aserto-dev/ds-load/sdk/common"
"github.com/aserto-dev/ds-load/sdk/common/js"
"github.com/aserto-dev/ds-load/sdk/fetcher"
)
type Fetcher struct {
cognitoClient *cognitoclient.CognitoClient
groups bool
}
func New(client *cognitoclient.CognitoClient) (*Fetcher, error) {
return &Fetcher{
cognitoClient: client,
}, nil
}
func (f *Fetcher) WithGroups(groups bool) *Fetcher {
f.groups = groups
return f
}
func (f *Fetcher) Fetch(ctx context.Context, outputWriter, errorWriter io.Writer) error {
writer := js.NewJSONArrayWriter(outputWriter)
defer writer.Close()
if f.groups {
for obj, err := range f.fetchGroups() {
if err != nil {
common.WriteErrorWithExitCode(errorWriter, err, 1)
}
if err := writer.Write(obj); err != nil {
_, _ = errorWriter.Write([]byte(err.Error()))
}
}
}
users, err := f.cognitoClient.ListUsers(ctx)
if err != nil {
_, _ = errorWriter.Write([]byte(err.Error()))
}
for _, user := range users {
attributes := make(map[string]string)
for _, attr := range user.Attributes {
attributes[*attr.Name] = *attr.Value
}
userBytes, err := json.Marshal(user)
if err != nil {
common.WriteErrorWithExitCode(errorWriter, err, 1)
return err
}
var obj map[string]any
if err := json.Unmarshal(userBytes, &obj); err != nil {
_, _ = errorWriter.Write([]byte(err.Error()))
}
obj["Attributes"] = attributes
if f.groups {
groups, err := f.cognitoClient.GetGroupsForUser(*user.Username)
if err != nil {
_, _ = errorWriter.Write([]byte(err.Error()))
continue
}
groupBytes, err := json.Marshal(groups.Groups)
if err != nil {
_, _ = errorWriter.Write([]byte(err.Error()))
return err
}
var grps []map[string]string
if err := json.Unmarshal(groupBytes, &grps); err != nil {
_, _ = errorWriter.Write([]byte(err.Error()))
}
obj["Groups"] = grps
}
if err := writer.Write(obj); err != nil {
_, _ = errorWriter.Write([]byte(err.Error()))
}
}
return nil
}
func (f *Fetcher) fetchGroups() iter.Seq2[map[string]any, error] {
groups, err := f.cognitoClient.ListGroups()
if err != nil {
return fetcher.YieldError(err)
}
return fetcher.YieldMap(groups, json.Marshal)
}