-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.go
More file actions
82 lines (72 loc) · 1.71 KB
/
config.go
File metadata and controls
82 lines (72 loc) · 1.71 KB
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
package main
import (
"os"
"path/filepath"
"golang.org/x/crypto/bcrypt"
"gopkg.in/yaml.v3"
)
type Role string
const (
Admin Role = "admin"
User Role = "user"
)
type UserEntry struct {
Name string `yaml:"name"`
Role Role `yaml:"role"`
PwHash string `yaml:"pw_hash"`
PwOneUse bool `yaml:"pw_oneuse,omitempty"`
Expires string `yaml:"expires,omitempty"` // RFC3339, optional
}
type Config struct {
Server struct {
Port int `yaml:"port"`
Key string `yaml:"https_key"`
} `yaml:"server"`
Auth struct {
Users []UserEntry `yaml:"users"`
} `yaml:"auth"`
Tools struct {
AllowPrivileged bool `yaml:"allow_privileged"`
} `yaml:"tools"`
DNS struct {
CustomServers []string `yaml:"custom_servers"`
} `yaml:"dns,omitempty"`
// New Ping targets list
Ping struct {
Targets []string `yaml:"targets,omitempty"`
} `yaml:"ping,omitempty"`
}
func defaultConfig(port int, pw string) *Config {
hash, _ := bcrypt.GenerateFromPassword([]byte(pw), bcrypt.DefaultCost)
cfg := &Config{}
cfg.Server.Port = port
cfg.Server.Key = certFile
cfg.Auth.Users = []UserEntry{
{Name: "admin", Role: Admin, PwHash: string(hash)},
}
return cfg
}
func loadOrInitConfig(path string, port int, pw string) (*Config, error) {
if _, err := os.Stat(path); err == nil {
f, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var c Config
if err := yaml.Unmarshal(f, &c); err != nil {
return nil, err
}
return &c, nil
}
c := defaultConfig(port, pw)
if err := saveConfig(path, c); err != nil {
return nil, err
}
return c, nil
}
func saveConfig(path string, cfg *Config) error {
dir := filepath.Dir(path)
os.MkdirAll(dir, 0o750)
out, _ := yaml.Marshal(cfg)
return os.WriteFile(path, out, 0o600)
}