This repository has been archived by the owner on Sep 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
gdirectory.go
111 lines (92 loc) · 2.55 KB
/
gdirectory.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
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
108
109
110
111
package gsuite
import (
"context"
"encoding/json"
"os"
"sync"
"github.com/aws/aws-xray-sdk-go/xray"
log "github.com/sirupsen/logrus"
"golang.org/x/oauth2/google"
admin "google.golang.org/api/admin/directory/v1"
)
type GoogleServiceAccountSecretProvider interface {
GetKey(context.Context) ([]byte, error)
}
type GoogleDirectory struct {
secretProvider GoogleServiceAccountSecretProvider
service *admin.Service
once sync.Once
}
type UserInfo struct {
Id string `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
IsAdmin bool `json:"is_admin"`
IsSuspended bool `json:"is_suspended"`
Schemas map[string]map[string]interface{} `json:"schemas"`
}
func NewGoogleDirectory(secretProvider GoogleServiceAccountSecretProvider) *GoogleDirectory {
return &GoogleDirectory{
secretProvider: secretProvider,
}
}
func (d *GoogleDirectory) init(ctx context.Context) {
d.once.Do(func() {
jsonKey, err := d.secretProvider.GetKey(ctx)
if err != nil {
log.WithError(err).Fatal("Error obtaining Google Service Account key")
}
config, err := google.JWTConfigFromJSON(jsonKey, admin.AdminDirectoryUserReadonlyScope)
if err != nil {
log.WithError(err).Fatal("Error creating config from Service Account key")
}
if iSubject, ok := os.LookupEnv("GSUITE_IMPERSONATE_SUBJECT"); ok {
config.Subject = iSubject
}
oaClient := config.Client(ctx)
oaClient = xray.Client(oaClient)
d.service, err = admin.New(oaClient)
if err != nil {
log.WithError(err).Fatal("Error creating Admin SDK client")
}
})
}
func (d *GoogleDirectory) GetUserInfo(ctx context.Context, userKey string) (*UserInfo, error) {
d.init(ctx)
res, err := d.service.Users.Get(userKey).Projection("full").Context(ctx).Do()
if err != nil {
return nil, err
}
schemas := make(map[string]map[string]interface{})
for s, r := range res.CustomSchemas {
schemas[s] = make(map[string]interface{})
var schema map[string]interface{}
if err := json.Unmarshal(r, &schema); err == nil {
for k, v := range schema {
if v1, ok := v.([]interface{}); ok {
var values []interface{}
for _, v2 := range v1 {
if v3, ok := v2.(map[string]interface{}); ok {
if v4, ok := v3["value"]; ok {
values = append(values, v4)
}
} else {
values = append(values, v3)
}
}
schemas[s][k] = values
} else {
schemas[s][k] = v
}
}
}
}
return &UserInfo{
Id: res.Id,
Email: res.PrimaryEmail,
Name: res.Name.FullName,
IsAdmin: res.IsAdmin,
IsSuspended: res.Suspended,
Schemas: schemas,
}, nil
}