-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathgauth.go
263 lines (213 loc) · 5.8 KB
/
gauth.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
package main
import (
"bufio"
"fmt"
"log"
"os"
"os/user"
"path/filepath"
"strings"
"syscall"
"text/tabwriter"
"github.com/creachadair/otp/otpauth"
"github.com/pcarrier/gauth/gauth"
"golang.org/x/term"
)
func main() {
accountName := ""
argument := ""
if len(os.Args) > 1 {
accountName = os.Args[1]
}
if len(os.Args) > 2 {
if os.Args[2] == "-b" || os.Args[2] == "-bare" {
argument = "bare"
} else if os.Args[2] == "-a" || os.Args[2] == "-add" {
argument = "add"
} else if os.Args[2] == "-r" || os.Args[2] == "-remove" {
argument = "remove"
} else if os.Args[2] == "-s" || os.Args[2] == "-secret" {
argument = "secret"
}
}
if accountName != "" {
switch argument {
case "bare":
printBareCode(accountName, getUrls())
return
case "add":
addCode(accountName)
return
case "remove":
removeCode(accountName)
return
case "secret":
printSecret(accountName, getUrls())
return
default:
printAllCodes(getUrls())
return
}
}
printAllCodes(getUrls())
}
func getPassword() ([]byte, error) {
fmt.Printf("Encryption password: ")
defer fmt.Println()
return term.ReadPassword(int(syscall.Stdin))
}
func getConfigPath() string {
cfgPath := os.Getenv("GAUTH_CONFIG")
if cfgPath == "" {
user, err := user.Current()
if err != nil {
log.Fatal(err)
}
cfgPath = filepath.Join(user.HomeDir, ".config", "gauth.csv")
}
return cfgPath
}
func getUrls() []*otpauth.URL {
cfgPath := getConfigPath()
cfgContent, err := gauth.LoadConfigFile(cfgPath, getPassword)
if err != nil {
log.Fatalf("Loading config: %v", err)
}
urls, err := gauth.ParseConfig(cfgContent)
if err != nil {
log.Fatalf("Decoding configuration file: %v", err)
}
return urls
}
func printBareCode(accountName string, urls []*otpauth.URL) {
for _, url := range urls {
if strings.EqualFold(strings.ToLower(accountName), strings.ToLower(url.Account)) {
_, curr, _, err := gauth.Codes(url)
if err != nil {
log.Fatalf("Generating codes for %q: %v", url.Account, err)
}
fmt.Print(curr)
break
}
}
}
func addCode(accountName string) {
cfgPath := getConfigPath()
// Check for encryption and ask for password if necessary
_, isEncrypted, err := gauth.ReadConfigFile(cfgPath)
if err != nil {
log.Fatalf("Reading config: %v", err)
}
password, err := []byte(nil), nil
if isEncrypted {
password, err = getPassword()
if err != nil {
log.Fatalf("reading passphrase: %v", err)
}
}
// Get decoded config
rawConfig, err := gauth.LoadConfigFile(cfgPath, func() ([]byte, error) { return password, err })
if err != nil {
log.Fatalf("Loading config: %v", err)
}
newConfig := strings.TrimSuffix(string(rawConfig), "\n")
// Check if account already exists
for _, line := range strings.Split(newConfig, "\n") {
if strings.HasPrefix(strings.ToLower(line), strings.ToLower(accountName)) {
fmt.Printf("Account \"%s\" already exists. Nothing has been added.", accountName)
return
}
}
// Read new key
fmt.Printf("Key for %s: ", accountName)
reader := bufio.NewReader(os.Stdin)
key, _ := reader.ReadString('\n')
// Append new key
newConfig += "\n" + accountName + ":" + key + "\n"
// Try parsing the new config and print the current OTP
parsedConfig, err := gauth.ParseConfig([]byte(newConfig))
if err != nil {
log.Fatalf("Parsing new config: %v", err)
}
fmt.Printf("Current OTP for %s: ", accountName)
printBareCode(accountName, parsedConfig)
// write new config
err = gauth.WriteConfigFile(cfgPath, password, []byte(newConfig))
if err != nil {
log.Fatalf("Error writing new config: %v", err)
}
}
func removeCode(accountName string) {
cfgPath := getConfigPath()
// Check for encryption and ask for password if necessary
_, isEncrypted, err := gauth.ReadConfigFile(cfgPath)
if err != nil {
log.Fatalf("Reading config: %v", err)
}
password, err := []byte(nil), nil
if isEncrypted {
password, err = getPassword()
if err != nil {
log.Fatalf("Reading passphrase: %v", err)
}
}
// Get decoded config
rawConfig, err := gauth.LoadConfigFile(cfgPath, func() ([]byte, error) { return password, err })
if err != nil {
log.Fatalf("Loading config: %v", err)
}
newConfig := ""
anythingRemoved := false
// Iterate over config lines and search for the one to be removed
for _, line := range strings.Split(string(rawConfig), "\n") {
trim := strings.TrimSpace(line)
if trim == "" {
continue
}
if strings.HasPrefix(strings.ToLower(trim), strings.ToLower(accountName)) {
anythingRemoved = true
continue
}
newConfig += trim + "\n"
}
if !anythingRemoved {
fmt.Printf("Account \"%s\" was not found. Nothing has been removed.", accountName)
return
}
// Prompt for confirmation
fmt.Printf("Are you sure you want to remove %s [y/N]: ", accountName)
reader := bufio.NewReader(os.Stdin)
confirmation, _ := reader.ReadString('\n')
confirmation = strings.TrimSpace(confirmation)
if strings.ToLower(confirmation) != "y" {
return
}
// Write the new config
err = gauth.WriteConfigFile(cfgPath, password, []byte(newConfig))
if err != nil {
log.Fatalf("Error writing new config: %v", err)
}
fmt.Printf("%s has been removed.", accountName)
}
func printSecret(accountName string, urls []*otpauth.URL) {
for _, url := range urls {
if strings.EqualFold(strings.ToLower(accountName), strings.ToLower(url.Account)) {
fmt.Print(url.RawSecret)
break
}
}
}
func printAllCodes(urls []*otpauth.URL) {
_, progress := gauth.IndexNow() // TODO: do this per-code
tw := tabwriter.NewWriter(os.Stdout, 0, 8, 1, ' ', 0)
fmt.Fprintln(tw, "\tprev\tcurr\tnext")
for _, url := range urls {
prev, curr, next, err := gauth.Codes(url)
if err != nil {
log.Fatalf("Generating codes for %q: %v", url.Account, err)
}
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", url.Account, prev, curr, next)
}
tw.Flush()
fmt.Printf("[%-29s]\n", strings.Repeat("=", progress))
}