From 02bcfbf503d083b3b7d565e5c7acc40a04f28c25 Mon Sep 17 00:00:00 2001 From: Danny Date: Tue, 8 May 2018 12:45:24 +0200 Subject: [PATCH] generate default value for secret so that fathom can run using only default values --- .env.example | 8 ++++---- fathom.go | 39 ++++++++++++++++++++++++++++++--------- pkg/datastore/config.go | 3 ++- 3 files changed, 36 insertions(+), 14 deletions(-) diff --git a/.env.example b/.env.example index be594c6..ac40817 100644 --- a/.env.example +++ b/.env.example @@ -1,6 +1,6 @@ -FATHOM_DATABASE_DRIVER=mysql -FATHOM_DATABASE_NAME="fathom_db" -FATHOM_DATABASE_USER="root" -FATHOM_DATABASE_PASSWORD="root" +FATHOM_DATABASE_DRIVER="sqlite3" +FATHOM_DATABASE_NAME="./fathom.db" +FATHOM_DATABASE_USER="" +FATHOM_DATABASE_PASSWORD="" FATHOM_DATABASE_HOST="" FATHOM_SECRET="abcdefghijklmnopqrstuvwxyz1234567890" diff --git a/fathom.go b/fathom.go index a616fe6..8a41152 100644 --- a/fathom.go +++ b/fathom.go @@ -1,22 +1,23 @@ package main import ( + "math/rand" "os" "github.com/joho/godotenv" "github.com/usefathom/fathom/pkg/commands" "github.com/usefathom/fathom/pkg/counter" "github.com/usefathom/fathom/pkg/datastore" - "gopkg.in/alecthomas/kingpin.v2" "github.com/kelseyhightower/envconfig" log "github.com/sirupsen/logrus" + kingpin "gopkg.in/alecthomas/kingpin.v2" ) type Config struct { Database *datastore.Config - Secret string `required:"true"` + Secret string } var ( @@ -31,13 +32,7 @@ var ( ) func main() { - // load .env file - var cfg Config - godotenv.Load() - err := envconfig.Process("Fathom", &cfg) - if err != nil { - log.Fatalf("Error parsing Fathom config from environment: %s", err) - } + cfg := parseConfig() // setup database connection db := datastore.Init(cfg.Database) @@ -61,3 +56,29 @@ func main() { } } + +func parseConfig() *Config { + var cfg Config + godotenv.Load() + err := envconfig.Process("Fathom", &cfg) + if err != nil { + log.Fatalf("Error parsing Fathom config from environment: %s", err) + } + + // if secret key is empty, use a randomly generated one to ease first-time installation + if cfg.Secret == "" { + cfg.Secret = randomString(40) + os.Setenv("FATHOM_SECRET", cfg.Secret) + } + + return &cfg +} + +func randomString(len int) string { + bytes := make([]byte, len) + for i := 0; i < len; i++ { + bytes[i] = byte(65 + rand.Intn(25)) //A=65 and Z = 65+25 + } + + return string(bytes) +} diff --git a/pkg/datastore/config.go b/pkg/datastore/config.go index 42fd2b0..82cea9b 100644 --- a/pkg/datastore/config.go +++ b/pkg/datastore/config.go @@ -7,7 +7,7 @@ type Config struct { Host string `default:""` User string `default:""` Password string `default:""` - Name string `default:"fathom"` + Name string `default:"fathom.db"` } func (c *Config) DSN() string { @@ -19,6 +19,7 @@ func (c *Config) DSN() string { case "mysql": dsn = fmt.Sprintf("%s:%s@%s/%s?parseTime=true&loc=Local", c.User, c.Password, c.Host, c.Name) case "sqlite3", "sqlite": + dsn = c.Name + "?_loc=auto" // TODO: Make this configurable }