-
Notifications
You must be signed in to change notification settings - Fork 12
/
main.go
404 lines (322 loc) · 10.5 KB
/
main.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
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package main
import (
"flag"
"fmt"
"log"
"os"
"sort"
"strings"
"text/tabwriter"
"github.com/dvcrn/maskedemail-cli/pkg"
)
type actionType string
const (
defaultAppname string = "maskedemail-cli"
envTokenVarName string = "MASKEDEMAIL_TOKEN"
envAppVarName string = "MASKEDEMAIL_APPNAME"
envAccountIdVarName string = "MASKEDEMAIL_ACCOUNTID"
flagNameToken string = "token"
flagNameAccountID string = "accountid"
flagNameEmail string = "email"
flagNameDomain string = "domain"
flagNameDesc string = "desc"
flagNamePrefix string = "prefix"
flagNameEnabled string = "enabled"
flagNameShowDeleted string = "show-deleted"
flagNameShowAllFields string = "all-fields"
actionTypeUnknown = ""
actionTypeCreate = "create"
actionTypeSession = "session"
actionTypeDisable = "disable"
actionTypeEnable = "enable"
actionTypeDelete = "delete"
actionTypeUpdate = "update"
actionTypeList = "list"
actionTypeVersion = "version"
)
// build info values get passed in from makefile via `-ldflags` argument to `go build`
//
// they only exist if within a git repo, otherwise use defaults below
//
// version is based on a git tag "vX.Y.Z" existing
var buildVersion string = "development"
var buildCommit string = "n/a"
// default / highest level flags
var flagAppname = flag.String("appname", os.Getenv(envAppVarName), "the appname to identify the creator (or "+envAppVarName+" env) (default: "+defaultAppname+")")
var flagToken = flag.String(flagNameToken, "", "the token to authenticate with (or "+envTokenVarName+" env)")
var flagAccountID = flag.String(flagNameAccountID, os.Getenv(envAccountIdVarName), "fastmail account id (or "+envAccountIdVarName+" env)")
// flags for list command
var listCmd = flag.NewFlagSet(actionTypeList, flag.ExitOnError)
var flagShowDeleted = listCmd.Bool(flagNameShowDeleted, false, "show deleted masked emails (true|false) (default false)")
var flagShowAllFields = listCmd.Bool(flagNameShowAllFields, false, "show all masked email fields (true|false) (default false)")
// flags for create command
var createCmd = flag.NewFlagSet(actionTypeCreate, flag.ExitOnError)
var flagCreateDomain = createCmd.String(flagNameDomain, "", "domain for the masked email (optional)")
var flagCreateDescription = createCmd.String(flagNameDesc, "", "description for the masked email (optional)")
var flagCreateEmailPrefix = createCmd.String(flagNamePrefix, "", "prefix for the masked email (optional)")
var flagCreateEnabled = createCmd.Bool(flagNameEnabled, true, "is masked email enabled (true|false)")
// flags for update command
var updateCmd = flag.NewFlagSet(actionTypeUpdate, flag.ExitOnError)
var flagUpdateDomain = updateCmd.String(flagNameDomain, "", "domain for the masked email (optional, only updated if argument passed)")
var flagUpdateDescription = updateCmd.String(flagNameDesc, "", "description for the masked email (optional, only updated if argument passed)")
var args []string
var action actionType = actionTypeUnknown
var commandArg string
var envToken string
func isFlagPassed(set flag.FlagSet, name string) bool {
found := false
//fmt.Printf("name: %s\n", name)
set.Visit(func(f *flag.Flag) {
// fmt.Printf("f.Name: %s\n", f.Name)
if f.Name == name {
found = true
}
})
return found
}
func init() {
flag.Parse()
// get all args after the global args
args = flag.Args()
// Define initial help message
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", os.Args[0])
fmt.Println("Global Flags:")
flag.PrintDefaults()
fmt.Println("")
fmt.Println("Commands:")
// create
fmt.Printf(" %s %s [-%s \"<domain>\"] [-%s \"<description>\"] [-%s \"<prefix>\"] [-%s=true|false (default true)]\n",
defaultAppname, actionTypeCreate, flagNameDomain, flagNameDesc, flagNamePrefix, flagNameEnabled)
// list
fmt.Printf(" %s %s [-%s] [-%s]\n",
defaultAppname, actionTypeList, flagNameShowDeleted, flagNameShowAllFields)
// enable
fmt.Printf(" %s %s <maskedemail>\n",
defaultAppname, actionTypeEnable)
// disable
fmt.Printf(" %s %s <maskedemail>\n",
defaultAppname, actionTypeDisable)
// delete
fmt.Printf(" %s %s <maskedemail>\n",
defaultAppname, actionTypeDelete)
// update
fmt.Printf(" %s %s <maskedemail> [-%s \"<domain>\"] [-%s \"<description>\"]\n",
defaultAppname, actionTypeUpdate, flagNameDomain, flagNameDesc)
// session
fmt.Printf(" %s %s\n",
defaultAppname, actionTypeSession)
// version
fmt.Printf(" %s %s\n",
defaultAppname, actionTypeVersion)
}
// determine command/subcommand
commandArg = ""
if len(args) > 0 {
commandArg = strings.ToLower(args[0])
}
// Check global arguments:
// CLI parameter have precedence over ENV variables
if *flagToken == "" && commandArg != actionTypeVersion {
envToken = os.Getenv(envTokenVarName)
if envToken != "" {
*flagToken = envToken
} else {
flag.Usage()
os.Exit(1)
}
}
if *flagAppname == "" {
*flagAppname = defaultAppname
}
switch commandArg {
case actionTypeVersion:
action = actionTypeVersion
case actionTypeCreate:
action = actionTypeCreate
case actionTypeSession:
action = actionTypeSession
case actionTypeDisable:
action = actionTypeDisable
case actionTypeEnable:
action = actionTypeEnable
case actionTypeDelete:
action = actionTypeDelete
case actionTypeList:
action = actionTypeList
case actionTypeUpdate:
action = actionTypeUpdate
}
}
func main() {
client := pkg.NewClient(*flagToken, *flagAppname, "35c941ae")
switch action {
case actionTypeVersion:
fmt.Printf("version: %s\n", buildVersion)
fmt.Printf("commit: %s\n", buildCommit)
case actionTypeSession:
session, err := client.Session()
if err != nil {
log.Fatalf("fetching session: %v", err)
}
var accIDs []string
for accID := range session.Accounts {
if *flagAccountID != "" && *flagAccountID != accID {
continue
}
accIDs = append(accIDs, accID)
}
primaryAccountID := session.PrimaryAccounts[pkg.MaskedEmailCapabilityURI]
sort.Slice(
accIDs,
func(i, j int) bool {
if primaryAccountID == accIDs[i] {
return true
}
return accIDs[i] < accIDs[j]
},
)
for _, accID := range accIDs {
isPrimary := primaryAccountID == accID
isEnabled := session.AccountHasCapability(accID, pkg.MaskedEmailCapabilityURI)
fmt.Printf(
"%s [%s] (primary: %t, enabled: %t)\n",
session.Accounts[accID].Name,
accID,
isPrimary,
isEnabled,
)
}
case actionTypeCreate:
// parse command-specific args
createCmd.Parse(args[1:])
domain := strings.TrimSpace(*flagCreateDomain)
description := strings.TrimSpace(*flagCreateDescription)
emailPrefix := strings.TrimSpace(*flagCreateEmailPrefix)
session, err := client.Session()
if err != nil {
log.Fatalf("initializing session: %v", err)
}
createRes, err := client.CreateMaskedEmail(session, *flagAccountID, domain, description, emailPrefix, *flagCreateEnabled)
if err != nil {
log.Fatalf("error creating masked email: %v", err)
}
// success output
fmt.Println(createRes.Email)
case actionTypeDisable:
maskedemail := strings.TrimSpace(args[1])
if maskedemail == "" {
log.Fatalln("Usage: disable <maskedemail>")
}
session, err := client.Session()
if err != nil {
log.Fatalf("initializing session: %v", err)
}
_, err = client.DisableMaskedEmail(session, *flagAccountID, maskedemail)
if err != nil {
log.Fatalf("error disabling masked email: %v", err)
}
// success output
fmt.Printf("disabled masked email: %s\n", maskedemail)
case actionTypeEnable:
maskedemail := strings.TrimSpace(args[1])
if maskedemail == "" {
log.Fatalln("Usage: enable <maskedemail>")
}
session, err := client.Session()
if err != nil {
log.Fatalf("initializing session: %v", err)
}
_, err = client.EnableMaskedEmail(session, *flagAccountID, maskedemail)
if err != nil {
log.Fatalf("error enabling masked email: %v", err)
}
// success output
fmt.Printf("enabled masked email: %s\n", maskedemail)
case actionTypeDelete:
maskedemail := strings.TrimSpace(args[1])
if maskedemail == "" {
log.Fatalln("Usage: delete <maskedemail>")
}
session, err := client.Session()
if err != nil {
log.Fatalf("initializing session: %v", err)
}
_, err = client.DeleteMaskedEmail(session, *flagAccountID, maskedemail)
if err != nil {
log.Fatalf("error deleting masked email: %v", err)
}
// success output
fmt.Printf("deleted masked email: %s\n", maskedemail)
case actionTypeList:
// parse command-specific args
listCmd.Parse(args[1:])
session, err := client.Session()
if err != nil {
log.Fatalf("initializing session: %v", err)
}
maskedEmails, err := client.GetAllMaskedEmails(session, *flagAccountID, *flagShowDeleted)
if err != nil {
log.Fatalf("err while getting maskedemails: %v", err)
}
w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
// display header line
if *flagShowAllFields {
fmt.Fprintln(w, "Masked Email\tFor Domain\tDescription\tState\tID\tCreated At\tLast Email At")
} else {
fmt.Fprintln(w, "Masked Email\tFor Domain\tDescription\tState")
}
// display each masked email
for _, email := range maskedEmails {
// HACK: trim space here is for hack to deal with possible empty strings
if *flagShowAllFields {
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
email.Email,
strings.TrimSpace(email.Domain),
strings.TrimSpace(email.Description),
email.State,
email.ID,
email.CreatedAt,
email.LastMessageAt)
} else {
fmt.Fprintf(w, "%s\t%s\t%s\t%s\n",
email.Email,
strings.TrimSpace(email.Domain),
strings.TrimSpace(email.Description),
email.State)
}
}
w.Flush()
case actionTypeUpdate:
maskedemail := strings.TrimSpace(args[1])
// parse command-specific args
updateCmd.Parse(args[2:])
domain := strings.TrimSpace(*flagUpdateDomain)
description := strings.TrimSpace(*flagUpdateDescription)
session, err := client.Session()
if err != nil {
log.Fatalf("initializing session: %v", err)
}
opts := []pkg.UpdateOption{}
if isFlagPassed(*updateCmd, flagNameDomain) {
opts = append(opts, pkg.WithUpdateDomain(domain))
}
if isFlagPassed(*updateCmd, flagNameDesc) {
opts = append(opts, pkg.WithUpdateDescription(description))
}
if len(opts) == 0 {
log.Println("no update options specified")
updateCmd.Usage()
os.Exit(1)
}
_, err = client.UpdateInfo(session, *flagAccountID, maskedemail, opts...)
if err != nil {
log.Fatalf("error updating masked email: %v", err)
}
fmt.Printf("updated %s\n", maskedemail)
default:
fmt.Println("action not found\n")
flag.Usage()
os.Exit(1)
}
}