-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
107 lines (86 loc) · 2.38 KB
/
config.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
package twothy
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/mitchellh/go-homedir"
)
const (
// configName for the configFile
configName = ".twothy.json"
// accountsFilename for accounts
accountsFolder = "twothy_accounts"
)
// Config holds the path of the accounts
type Config struct {
AccountsFolder string `json:"accounts_folder"`
}
// loadConfig loads the 2fa Config if configured,
// else returns an error
func loadConfig(filePath string) (c Config, err error) {
data, err := ioutil.ReadFile(filePath)
if err != nil {
return c, fmt.Errorf("failed to load Config file: %v", err)
}
err = json.Unmarshal(data, &c)
if err != nil {
return c, fmt.Errorf("failed to unmarshall Config: %v", err)
}
return c, nil
}
// Configure configures twothy
func Configure(homeDir string) (config Config, err error) {
fmt.Println("Welcome to twothy!!")
fmt.Println("Enter the path to store your 2FA accounts.")
fmt.Printf("I will create '%s' folder at the provided path.\n", accountsFolder)
fmt.Printf("If you are restoring accounts, provide path to '%s'.\n", accountsFolder)
reader := bufio.NewReader(os.Stdin)
fmt.Printf("Path(%s):", homeDir)
dir, err := reader.ReadString('\n')
if err != nil {
return config, fmt.Errorf("failed to scan user choice: %v", err)
}
dir = strings.TrimSpace(dir)
if dir == "" {
dir = homeDir
}
if !strings.HasSuffix(dir, "/") {
dir = dir + "/"
}
if !strings.HasSuffix(dir, accountsFolder+"/") {
dir = dir + accountsFolder + "/"
}
err = os.MkdirAll(dir, 0766)
if err != nil {
return config, fmt.Errorf("failed to create %s: %v", dir, err)
}
config.AccountsFolder = dir
data, err := json.Marshal(config)
if err != nil {
return config, fmt.Errorf("failed to marshall the object: %v", err)
}
err = writeToFile(fmt.Sprintf("%s/%s", homeDir, configName), data)
if err != nil {
return config, fmt.Errorf("failed to write twothy config file: %v", err)
}
return config, nil
}
// GetConfig returns twothy config
func GetConfig() (config Config, err error) {
hd, err := homedir.Dir()
if err != nil {
return config, fmt.Errorf("failed to get user home directory: %v", err)
}
config, err = loadConfig(fmt.Sprintf("%s/%s", hd, configName))
if err == nil {
return config, nil
}
config, err = Configure(hd)
if err != nil {
return config, fmt.Errorf("failed to Configure twothy: %v", err)
}
return config, nil
}