-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
401 lines (371 loc) · 8.95 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
package main
import (
"fmt"
"github.com/AlecAivazis/survey/v2"
"github.com/fatih/color"
"github.com/peterh/liner"
"github.com/spf13/viper"
"github.com/urfave/cli/v2"
"github.com/vearne/passwordbox/args"
"github.com/vearne/passwordbox/consts"
"github.com/vearne/passwordbox/model"
"github.com/vearne/passwordbox/resource"
"github.com/vearne/passwordbox/sc"
"github.com/vearne/passwordbox/store"
"github.com/vearne/passwordbox/utils"
slog "github.com/vearne/simplelog"
"os"
"path/filepath"
"strings"
)
func main() {
app := cli.NewApp()
app.Name = "passwordbox"
app.Version = consts.Version
MasterAuthor := &cli.Author{Name: "vearne", Email: "[email protected]"}
app.Authors = []*cli.Author{MasterAuthor}
app.Copyright = "(c)2020-? vearne"
app.Flags = []cli.Flag{
&cli.StringFlag{
Name: "data",
Aliases: []string{"c"},
Value: ".",
Usage: "Load data from `DIR`",
},
&cli.StringFlag{
Name: "loglevel",
Aliases: []string{"l"},
Usage: "specify log level, optional: debug|info|warn|error",
Value: "info",
},
&cli.IntFlag{
Name: "maxBackupFileCount",
Usage: "Maximum number of backup file retained",
Value: 5,
},
&cli.StringFlag{
Name: "oss",
Usage: `--oss /etc/qingstor.yaml
specify Object Storage Service address,
Note: pwbox identify cloud services by configuration file name.
optional: qingstor.yaml`,
},
}
app.Commands = []*cli.Command{
{
Name: "clear",
Usage: "clear",
Action: func(c *cli.Context) error {
fmt.Print("\x1b[H\x1b[2J")
return nil
},
},
{
Name: "add",
Usage: "add",
Action: store.AddItem,
},
{
Name: "delete",
Usage: "delete -itemId <itemId>",
Action: store.DelItem,
Flags: []cli.Flag{
&cli.IntFlag{
Name: "itemId",
Required: true,
},
},
},
{
Name: "modify",
Usage: "modify -itemId <itemId>",
Action: store.ModifyItem,
Flags: []cli.Flag{
&cli.IntFlag{
Name: "itemId",
Required: true,
},
},
},
{
Name: "view",
Usage: "view -itemId <itemId>",
Action: store.ViewItem,
Flags: []cli.Flag{
&cli.IntFlag{
Name: "itemId",
Required: true,
},
},
},
{
Name: "otp",
Usage: "otp -itemId <itemId>",
Action: store.OtpItem,
Flags: []cli.Flag{
&cli.IntFlag{
Name: "itemId",
Required: true,
},
},
},
{
Name: "search",
Usage: "search [-pageId <pageId>] [-keyword <keyword>]",
UsageText: "pageId/keyword is optional.",
Action: store.SearchItem,
Flags: []cli.Flag{
&cli.IntFlag{
Name: "pageId",
Value: 1,
},
&cli.StringFlag{
Name: "keyword",
Value: "",
},
},
},
{
Name: "backup",
Action: store.Backup,
},
{
Name: "restore",
Usage: "restore [-tagId <tagId>]",
UsageText: "Restore from backup data with specific tag.",
Action: store.RestoreItem,
Flags: []cli.Flag{
&cli.IntFlag{
Name: "tagId",
Value: -1,
},
},
},
{
Name: "quit",
Action: store.Quit,
},
{
Name: "modifyDB",
Action: store.ModifyDBPassword,
},
{
Name: "help",
Action: func(cxt *cli.Context) error {
return cli.ShowAppHelp(cxt)
},
},
}
app.Action = MainLogic
err := app.Run(os.Args)
if err != nil {
slog.Fatal("app run error, %v", err)
}
}
func MainLogic(c *cli.Context) error {
logLevel := c.String("loglevel")
slog.Level = slog.LogMap[logLevel]
maxBackupFileCount := c.Int("maxBackupFileCount")
resource.MaxBackupFileCount = maxBackupFileCount
if resource.MaxBackupFileCount <= 0 {
resource.MaxBackupFileCount = 5
}
// check data directory exist?
dataPath := c.String("data")
if !utils.Exists(dataPath) {
return cli.Exit("Data directory is not exist.", -1)
}
if !utils.IsDir(dataPath) {
return cli.Exit("Data directory is not directory.", -1)
}
// datapath
resource.DataPath = dataPath
ossConfigFile := c.String("oss")
if len(ossConfigFile) > 0 {
viper.SetConfigFile(ossConfigFile)
if err := viper.ReadInConfig(); err == nil {
slog.Info("Using config file: %v", viper.ConfigFileUsed())
} else {
slog.Fatal("can't find config file, %v", err)
}
ossType := extractType(ossConfigFile)
switch ossType {
case "qingstor":
oss := sc.QingStor{}
err := viper.Unmarshal(&oss)
if err != nil {
slog.Fatal("can't parse oss config file, %v", err)
}
resource.GlobalOSS = &oss
case "oss":
oss := sc.AliOSS{}
err := viper.Unmarshal(&oss)
if err != nil {
slog.Fatal("can't parse oss config file, %v", err)
}
resource.GlobalOSS = &oss
default:
slog.Fatal("Unsupport Cloud service providers, %v", ossType)
}
// init object storage service
err := resource.GlobalOSS.Init()
if err != nil {
slog.Fatal("GlobalOSS init error:%v", err)
}
// sync from oss
sc.CompareAndDownloadAll()
}
LOGIN:
fmt.Println("---- login database ----")
database := ""
promptDatabse := &survey.Input{
Message: "Please type database's name:",
}
err := survey.AskOne(promptDatabse, &database, survey.WithValidator(survey.Required))
if err != nil {
fmt.Printf("survey.AskOne error, %v\n", err)
}
database = strings.TrimSpace(database)
slog.Debug("database:%v", database)
filename := utils.Sha256N(database, consts.HashCount)
fullpath := filepath.Join(dataPath, filename)
fmt.Println("fullpath", fullpath)
slog.Debug("fullpath:%v", fullpath)
if !utils.Exists(fullpath) {
createFlag := false
prompt := &survey.Confirm{
Message: "Database is not exist.\nDo you like to create database now?",
}
err = survey.AskOne(prompt, &createFlag)
if err != nil {
fmt.Printf("survey.AskOne error, %v\n", err)
createFlag = false
}
if !createFlag {
return nil
}
// ---- create database ----
err = createDatabase(dataPath)
if err != nil {
fmt.Printf("createDatabase error, %v\n", err)
return err
}
goto LOGIN
}
password := ""
promptPasswd := &survey.Password{
Message: "Please type your password:",
}
err = survey.AskOne(promptPasswd, &password, survey.WithValidator(survey.Required))
if err != nil {
fmt.Printf("survey.AskOne error, %v\n", err)
}
db, err := store.OpenDatabaseStore(dataPath, &model.Database{Name: database, Password: password})
if err != nil {
slog.Fatal("openDatabase error, %v", err)
os.Exit(1)
}
store.GlobalStore = db
// Even if the database name or password is wrong, sqlite3 is still successfully opened,
// and the error will not be reported until you actually query.
db.Hint, err = store.GetHint(db.DB)
if err != nil {
slog.Debug("Get Hint error, %v", err)
fmt.Printf("Decrypt error, Maybe DatabaseName or Password is invalid.\n")
os.Exit(2)
}
info := color.New(color.FgRed, color.BgGreen).SprintFunc()
fmt.Printf("Hint for database %v is %v", info(db.DatabaseName), info(db.Hint))
line := liner.NewLiner()
defer line.Close()
msg := `
Tip: Up and down arrow keys can switch historical commands.
Tip: Ctrl + A jumps to the beginning of the command.
Tip: Ctrl + E jumps to the end of the command.
Tip: Type help for help.
`
fmt.Println(msg)
// For user experience
err = store.SearchItem(c)
if err != nil {
fmt.Printf("SearchItem error, %v\n", err)
}
for {
commandLine, err := line.Prompt(store.GlobalStore.DatabaseName + " > ")
if err != nil {
slog.Error("commandLine:%v, error:%v", commandLine, err)
}
slog.Debug("commandLine:%v", commandLine)
line.AppendHistory(commandLine)
cmdArgs := args.Parse(commandLine)
if len(cmdArgs) <= 0 {
continue
}
s := []string{os.Args[0]}
s = append(s, cmdArgs...)
cmd := cmdArgs[0]
if !utils.FindInSlice(cmd, []string{
"clear", "add", "delete", "quit",
"modify", "view", "otp", "search", "modifyDB",
"backup", "restore", "help"}) {
fmt.Println("unknow command", cmd)
continue
}
err = c.App.Run(s)
if err != nil {
fmt.Println("App.Run error", s)
}
if resource.LoopExit {
break
}
}
return nil
}
func createDatabase(dataPath string) error {
fmt.Println("---- create database ----")
// the questions to ask
var qs = []*survey.Question{
{
Name: "name",
Prompt: &survey.Input{Message: "Please type database's name:"},
Validate: survey.Required,
},
{
Name: "password",
Prompt: &survey.Password{
Message: "Please type password:",
},
Validate: survey.Required,
},
{
Name: "hint",
Prompt: &survey.Input{Message: "Please type hint:"},
Validate: survey.Required,
},
}
answers := model.Database{}
// perform the questions
err := survey.Ask(qs, &answers)
if err != nil {
fmt.Println("error", err)
return err
}
st := store.NewDatabaseStore(dataPath, &answers)
err = st.Init()
if err != nil {
slog.Error("init store error,%v", err)
return err
}
err = st.Close()
if err != nil {
slog.Error("close store error,%v", err)
return err
}
return nil
}
// /abc/def/qingstor.yaml
func extractType(localfilepath string) string {
_, filename := filepath.Split(localfilepath)
itemList := strings.Split(filename, ".")
return itemList[0]
}