-
Notifications
You must be signed in to change notification settings - Fork 6
/
commands.go
1140 lines (990 loc) · 28.8 KB
/
commands.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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"fmt"
"net/url"
"os/exec"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"github.com/renatoathaydes/go-hash/encryption"
"github.com/renatoathaydes/go-hash/gohash_db"
"github.com/atotto/clipboard"
"github.com/chzyer/readline"
"golang.org/x/crypto/ssh/terminal"
)
// State local alias
type State = gohash_db.State
// LoginInfo local alias
type LoginInfo = gohash_db.LoginInfo
type command interface {
// run a command with the given state, within the given group.
run(state *State, group string, args string, reader *bufio.Reader)
// help returns helpful information about how to use this command.
help() string
// a full explanation of how this command works.
longHelp() string
// the auto-completer for this command
completer() readline.PrefixCompleterInterface
// requires password after idle timeout
requiresPasswordIfIdleTooLong() bool
}
type helpCommand struct {
commands map[string]command
}
type entryCommand struct {
entries func() []string
}
type groupCommand struct {
groups func() []string
groupBox *stringBox
}
type cpCommand struct {
entries func() []string
}
type gotoCommand struct {
entries func() []string
}
type cmpCommand struct {
mpBox *stringBox
}
type stringBox struct {
value string
}
// ============= CLI creation ============= //
func createCommands(state *State, groupBox *stringBox, masterPassBox *stringBox) map[string]command {
getGroups := func() []string {
result := make([]string, len(*state), len(*state))
i := 0
for gr := range *state {
result[i] = gr
i++
}
return result
}
getEntries := func() []string {
entries := (*state)[groupBox.value]
result := make([]string, len(entries), len(entries))
for i, e := range entries {
result[i] = e.Name
}
return result
}
var commands = map[string]command{
"group": groupCommand{
groups: getGroups,
groupBox: groupBox,
},
"entry": entryCommand{
entries: getEntries,
},
"cp": cpCommand{
entries: getEntries,
},
"goto": gotoCommand{
entries: getEntries,
},
"cmp": cmpCommand{
mpBox: masterPassBox,
},
}
commands["help"] = helpCommand{
commands: commands,
}
return commands
}
func createCompleter(commands map[string]command) *readline.PrefixCompleter {
var cmdItems = make([]readline.PrefixCompleterInterface, len(commands)+2)
i := 0
for _, cmd := range commands {
cmdItems[i] = cmd.completer()
i++
}
cmdItems[i] = readline.PcItem("exit")
cmdItems[i+1] = readline.PcItem("quit")
return readline.NewPrefixCompleter(cmdItems...)
}
// ============= Commands: Short help ============= //
func (cmd helpCommand) help() string {
return "prints this message or help about a specific command."
}
func (cmd entryCommand) help() string {
return "manages entries within the current group."
}
func (cmd groupCommand) help() string {
return "manages/enters groups."
}
func (cmd cpCommand) help() string {
return "copies an entry's field to the clipboard. Fields: -p = password, -u = username."
}
func (cmd gotoCommand) help() string {
return "goes to the URL associated with an entry and copies its password to the clipboard."
}
func (cmd cmpCommand) help() string {
return "changes the master password."
}
// ============= Commands: Long help ============= //
const helpUsage = `
=== help command usage ===
The help command prints helpful information.
Usage:
help [<name>]
Without a <name> argument, the help command shows general go-hash usage,
otherwise full information about a specific command is shown.
`
const entryUsage = `
=== entry command usage ===
The entry command is used to manage entries within the current group or a specified group.
To switch to a different group, use the 'group' command (type 'help group' for more information about groups).
Usage:
entry [-option] [[<group>:]<name>]
Options:
-c create an entry.
-d delete an entry.
-e edit an entry.
-r rename an entry.
Without an option or an argument, the entry command simply lists all entries within the current group.
Typing 'entry <name>' will either display information about the entry, or create it if the entry does not exist.
Examples:
# list all entries in the current group
entry
# delete the entry called 'hello' in the current group
entry -d hello
# display the entry called 'foo' in the 'top-secret' group
entry top-secret:foo
`
const groupUsage = `
=== group command usage ===
The group command is used to manage groups or enter a group in order to manage its entries.
Usage:
group [-option] [<name>]
Options:
-c <name> create a group.
-d <name> delete a group.
-r <name> rename a group.
Without an option or a <name> argument, the group command simply lists all groups in the database.
Typing 'group <name>' will either enter the group (so that the 'entry' command will apply to entries
within the chosen group) , or create it if it does not exist.
After entering a group, the 'entry' command applies only to the entries within the entered group.
Type 'exit' to exit a group.
A group called 'default' is used if no group is entered. This group always exists but is not
shown in the prompt as other groups, allowing the user to manage entries without using groups
explicitly.
Examples:
# list all groups
group
# delete a group called 'hello'
group -d hello
`
const copyUsage = `
=== cp command usage ===
The cp command can be used to copy information about entries to the clipboard.
That allows users to easily copy/paste the information where the information is required.
Usage:
cp [-option] [<group>:]<name>
Options:
-u copy the username.
-p copy the password.
If an option is not provided, the username associated with the chosen entry is copied.
Information is automatically removed from the clipboard after one minute.
Examples:
# copy the username associated with the 'hello' entry
cp hello
# copy the password associated with the 'other' entry
cp -p other
`
const gotoUsage = `
=== goto command usage ===
The goto command helps users login safely into websites by opening the URL associated with
an entry directly in the default browser, then copying the password to the clipboard so that
it can be pasted into the login form without waste of time.
Usage:
goto [-option] [<group>:]<name>
Options:
-n do not copy the password.
If the -n option is not used, the entry's password is copied to the clipboard automatically.
Examples:
# go to the web page (URL) associated with the 'hello' entry
goto hello
`
const cmpUsage = `
=== cmp command usage ===
The cmp command is used to change the master password.
No options or arguments are accepted.
`
func (cmd helpCommand) longHelp() string {
return helpUsage
}
func (cmd entryCommand) longHelp() string {
return entryUsage
}
func (cmd groupCommand) longHelp() string {
return groupUsage
}
func (cmd cpCommand) longHelp() string {
return copyUsage
}
func (cmd gotoCommand) longHelp() string {
return gotoUsage
}
func (cmd cmpCommand) longHelp() string {
return cmpUsage
}
// ============= Commands: Auto-completers ============= //
func (cmd helpCommand) completer() readline.PrefixCompleterInterface {
commands := cmd.commands
commandItems := make([]readline.PrefixCompleterInterface, len(commands), len(commands))
i := 0
for name := range commands {
commandItems[i] = readline.PcItem(name)
i++
}
return readline.PcItem("help", commandItems...)
}
func commandCompleter(getValues func() []string) readline.PrefixCompleterInterface {
resolve := func(line string) []string {
return getValues()
}
return readline.PcItemDynamic(resolve)
}
func (cmd entryCommand) completer() readline.PrefixCompleterInterface {
cmp := commandCompleter(cmd.entries)
return readline.PcItem("entry",
cmp,
readline.PcItem("-c"),
readline.PcItem("-d", cmp),
readline.PcItem("-e", cmp),
readline.PcItem("-r", cmp))
}
func (cmd groupCommand) completer() readline.PrefixCompleterInterface {
cmp := commandCompleter(cmd.groups)
return readline.PcItem("group",
cmp,
readline.PcItem("-c"),
readline.PcItem("-d", cmp),
readline.PcItem("-r", cmp))
}
func (cmd cpCommand) completer() readline.PrefixCompleterInterface {
cmp := commandCompleter(cmd.entries)
return readline.PcItem("cp",
cmp,
readline.PcItem("-u", cmp),
readline.PcItem("-p", cmp))
}
func (cmd gotoCommand) completer() readline.PrefixCompleterInterface {
cmp := commandCompleter(cmd.entries)
return readline.PcItem("goto",
cmp,
readline.PcItem("-n", cmp))
}
func (cmd cmpCommand) completer() readline.PrefixCompleterInterface {
return readline.PcItem("cmp")
}
// ============= Commands: requires password after idle timeout ============= //
func (cmd helpCommand) requiresPasswordIfIdleTooLong() bool {
return false
}
func (cmd entryCommand) requiresPasswordIfIdleTooLong() bool {
return true
}
func (cmd groupCommand) requiresPasswordIfIdleTooLong() bool {
return true
}
func (cmd cpCommand) requiresPasswordIfIdleTooLong() bool {
return true
}
func (cmd gotoCommand) requiresPasswordIfIdleTooLong() bool {
return true
}
func (cmd cmpCommand) requiresPasswordIfIdleTooLong() bool {
return false // it will ask for the password in the implementation
}
// ============= Commands: run implementations ============= //
func (cmd helpCommand) run(state *State, group, args string, reader *bufio.Reader) {
commands := cmd.commands
if args == "" {
println("go-hash commands:\n")
for name, cmd := range commands {
fmt.Printf(" %-8s %s\n", name, cmd.help())
}
println("\nType 'exit' to exit a group or quit if you are not within a group.")
println("To quit from anywhere, type 'quit'.")
} else {
cmd, exists := commands[args]
if exists {
println(cmd.longHelp())
} else {
println("Error: command does not exist.")
}
}
}
func (cmd entryCommand) run(state *State, group, args string, reader *bufio.Reader) {
var (
CreateEntry bool
DeleteEntry bool
RenameEntry bool
EditEntry bool
entry string
)
switch {
case strings.HasPrefix(args, "-c"):
CreateEntry = true
entry = strings.TrimSpace(args[2:])
case strings.HasPrefix(args, "-d"):
DeleteEntry = true
entry = strings.TrimSpace(args[2:])
case strings.HasPrefix(args, "-r"):
RenameEntry = true
entry = strings.TrimSpace(args[2:])
case strings.HasPrefix(args, "-e"):
EditEntry = true
entry = strings.TrimSpace(args[2:])
case strings.HasPrefix(args, "-"):
println("Error: unknown option. Type 'help entry' for usage.")
return
default:
entry = args
}
switch {
case CreateEntry:
createOrShowEntry(entry, state, group, reader, true)
case DeleteEntry:
removeEntry(entry, state, group, reader)
case RenameEntry:
renameEntry(entry, state, group, reader)
case EditEntry:
editEntry(entry, state, group, reader)
// no option provided, the next cases list or offer to create an entry
case len(entry) > 0:
createOrShowEntry(entry, state, group, reader, false)
default:
entries := (*state)[group]
fmt.Printf("Showing group %s:\n\n", groupDescription(group, &entries, false))
if len(entries) > 0 {
for _, e := range entries {
println(e.String())
}
}
println("\nHint: To show the details of a single entry, type 'entry <name>'.")
}
}
func (cmd groupCommand) run(state *State, group, args string, reader *bufio.Reader) {
var (
CreateGroup bool
DeleteGroup bool
RenameGroup bool
groupName string
)
switch {
case strings.HasPrefix(args, "-c"):
CreateGroup = true
groupName = strings.TrimSpace(args[2:])
case strings.HasPrefix(args, "-d"):
DeleteGroup = true
groupName = strings.TrimSpace(args[2:])
case strings.HasPrefix(args, "-r"):
RenameGroup = true
groupName = strings.TrimSpace(args[2:])
case strings.HasPrefix(args, "-"):
println("Error: unknown option. Type 'help group' for usage.")
return
default:
groupName = args
}
switch {
case CreateGroup:
cmd.groupBox.value = createGroup(groupName, state, group, reader)
case DeleteGroup:
cmd.groupBox.value = removeGroup(groupName, state, group, reader)
case RenameGroup:
cmd.groupBox.value = renameGroup(groupName, state, group, reader)
// no option selected, list or offer to create group
case len(groupName) > 0:
_, groupExists := (*state)[groupName]
if groupExists {
cmd.groupBox.value = groupName
} else {
newGroupWanted := yesNoQuestion("Group does not exist, do you want to create it?", reader, true)
if newGroupWanted {
cmd.groupBox.value = createGroup(groupName, state, group, reader)
}
}
default:
groupLen := len(*state)
switch groupLen {
case 1:
println("There is 1 group:\n")
default:
fmt.Printf("There are %d groups:\n\n", groupLen)
}
for groupName, entries := range *state {
fmt.Printf(" %s\n", groupDescription(groupName, &entries, true))
}
println("\nHint: Type 'entry' to list all entries in the current group.")
}
}
func (cmd cpCommand) run(state *State, group, args string, reader *bufio.Reader) {
CopyPassword := false
CopyUsername := false
entries := (*state)[group]
var entry string
switch {
case strings.HasPrefix(args, "-p"):
CopyPassword = true
entry = strings.TrimSpace(args[2:])
case strings.HasPrefix(args, "-u"):
CopyUsername = true
entry = strings.TrimSpace(args[2:])
case strings.HasPrefix(args, "-"):
println("Error: Unknown option.")
println("Hint: valid options are: -p (password), -u (username)")
return
default:
CopyUsername = true
entry = args
}
showEntryHint := func() {
if len(entries) > 0 {
entryNames := make([]string, len(entries))
for i, e := range entries {
entryNames[i] = e.Name
}
fmt.Printf("Hint: under the current group, %s, the following entries exist: %s\n", group, strings.Join(entryNames, ", "))
} else if len(*state) > 1 {
println("Hint: there are no entries under the current group! " +
"To enter a group which contains entries, use the 'group' command. " +
"Type 'ls' to list all groups.")
} else {
println("Hint: there are no entries yet! You can create a new entry with the 'entry' command! " +
"For example, try typing 'entry gmail'.")
}
}
if len(entry) == 0 {
println("Error: please provide an entry name.")
showEntryHint()
} else {
entryIndex, found := findEntryIndex(&entries, entry)
if !found && strings.Contains(entry, ":") {
// split up group:entry from user input
parts := strings.SplitN(entry, ":", 2)
group = parts[0]
entry = parts[1]
entries = (*state)[group]
entryIndex, found = findEntryIndex(&entries, entry)
}
if found {
var content string
switch {
case CopyPassword:
content = entries[entryIndex].Password
case CopyUsername:
content = entries[entryIndex].Username
default:
panic("Unexpected field case")
}
err := clipboard.WriteAll(content)
if err != nil {
fmt.Printf("Error: unable to copy! Reason: %s\n", err.Error())
} else {
go removeFromClipboardAfterDelay(content)
}
} else {
fmt.Printf("Error: entry '%s' does not exist.\n", entry)
showEntryHint()
}
}
}
func (cmd gotoCommand) run(state *State, group, args string, reader *bufio.Reader) {
entry := args
doCopyPass := true
if strings.HasPrefix(args, "-n ") {
entry = strings.TrimSpace(args[3:])
doCopyPass = false
} else if len(args) == 0 {
println("Error: please provide the name of the entry to goto.")
return
}
entries := (*state)[group]
entryIndex, found := findEntryIndex(&entries, entry)
if !found && strings.Contains(entry, ":") {
// split up group:entry from user input
parts := strings.SplitN(entry, ":", 2)
group = parts[0]
entry = parts[1]
entries = (*state)[group]
entryIndex, found = findEntryIndex(&entries, entry)
}
if found {
URL := entries[entryIndex].URL
if len(URL) == 0 {
println("Error: entry does not have a URL to go to.")
} else {
go open(URL)
if doCopyPass {
cpCommand{}.run(state, group, "-p "+entry, reader)
}
}
} else {
fmt.Printf("Error: entry '%s' does not exist.\n", entry)
}
}
func (cmd cmpCommand) run(state *State, group, args string, reader *bufio.Reader) {
if len(args) > 0 {
println("Error: the cmp command does not accept any arguments.")
} else {
attempts := 5
for {
print("Current password: ")
pass, err := terminal.ReadPassword(int(syscall.Stdin))
println("")
if err != nil {
panic(err)
}
if string(pass) == cmd.mpBox.value {
cmd.mpBox.value = createPassword()
break
} else if attempts == 0 {
panic("Too many failed attempts.")
} else {
println("Error: incorrect password. Please try again.")
}
attempts--
}
}
}
// ============= Entry helper functions ============= //
func createOrShowEntry(entry string, state *State, group string,
reader *bufio.Reader, createOnly bool) {
currentGroup := group
if len(entry) > 0 {
entries, _ := (*state)[group]
if strings.Contains(entry, ":") {
// split up group:entry from user input
parts := strings.SplitN(entry, ":", 2)
candidateGroup := parts[0]
candidateEntry := parts[1]
useCandidates := ask2OptionsQuestion(
"Option 1: create or view entry '"+candidateEntry+"' in group '"+candidateGroup+"'.\n"+
"Option 2: create or view entry '"+entry+"' in group '"+group+"'.\n\n"+
"Which option do you prefer?", reader, "1", "2", true)
if useCandidates {
group = candidateGroup
entry = candidateEntry
var groupExists bool
entries, groupExists = (*state)[group]
if !groupExists {
newGroupWanted := yesNoQuestion("Group does not exist, do you want to create it?", reader, true)
if newGroupWanted {
createGroup(group, state, group, reader)
} else {
return
}
}
}
}
entryIndex, exists := findEntryIndex(&entries, entry)
if exists {
if createOnly {
println("Error: entry already exists.")
} else {
println(entries[entryIndex].String())
}
} else {
doCreate := createOnly ||
yesNoQuestion("Entry does not exist. Do you want to create it?", reader, true)
if doCreate {
newEntry := createOrEditEntry(entry, group, currentGroup, reader, nil)
(*state)[group] = append(entries, newEntry)
}
}
} else {
println("Error: please provide the name of the entry to be created.")
}
}
func renameEntry(entry string, state *State, group string, reader *bufio.Reader) {
if len(entry) > 0 {
entries, _ := (*state)[group]
entryIndex, found := findEntryIndex(&entries, entry)
if !found && strings.Contains(entry, ":") {
// split up group:entry from user input
parts := strings.SplitN(entry, ":", 2)
group = parts[0]
entry = parts[1]
entries = (*state)[group]
entryIndex, found = findEntryIndex(&entries, entry)
}
if found {
for {
newName := read(reader, "Please enter the new entry name: ")
if len(newName) == 0 {
println("Error: no name provided.")
} else if _, taken := findEntryIndex(&entries, newName); taken {
println("Error: name alredy taken.")
} else {
entries[entryIndex].Name = newName
break
}
}
} else {
println("Error: entry does not exist.")
}
} else {
println("Error: please provide the name of the entry to be renamed.")
}
}
func editEntry(entry string, state *State, group string, reader *bufio.Reader) {
if len(entry) > 0 {
currentGroup := group
entries, _ := (*state)[group]
entryIndex, found := findEntryIndex(&entries, entry)
if !found && strings.Contains(entry, ":") {
// split up group:entry from user input
parts := strings.SplitN(entry, ":", 2)
group = parts[0]
entry = parts[1]
entries = (*state)[group]
entryIndex, found = findEntryIndex(&entries, entry)
}
if found {
fmt.Printf("Editing entry:\n%s\n", entries[entryIndex].String())
println("\nHint: to keep the current value for a field, don't enter a new value.\n")
entries[entryIndex] = createOrEditEntry(entry, currentGroup, group, reader, &entries[entryIndex])
} else {
println("Error: entry does not exist.")
}
} else {
println("Error: please provide the name of the entry to be edited.")
}
}
func removeEntry(entryName string, state *State, group string, reader *bufio.Reader) {
if len(entryName) == 0 {
println("Error: please provide the name of the entry to remove.")
} else {
removed := removeEntryFrom(state, group, entryName)
if !removed {
println("Error: entry does not exist. Are you within the correct group?")
println("Hint: To enter a group called <group-name>, type 'group group-name'.")
}
}
}
func createOrEditEntry(name, group, currentGroup string, reader *bufio.Reader,
entry *LoginInfo) (result LoginInfo) {
username := read(reader, "Enter username: ")
var URL string
goodURL := false
for !goodURL {
URL = read(reader, "Enter URL: ")
if len(URL) > 0 {
_, err := url.Parse(URL)
if err != nil {
println("Invalid URL, please try again.")
} else {
goodURL = true
}
} else {
goodURL = true // empty URL is ok
}
}
description := read(reader, "Enter description: ")
var password string
doChangePassword := true
if entry != nil {
doChangePassword = yesNoQuestion("Do you want to change the password?", reader, false)
}
if doChangePassword {
doGeneratePassword := yesNoQuestion("Generate password?", reader, true)
if doGeneratePassword {
password = generatePassword(reader)
fmt.Printf("Generated password for %s!\n", name)
entryKey := name
if currentGroup != group {
entryKey = group + ":" + name
}
fmt.Printf("Hint: To copy it to the clipboard, type 'cp -p %s'.\n", entryKey)
} else {
for {
print("Please enter a password (at least 4 characters): ")
pass, err := terminal.ReadPassword(int(syscall.Stdin))
println("")
if err != nil {
panic(err)
}
password = string(pass)
if len(password) < 4 {
println("Error: Password too short, please try again!")
} else {
break
}
}
}
}
if entry != nil {
if username == "" {
username = entry.Username
}
if URL == "" {
URL = entry.URL
}
if password == "" {
password = entry.Password
}
if description == "" {
description = entry.Description
}
}
result.Name = name
result.Username = username
result.URL = URL
result.Password = password
result.Description = description
result.UpdatedAt = time.Now()
return
}
func findEntryIndex(entries *[]LoginInfo, name string) (int, bool) {
for i, e := range *entries {
if name == e.Name {
return i, true
}
}
return -1, false
}
func removeEntryFrom(state *State, group, entry string) bool {
entries := (*state)[group]
i, found := findEntryIndex(&entries, entry)
if !found && strings.Contains(entry, ":") {
// split up group:entry from user input
parts := strings.SplitN(entry, ":", 2)
group = parts[0]
entry = parts[1]
entries = (*state)[group]
i, found = findEntryIndex(&entries, entry)
}
if found {
(*state)[group] = append(entries[:i], entries[i+1:]...)
}
return found
}
// ============= Group helper functions ============= //
func createGroup(name string, state *State, group string, reader *bufio.Reader) string {
if len(name) > 0 {
_, ok := (*state)[name]
if !ok {
(*state)[name] = []LoginInfo{}
return name
}
println("Error: group already exists.")
} else {
println("Error: please provide a name for the group.")
}
return group
}
func renameGroup(name string, state *State, group string, reader *bufio.Reader) string {
if len(name) > 0 {
entries, ok := (*state)[name]
if ok {
var newGroupName string
for {
newGroupName = read(reader, "Enter a new name for the group: ")
if len(newGroupName) > 0 {
_, exists := (*state)[newGroupName]
if exists {
println("Error: name already taken.")
} else {
break
}
} else {
println("Error: no name provided.")
}
}
if name == "default" {
(*state)["default"] = []LoginInfo{}
} else {
delete(*state, name)
}
(*state)[newGroupName] = entries
if name == group {
return newGroupName
}
} else {
println("Error: Group does not exist.")
}
} else {
println("Error: please provide the name of the group to be renamed.")
}
return group
}
func removeGroup(groupName string, state *State, group string, reader *bufio.Reader) string {
if len(groupName) == 0 {
println("Error: please provide the name of the group to remove.")
} else {
entries, ok := (*state)[groupName]
entriesLen := len(entries)
if ok {
goAhead := entriesLen == 0 // if there are no entries, don't bother asking for confirmation
if groupName == "default" {
if !goAhead {
goAhead = yesNoQuestion(fmt.Sprintf("Are you sure you want to remove all (%d) entries of the default group?",
entriesLen), reader, false)
if goAhead {
(*state)[groupName] = []LoginInfo{}
}
} else {
println("Warning: cannot delete the default group and there are no entries to remove.")
}
} else {
if !goAhead {
goAhead = yesNoQuestion(fmt.Sprintf("Are you sure you want to remove group '%s' and all of its (%d) entries?",
groupName, entriesLen), reader, false)
if !goAhead {
println("Aborted!")
}
}
if goAhead {
delete(*state, groupName)
if group == groupName {
return "default" // exit the deleted group
}
}
}
} else {
println("Error: group does not exist.")
}
}
return group
}
func groupDescription(name string, entries *[]LoginInfo, tabularFormat bool) string {
var entriesSize string
entriesLen := len(*entries)
switch entriesLen {
case 0:
entriesSize = "empty"
case 1: