-
Notifications
You must be signed in to change notification settings - Fork 0
/
commands.go
95 lines (75 loc) · 2.24 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
package twothy
import (
"bytes"
"fmt"
"time"
"github.com/mitchellh/go-homedir"
)
// ExecOp executes the given operation
func ExecOp(cmd string, args ...string) (result string, err error) {
switch cmd {
case "configure":
hd, err := homedir.Dir()
if err != nil {
return result, fmt.Errorf("failed to get user's home directory: %v", err)
}
c, err := Configure(hd)
if err != nil {
return result, fmt.Errorf("failed to configure twothy: %v", err)
}
return fmt.Sprintf("2FA accounts will be at: %s\n", c.AccountsFolder), nil
case "add":
c, err := GetConfig()
if err != nil {
return result, fmt.Errorf("failed to configure twothy: %v", err)
}
if len(args) < 3 {
return result, fmt.Errorf("require Issuer, Label, and Key(base32) to add an account")
}
a := NewAccount(args[0], args[1], args[2])
pwd, err := getPassword("to encrypt the account")
if err != nil {
return result, fmt.Errorf("failed to get password from user: %v", err)
}
err = SaveAccount(c, a, pwd)
if err != nil {
return result, fmt.Errorf("failed to save account: %v", err)
}
otp, err := CreateOTP(a, time.Now().Unix())
if err != nil {
return result, fmt.Errorf("failed to generate otp for account %s@%s: %v", a.Issuer, a.Label, err)
}
return fmt.Sprintf("%s@%s: %s\n", a.Label, a.Issuer, otp), nil
case "otp":
c, err := GetConfig()
if err != nil {
return result, fmt.Errorf("failed to configure twothy: %v", err)
}
var name, label string
if len(args) >= 1 {
name = args[0]
}
if len(args) >= 2 {
label = args[1]
}
pwd, err := getPassword("to decrypt the account")
if err != nil {
return result, fmt.Errorf("failed to get password from user: %v", err)
}
accounts, err := LoadAccounts(c, name, label, pwd)
if len(accounts) < 1 {
return fmt.Sprintf("No accounts associated with '%s' are found\n", name), nil
}
var b bytes.Buffer
for _, a := range accounts {
otp, err := CreateOTP(a, time.Now().Unix())
if err != nil {
return result, fmt.Errorf("failed to generate otp for account %s@%s: %v", a.Issuer, a.Label, err)
}
b.WriteString(fmt.Sprintf("%s@%s: %s\n", a.Label, a.Issuer, otp))
}
return b.String(), nil
default:
return result, fmt.Errorf("%s: unknown command", cmd)
}
}