-
Notifications
You must be signed in to change notification settings - Fork 0
/
gsuite.go
97 lines (83 loc) · 2.17 KB
/
gsuite.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
package main
import (
"fmt"
"io/ioutil"
"golang.org/x/net/context"
"golang.org/x/oauth2/google"
"encoding/json"
admin "google.golang.org/api/admin/directory/v1"
"google.golang.org/api/option"
"strings"
)
// RsaKey struct to map json RawMessage to
type RsaKey struct {
Key string `json:"Public_SSH_Key"`
}
// CreateDirectoryService builds and returns an Admin SDK Directory service
// object authorized with the service accounts that act on behalf of the
// given user.
func CreateDirectoryService(
userEmail string,
credentialsPath string,
) (*admin.Service, error) {
ctx := context.Background()
jsonCredentials, err := ioutil.ReadFile(credentialsPath)
if err != nil {
return nil, err
}
config, err := google.JWTConfigFromJSON(
jsonCredentials,
admin.AdminDirectoryUserScope,
)
if err != nil {
return nil, fmt.Errorf("JWTConfigFromJSON: %v", err)
}
config.Subject = userEmail
ts := config.TokenSource(ctx)
srv, err := admin.NewService(ctx, option.WithTokenSource(ts))
if err != nil {
return nil, fmt.Errorf("NewService: %v", err)
}
return srv, nil
}
// PullGsuiteUsers Creates a Google Workspace API Directory Service and
// authenticates. It then queries the API for a list of domain users with
// the appropriate custom attribute set. Returns a list of gsuiteUser objects.
func PullGsuiteUsers(
email string,
domain string,
mask string,
credentialsPath string,
) ([]IAMUser, error) {
// gsuiteUsers List of gsuiteUser objects
var gsuiteUsers = []IAMUser{}
srv, e := CreateDirectoryService(email, credentialsPath)
if e != nil {
return nil, e
}
r, err := srv.Users.List().Domain(domain).Projection(
"Custom",
).CustomFieldMask(mask).Do()
if err != nil {
return nil, err
}
if len(r.Users) != 0 {
for _, u := range r.Users {
if val, ok := u.CustomSchemas["SSHKEY"]; ok {
// Custom Schema SSHKEY exists
var rsakey RsaKey
err := json.Unmarshal(val, &rsakey)
if err != nil {
return nil, err
}
uName := u.Name.GivenName + "." + u.Name.FamilyName
gUser := IAMUser{
username: strings.ToLower(uName),
publickey: rsakey.Key,
}
gsuiteUsers = append(gsuiteUsers, gUser)
}
}
}
return gsuiteUsers, nil
}