lockserver/config/config.go
2024-04-23 17:53:17 -07:00

72 lines
1.6 KiB
Go

package config
import (
"encoding/base64"
"encoding/json"
"errors"
"os"
"github.com/gorilla/securecookie"
"github.com/sirupsen/logrus"
)
type Config struct {
ZWaveJSServer string `json:"zwave-js-server"`
SqliteDatabase string `json:"sqlite-database"`
HTTPBind string `json:"http-bind"`
SessionSecrets []JSONBytes `json:"session-secrets"`
}
var C = Config{
ZWaveJSServer: "ws://home-assistant:3000",
SqliteDatabase: "lockserver.db",
HTTPBind: ":8080",
SessionSecrets: []JSONBytes{},
}
var configFiles = []string{"lockserver.json", "/etc/lockserver.json"}
func Load() error {
for _, path := range configFiles {
err := load(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
continue
}
return err
}
logrus.WithField("file", path).Info("loaded config")
}
if len(C.SessionSecrets) == 0 {
logrus.WithFields(logrus.Fields{
"rand_64": base64.URLEncoding.EncodeToString(securecookie.GenerateRandomKey(64)),
"rand_32": base64.URLEncoding.EncodeToString(securecookie.GenerateRandomKey(32)),
}).Info("some potential session secrets for you (hint: use both)")
return errors.New("no session secrets defined, some possible values have been logged")
}
return nil
}
func load(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
if err := json.NewDecoder(f).Decode(&C); err != nil {
return err
}
return nil
}
func (c Config) GetSessionSecrets() [][]byte {
var resp [][]byte
for _, s := range c.SessionSecrets {
resp = append(resp, s.AsByteArrayArray())
}
return resp
}