-
Notifications
You must be signed in to change notification settings - Fork 0
/
goauth_helper.go
232 lines (218 loc) · 7.98 KB
/
goauth_helper.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package googleoauth
import (
"encoding/json"
"fmt"
"net/http"
"strings"
v3 "github.com/rancher/types/apis/management.cattle.io/v3"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
admin "google.golang.org/api/admin/directory/v1"
"google.golang.org/api/googleapi"
)
func (g *googleOauthProvider) getUserInfoAndGroups(adminSvc *admin.Service, gOAuthToken *oauth2.Token, config *v3.GoogleOauthConfig) (v3.Principal, []v3.Principal, error) {
var userPrincipal v3.Principal
var groupPrincipals []v3.Principal
// use the access token to make requests, get user info
user, err := g.goauthClient.getUser(gOAuthToken.AccessToken, config)
if err != nil {
return userPrincipal, groupPrincipals, err
}
userPrincipal = g.toPrincipal(userType, *user, nil)
userPrincipal.Me = true
logrus.Debugf("[Google OAuth] loginuser: Obtained userinfo using oauth access token")
groupPrincipals, err = g.getGroupsUserBelongsTo(adminSvc, user.SubjectUniqueID, user.HostedDomain, config)
if err != nil {
// The error for this group request could be 403, because svc acc was not provided, and we're relying on individual
// users' creds to get groups
if config.ServiceAccountCredential == "" {
if gErr, ok := err.(*googleapi.Error); !ok || gErr.Code != http.StatusForbidden {
// if the error is not forbidden, return the error
return userPrincipal, groupPrincipals, err
}
// if the error is forbidden, don't throw any error, just no group principals will be returned
} else {
// getting any error in spite of svc acc creds must be returned
return userPrincipal, groupPrincipals, err
}
}
logrus.Debugf("[Google OAuth] loginuser: Retrieved user's groups using admin directory")
return userPrincipal, groupPrincipals, nil
}
func (g *googleOauthProvider) getGroupsUserBelongsTo(adminSvc *admin.Service, userKey string, hostedDomain string, config *v3.GoogleOauthConfig) ([]v3.Principal, error) {
var groupPrincipals []v3.Principal
_, groups, err := g.paginateResults(adminSvc, hostedDomain, userKey, "", "", groupType, false)
if err != nil {
// The error for this group request could be 403, because svc acc was not provided, and we're relying on individual
// users' creds to get groups
if config.ServiceAccountCredential == "" {
// used the client creds, if error is forbidden, don't throw error
if gErr, ok := err.(*googleapi.Error); ok && gErr.Code == http.StatusForbidden {
return groupPrincipals, nil
}
}
// getting any error in spite of svc acc creds must be returned
return nil, err
}
for _, gr := range groups {
group := Account{Name: gr.Name, Email: gr.Email, SubjectUniqueID: gr.Id}
groupPrincipal := g.toPrincipal(groupType, group, nil)
groupPrincipal.MemberOf = true
groupPrincipals = append(groupPrincipals, groupPrincipal)
}
return groupPrincipals, nil
}
func (g *googleOauthProvider) searchPrincipals(adminSvc *admin.Service, searchKey, principalType string, config *v3.GoogleOauthConfig) ([]Account, error) {
var accounts []Account
if principalType == "" || principalType == "user" {
userAccounts, err := g.searchUsers(adminSvc, searchKey, config, false)
if err != nil {
if config.ServiceAccountCredential == "" {
// used the client creds, must try once with viewType domain_public
if gErr, ok := err.(*googleapi.Error); ok && gErr.Code == http.StatusForbidden {
userAccounts, err = g.searchUsers(adminSvc, searchKey, config, true)
if err != nil {
return nil, err
}
} else {
return nil, err
}
} else {
// getting any error in spite of svc acc creds must be returned
return nil, err
}
}
accounts = append(accounts, userAccounts...)
}
if principalType == "" || principalType == "group" {
groupAccounts, err := g.searchGroups(adminSvc, searchKey, config)
if err != nil {
if config.ServiceAccountCredential == "" {
// used the client creds, if error is forbidden, don't throw error
if gErr, ok := err.(*googleapi.Error); ok && gErr.Code == http.StatusForbidden {
return accounts, nil
}
}
// getting any error in spite of svc acc creds must be returned
return nil, err
}
accounts = append(accounts, groupAccounts...)
}
return accounts, nil
}
func (g *googleOauthProvider) searchUsers(adminSvc *admin.Service, searchKey string, config *v3.GoogleOauthConfig, viewPublic bool) ([]Account, error) {
var users []*admin.User
var accounts []Account
users, _, err := g.paginateResults(adminSvc, config.Hostname, "", searchKey, "", userType, viewPublic)
if err != nil {
return accounts, err
}
for _, u := range users {
a := Account{
SubjectUniqueID: u.Id,
Email: u.PrimaryEmail,
PictureURL: u.ThumbnailPhotoUrl,
Type: userType,
}
if u.Name != nil {
a.Name = u.Name.FullName
a.GivenName = u.Name.GivenName
a.FamilyName = u.Name.FamilyName
}
accounts = append(accounts, a)
}
return accounts, nil
}
func (g *googleOauthProvider) searchGroups(adminSvc *admin.Service, searchKey string, config *v3.GoogleOauthConfig) ([]Account, error) {
var accounts []Account
groupsMap := map[string]*admin.Group{}
for _, attr := range []string{"name", "email"} {
_, resGroups, err := g.paginateResults(adminSvc, config.Hostname, "", searchKey, attr, groupType, false)
if err != nil {
return accounts, err
}
//dedup groups
for _, gr := range resGroups {
if _, ok := groupsMap[gr.Id]; !ok {
groupsMap[gr.Id] = gr
}
}
}
for _, g := range groupsMap {
accounts = append(accounts, Account{SubjectUniqueID: g.Id, Email: g.Email, Name: g.Name, Type: groupType})
}
return accounts, nil
}
func (g *googleOauthProvider) paginateResults(adminSvc *admin.Service, hostedDomain, memberKey, searchKey, searchAttr, accountType string, viewPublic bool) ([]*admin.User, []*admin.Group, error) {
var groups []*admin.Group
var users []*admin.User
switch accountType {
case userType:
// in case of list users call, using the searchKey itself as query searches all attributes for the search key
userListCall := adminSvc.Users.List().Domain(hostedDomain).Query(searchKey)
if viewPublic {
userListCall.ViewType(domainPublicViewType)
}
for {
res, err := userListCall.Do()
if err != nil {
return users, nil, err
}
users = append(users, res.Users...)
if res.NextPageToken == "" {
return users, nil, nil
}
userListCall.PageToken(res.NextPageToken)
}
case groupType:
groupListCall := adminSvc.Groups.List().Domain(hostedDomain)
if memberKey != "" {
groupListCall.UserKey(memberKey)
} else if searchKey != "" {
// in case of list groups call, we need to specify search attributes
groupListCall.Query(searchAttr + ":" + searchKey + "*")
}
for {
res, err := groupListCall.Do()
if err != nil {
return nil, groups, err
}
groups = append(groups, res.Groups...)
if res.NextPageToken == "" {
return nil, groups, nil
}
groupListCall.PageToken(res.NextPageToken)
}
default:
return nil, nil, fmt.Errorf("paginateResults: Invalid principal type")
}
}
func (g *googleOauthProvider) getdirectoryServiceFromStoredToken(storedOauthToken string, config *v3.GoogleOauthConfig) (*admin.Service, error) {
var oauthToken oauth2.Token
if err := json.Unmarshal([]byte(storedOauthToken), &oauthToken); err != nil {
return nil, err
}
oauth2Config, err := google.ConfigFromJSON([]byte(config.OauthCredential), scopes...)
if err != nil {
return nil, err
}
adminSvc, err := g.getDirectoryService(g.ctx, config.AdminEmail, []byte(config.ServiceAccountCredential), oauth2Config.TokenSource(g.ctx, &oauthToken))
if err != nil {
return nil, err
}
return adminSvc, nil
}
func getUIDFromPrincipalID(principalID string) (string, string, error) {
var externalID string
parts := strings.SplitN(principalID, ":", 2)
if len(parts) != 2 {
return "", "", fmt.Errorf("invalid id %v", principalID)
}
externalID = strings.TrimPrefix(parts[1], "//")
parts = strings.SplitN(parts[0], "_", 2)
if len(parts) != 2 {
return "", "", fmt.Errorf("invalid id %v", principalID)
}
return externalID, parts[1], nil
}