-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
72 lines (57 loc) · 1.98 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
package client
import (
"errors"
"fmt"
"os"
"github.com/BurntSushi/toml"
)
const CONFIG_PATH = ".config/oprand/"
const CONFIG_FILE = "credentials.toml"
type Credentials struct {
Apikey string `toml:"apikey"`
Apisecret string `toml:"apisecret"`
}
// SetupConfig lets user input their API crendetials and
// saves them in a file. This credential file will be read
// when needed to authenticate network requests.
func (op *OprClient) SetupConfig() error {
var config Credentials
// Create config path if it doesn't exist, with read for user only
fullPath := fmt.Sprintf("%s/%s", os.Getenv("HOME"), CONFIG_PATH)
_, err := os.Stat(fullPath)
if errors.Is(err, os.ErrNotExist) {
err = os.MkdirAll(fullPath, 0700)
if err != nil {
return fmt.Errorf("cannot mkdir config file path: %w", err)
}
} else if err != nil {
return fmt.Errorf("cannot stat config file path: %w", err)
} else {
fmt.Fprintf(os.Stderr, "WARN: Config file at `%s` already exists.\n", fullPath+CONFIG_FILE)
fmt.Fprintf(os.Stderr, "WARN: Content will be overwritten by new values entered. Press Ctrl+C to keep current values.\n\n")
}
// Ask for API Key
fmt.Printf("OPRAND API KEY: ")
fmt.Scanln(&config.Apikey)
// Ask for API Secret
fmt.Printf("OPRAND API SECRET: ")
fmt.Scanln(&config.Apisecret)
// Write to config file
f, err := os.OpenFile(fullPath+CONFIG_FILE, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("cannot open config file: %w", err)
}
header := []byte("# Credentials to access threat data provided by oprand.com\n# Generated by: opr config\n\n")
if _, err := f.Write(header); err != nil {
return fmt.Errorf("cannot write to config file: %w", err)
}
err = toml.NewEncoder(f).Encode(&config)
if err != nil {
return fmt.Errorf("cannot marshall config struct to toml: %w", err)
}
if err := f.Close(); err != nil {
return fmt.Errorf("cannot close config file: %w", err)
}
fmt.Printf("Config file successfully written at `%s`\n", fullPath+CONFIG_FILE)
return nil
}