-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
169 lines (139 loc) · 3.82 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
package main
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
"time"
"github.com/pquerna/otp/totp"
)
type otp struct {
Issuer string
AccountName string
Secret string
}
// Show usage text when incoming unknown command.
func helpText() string {
return "usage: gtp [{number}|list|add|remove|clear]\n\n" +
" {number} Show time based one-time password by specified secret\n" +
" list All registered OTP secrets\n" +
" add Add new OTP secret\n" +
" remove Remove the specified secret\n" +
" clear Clear all secrets\n"
}
func errorOutOfRangeText(index int) string {
return fmt.Sprintf("ERRORRRRR: Selected number %d is out of range OTP list\n", index)
}
// Create linked text with OTP list.
func getTotalOtpsInfo(otpList []otp) []string {
listResult := make([]string, len(otpList))
for seq, otp := range otpList {
listResult[seq] = fmt.Sprintf("{%d} %s:%s:<secret>", seq+1, otp.Issuer, otp.AccountName)
}
return listResult
}
// Write gtp configuration file (overwrite).
func rewriteConfFile(file *os.File, otpList []otp) {
var jsonConfig []byte
if len(otpList) > 0 {
jsonConfig, _ = json.Marshal(otpList)
} else {
jsonConfig = []byte("")
}
ioutil.WriteFile(file.Name(), jsonConfig, os.FileMode(0644))
}
func main() {
var otpList []otp
var file *os.File
userHomeDir, _ := os.UserHomeDir()
configFile := userHomeDir + "/.gtplist"
if _, err := os.Stat(configFile); os.IsNotExist(err) {
// Check exists file for practice purpose
f, _ := os.Create(configFile)
file = f
} else {
f, _ := os.OpenFile(configFile, os.O_RDWR, os.FileMode(0644))
file = f
}
defer file.Close()
gtpList, err := ioutil.ReadAll(file)
if err != nil {
panic("Error reading configuration file")
}
if len(gtpList) > 0 {
if err := json.Unmarshal(gtpList, &otpList); err != nil {
panic(err)
}
}
args := os.Args
if len(args) < 2 {
fmt.Println(helpText())
return
}
command := args[1]
if len(otpList) == 0 && command != "add" {
fmt.Println("¯\\_(ツ)_/¯ Nothing has been registered")
return
}
switch command {
case "list":
fmt.Println(strings.Join(getTotalOtpsInfo(otpList), "\n"))
case "add":
newOtp := otp{}
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Step 1/3) Issuer: ")
scanner.Scan()
newOtp.Issuer = scanner.Text()
fmt.Print("Step 2/3) Account Name: ")
scanner.Scan()
newOtp.AccountName = scanner.Text()
fmt.Print("Step 3/3) Secret: ")
scanner.Scan()
newOtp.Secret = scanner.Text()
otpList = append(otpList, newOtp)
rewriteConfFile(file, otpList)
fmt.Println("✨ 🔑 ✨ Completed the addition of new OTP ")
case "remove":
fmt.Println(strings.Join(getTotalOtpsInfo(otpList), "\n"))
fmt.Print("\nChoose remove target OTP: ")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
removedSeq, err := strconv.Atoi(scanner.Text())
if err != nil || removedSeq > len(otpList) {
fmt.Println(errorOutOfRangeText(removedSeq))
} else {
newOtpList := append(otpList[:removedSeq-1], otpList[removedSeq:]...)
rewriteConfFile(file, newOtpList)
fmt.Println("💨 Removal success")
}
case "clear":
fmt.Println(strings.Join(getTotalOtpsInfo(otpList), "\n"))
fmt.Print("\nDo you want clear all?: [y|N]")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
confirmFlag := scanner.Text()
if confirmFlag == "y" || confirmFlag == "Y" {
rewriteConfFile(file, []otp{})
fmt.Println("🗑 Removed all")
}
default:
if otpSeq, err := strconv.Atoi(command); err != nil {
fmt.Println(helpText())
} else {
if otpSeq < 1 || otpSeq > len(otpList) {
fmt.Printf(errorOutOfRangeText(otpSeq))
fmt.Println(helpText())
return
}
secret := otpList[otpSeq-1].Secret
passcode, err := totp.GenerateCode(secret, time.Now().UTC())
if err != nil {
panic(err)
}
fmt.Println(passcode)
}
}
}