-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathremove.go
More file actions
257 lines (223 loc) · 5.81 KB
/
Copy pathremove.go
File metadata and controls
257 lines (223 loc) · 5.81 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
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
//
// Copyright (c) 2019 Sony Mobile Communications Inc.
// SPDX-License-Identifier: MIT
//
package cmd
import (
"fmt"
"ghorgs/gnet"
"ghorgs/model"
"ghorgs/utils"
cmds "github.com/spf13/cobra"
"log"
"net/http"
"path"
"regexp"
"strings"
)
type remover struct {
quiet bool
mfa bool
company bool
access bool
names []string
data map[string]*model.Table
}
var (
r = &remover{}
removeCmd = &cmds.Command{
Use: "remove",
Short: "Remove GitHub users according to given criteria.",
Long: `Remove GitHub users according to given criteria.`,
Args: r.validateArgs,
Run: r.run,
}
users = model.Users
usersFields = model.Users.GetFields().(*model.UsersFields)
)
func init() {
removeCmd.Flags().BoolP("quiet",
"q",
false,
"DO NOT ask user for confirmation. "+
"(Use with care, e.g. in scripts where interaction is minimal or impossible.)")
removeCmd.Flags().BoolP("MFA",
"m",
false,
"Remove users without MFA set up.")
removeCmd.Flags().BoolP("company",
"c",
false,
"Remove users without company affiliation.")
removeCmd.Flags().BoolP("access",
"a",
false,
"Remove users without access to any repository owned by the organization.")
removeCmd.Flags().StringP("users",
"r",
"",
"Comma separated list of users to remove. "+
"Name can contain alphanumeric and special characters '_', '.' and '-'.")
rootCmd.AddCommand(removeCmd)
}
func (r *remover) addCache(c map[string]*model.Table) {
r.data = c
}
func (r *remover) validateArgs(c *cmds.Command, args []string) error {
var err error
r.quiet, err = c.Flags().GetBool("quiet")
if err != nil {
panic(err)
}
r.mfa, err = c.Flags().GetBool("2FA")
if err != nil {
panic(err)
}
r.company, err = c.Flags().GetBool("company")
if err != nil {
panic(err)
}
r.access, err = c.Flags().GetBool("access")
if err != nil {
panic(err)
}
// Verify that users are a comma separated list of alphanumerics and
// special characters '.', '_' and '-'.
// Ignore other criteria.
users, err := c.Flags().GetString("users")
if err != nil {
panic(err)
}
if users != "" {
matched, err := regexp.MatchString(`^[\.|\-|\_|[:alnum:]]+(\,[\.|\-|\_|[:alnum:]]+)*$`, users)
if err != nil {
return err
}
if !matched {
return fmt.Errorf("--users can only contain a comma separated list of usernames " +
"written in ascii alpha-numeric characters ([._-] are allowed.).")
}
r.names = strings.Split(users, ",")
r.mfa = false
r.company = false
r.access = false
}
return nil
}
func (r *remover) run(c *cmds.Command, args []string) {
if gnet.Conf.User == "" || gnet.Conf.Token == "" {
fmt.Println("Error! Invalid credentials.")
return
}
// 0. get cache for users
ca, err := Cache([]model.Entity{users})
if err != nil {
fmt.Println("Error!", err.Error())
return
}
r.addCache(ca)
// 2. if --users set, get cache projection to --users,
var projection *model.Table
if r.names != nil {
projection, err = r.dataProjectionByName()
if err != nil {
fmt.Println(err.Error())
if projection == nil {
// nothing to work with so just return
return
}
}
} else {
projection = r.data[users.GetName()]
}
// 2FA, Company affiliation and Accessible repositories
// criteria are combined with AND operation.
// (Note: if r.names == true,
// then r.mfa == r.company == r.access == false)
// 1. check by 2FA
if r.mfa {
tmp, err := projection.FindAllByField(usersFields.MFA.Name, "false")
if err != nil {
fmt.Println(err.Error())
// allow partial results, so don't return
}
if tmp == nil {
// nothing to work with so return here
return
}
projection = tmp
}
// 2. check by company affiliation
if r.company {
tmp, err := projection.FindAllByField(usersFields.Company.Name, "")
if err != nil {
fmt.Println(err.Error())
// allow partial results, so don't return
}
if tmp == nil {
// nothing to work with so return here
return
}
projection = tmp
}
// 3. check by accessible repositories
if r.access {
tmp, err := projection.FindAllByField(usersFields.Repositories.Name, "0")
if err != nil {
fmt.Println(err.Error())
// allow partial results, so don't return
}
if tmp == nil {
// nothing to work with so return here
return
}
projection = tmp
}
if projection == nil {
// nothing to work with so just return
return
}
// 4. display the result to the user and request confirmation
fmt.Printf("\nThe following users will be removed from the organization (%d):\n",
len(projection.Keys))
fmt.Printf("%s\n", projection)
if !r.quiet && !utils.GetUserConfirmation() {
return
}
// 5. iterate over the result to remove the users
for _, key := range projection.Keys {
userLogin := projection.Records[key][usersFields.Login.Index]
// create GitHub v3 request to delete a user:
// DELETE /orgs/:org/members/:username
rmRequest := gnet.MakeGitHubV3Request(http.MethodDelete,
path.Join("orgs",
gnet.Conf.Organization,
"members",
userLogin),
gnet.Conf.Token)
if utils.Debug.DryRun {
fmt.Printf("Executing %s %s\n", rmRequest.Url, rmRequest.Method)
} else {
resp, status := rmRequest.Execute()
if utils.Debug.Verbose {
log.Print(resp)
}
// check response for error:
// - `Status: 204 No Content` is OK
// - `Status: 403 Forbidden` - abort since Token doesn't have Delete rights
// - Any other code, continue
if status.Code == http.StatusForbidden {
fmt.Println("Error! HttpResponse:", status.Status)
fmt.Println("Token is not allowed to delete repository.")
return
}
if status.Code != http.StatusOK && status.Code != http.StatusNoContent {
fmt.Println("Error! HttpResponse:", status.Status)
continue
}
}
}
}
func (r *remover) dataProjectionByName() (*model.Table, error) {
return r.data[users.GetName()].FindAllByFieldValues(usersFields.Login.Name, r.names)
}