84 lines
1.7 KiB
Go
84 lines
1.7 KiB
Go
package config
|
|
|
|
import (
|
|
"GoMembership/internal/utils"
|
|
"GoMembership/pkg/logger"
|
|
"encoding/json"
|
|
"os"
|
|
"path/filepath"
|
|
"sync"
|
|
)
|
|
|
|
type DatabaseConfig struct {
|
|
DBPath string `json:"DBPath"`
|
|
}
|
|
|
|
type AuthenticationConfig struct {
|
|
JWTSecret string
|
|
CSRFSecret string
|
|
}
|
|
|
|
type SMTPConfig struct {
|
|
Host string `json:"Host"`
|
|
User string `json:"User"`
|
|
Password string `json:"Password"`
|
|
Mailtype string `json:"Mailtype"`
|
|
AdminEmail string `json:"AdminEmail"`
|
|
Port int `json:"Port"`
|
|
}
|
|
|
|
type TemplateConfig struct {
|
|
MailDir string `json:"MailDir"`
|
|
}
|
|
type Config struct {
|
|
DB DatabaseConfig `json:"db"`
|
|
Auth AuthenticationConfig
|
|
SMTP SMTPConfig `json:"smtp"`
|
|
Templates TemplateConfig `json:"templates"`
|
|
}
|
|
|
|
var (
|
|
pConfig Config
|
|
once sync.Once
|
|
loaded bool
|
|
)
|
|
|
|
func LoadConfig() *Config {
|
|
path, err := os.Getwd()
|
|
if err != nil {
|
|
logger.Error.Fatalf("could not get working directory: %v", err)
|
|
}
|
|
|
|
configFile, err := os.Open(filepath.Join(path, "configs", "config.json"))
|
|
if err != nil {
|
|
logger.Error.Fatalf("could not open config file: %v", err)
|
|
}
|
|
defer configFile.Close()
|
|
|
|
decoder := json.NewDecoder(configFile)
|
|
// pConfig = &Config{}
|
|
err = decoder.Decode(&pConfig)
|
|
if err != nil {
|
|
logger.Error.Fatalf("could not decode config file: %v", err)
|
|
}
|
|
if !loaded {
|
|
once.Do(
|
|
func() {
|
|
csrfSecret, err := utils.GenerateRandomString(32)
|
|
if err != nil {
|
|
logger.Error.Fatalf("could not generate CSRF secret: %v", err)
|
|
}
|
|
|
|
jwtSecret, err := utils.GenerateRandomString(32)
|
|
if err != nil {
|
|
logger.Error.Fatalf("could not generate JWT secret: %v", err)
|
|
}
|
|
pConfig.Auth.JWTSecret = jwtSecret
|
|
pConfig.Auth.CSRFSecret = csrfSecret
|
|
loaded = true
|
|
})
|
|
}
|
|
|
|
return &pConfig
|
|
}
|