-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
103 lines (84 loc) · 2.23 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
package core
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"github.com/terotoi/marque/utils"
)
// Config contains configuration options of the application.
type Config struct {
ListenAddress string `json:"listen_address"`
DatabaseType string `json:"db_type"`
DatabaseConfig string `json:"db_string"`
PasswordSecret string `json:"password_secret"`
JWTSecret string `json:"jwt_secret"`
InitialUser string `json:"initial_user"`
InitialPassword string `json:"initial_password"`
PublicDir string `json:"public_dir"`
}
// LoadConfig loads the configuration file.
func LoadConfig(cfgFile string) (*Config, error) {
var cfg Config
d, err := ioutil.ReadFile(cfgFile)
if err != nil {
return nil, err
}
if err = json.Unmarshal(d, &cfg); err != nil {
return nil, err
}
if cfg.PasswordSecret == "" {
log.Println("Generating new password secret.")
cfg.PasswordSecret, err = utils.GenerateSecret(32)
if err != nil {
return nil, err
}
}
if cfg.JWTSecret == "" {
log.Println("Generating new JWT secret.")
cfg.JWTSecret, err = utils.GenerateSecret(32)
if err != nil {
return nil, err
}
}
return &cfg, nil
}
func GenerateConfig(cfgFile, dataDir, listenAddress string, createInitialUser bool) (*Config, error) {
if _, err := os.Stat(cfgFile); err == nil {
return nil, fmt.Errorf("configuration file %s already exists", cfgFile)
}
if err := os.MkdirAll(path.Dir(cfgFile), 0700); err != nil && !os.IsExist(err) {
return nil, err
}
pwSecret, err := utils.GenerateSecret(32)
if err != nil {
return nil, err
}
jwtSecret, err := utils.GenerateSecret(32)
if err != nil {
return nil, err
}
cfg := Config{
ListenAddress: listenAddress,
DatabaseType: "sqlite3",
DatabaseConfig: fmt.Sprintf("file:%s/marque.db?cache=shared\u0026mode=rwc", dataDir),
PasswordSecret: pwSecret,
JWTSecret: jwtSecret,
PublicDir: "./public",
}
if createInitialUser {
cfg.InitialUser = "admin"
cfg.InitialPassword = "admin"
}
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return nil, err
}
log.Printf("Writing a configuration file to %s", cfgFile)
if err := ioutil.WriteFile(cfgFile, data, 0600); err != nil {
return nil, err
}
return &cfg, nil
}