add: Environment Var support
This commit is contained in:
@@ -1,36 +1,39 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"GoMembership/internal/utils"
|
||||
"GoMembership/pkg/logger"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"github.com/kelseyhightower/envconfig"
|
||||
|
||||
"GoMembership/internal/utils"
|
||||
"GoMembership/pkg/logger"
|
||||
)
|
||||
|
||||
type DatabaseConfig struct {
|
||||
Path string `json:"Path"`
|
||||
Path string `json:"Path" envconfig:"DB_PATH"`
|
||||
}
|
||||
|
||||
type AuthenticationConfig struct {
|
||||
JWTSecret string
|
||||
CSRFSecret string
|
||||
APIKEY string `json:"APIKey"`
|
||||
APIKEY string `json:"APIKey" envconfig:"API_KEY"`
|
||||
}
|
||||
|
||||
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"`
|
||||
Host string `json:"Host" envconfig:"SMTP_HOST"`
|
||||
User string `json:"User" envconfig:"SMTP_USER"`
|
||||
Password string `json:"Password" envconfig:"SMTP_PASS"`
|
||||
Mailtype string `json:"Mailtype" envconfig:"MAIL_TYPE"`
|
||||
AdminEmail string `json:"AdminEmail" envconfig:"ADMIN_MAIL"`
|
||||
Port int `json:"Port" envconfig:"SMTP_PORT"`
|
||||
}
|
||||
|
||||
type TemplateConfig struct {
|
||||
MailDir string `json:"MailDir"`
|
||||
MailDir string `json:"MailDir" envconfig:"TEMPLATE_DIR"`
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Auth AuthenticationConfig `json:"auth"`
|
||||
DB DatabaseConfig `json:"db"`
|
||||
@@ -39,46 +42,57 @@ type Config struct {
|
||||
}
|
||||
|
||||
var (
|
||||
pConfig Config
|
||||
once sync.Once
|
||||
loaded bool
|
||||
CFG Config
|
||||
Auth AuthenticationConfig
|
||||
DB DatabaseConfig
|
||||
Templates TemplateConfig
|
||||
SMTP SMTPConfig
|
||||
)
|
||||
|
||||
func LoadConfig() *Config {
|
||||
func LoadConfig() {
|
||||
readFile(&CFG)
|
||||
readEnv(&CFG)
|
||||
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)
|
||||
}
|
||||
CFG.Auth.JWTSecret = jwtSecret
|
||||
CFG.Auth.CSRFSecret = csrfSecret
|
||||
|
||||
Auth = CFG.Auth
|
||||
DB = CFG.DB
|
||||
Templates = CFG.Templates
|
||||
SMTP = CFG.SMTP
|
||||
}
|
||||
|
||||
func readFile(cfg *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"))
|
||||
// configFile, err := os.Open("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)
|
||||
err = decoder.Decode(cfg)
|
||||
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
|
||||
}
|
||||
|
||||
func readEnv(cfg *Config) {
|
||||
err := envconfig.Process("", cfg)
|
||||
if err != nil {
|
||||
logger.Error.Fatalf("could not decode env variables: %#v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,14 +28,14 @@ func (mc *MembershipController) RegisterSubscription(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Couldn't decode subscription data"})
|
||||
}
|
||||
|
||||
logger.Info.Printf("Using API key: %v", config.LoadConfig().Auth.APIKEY)
|
||||
logger.Info.Printf("Using API key: %v", config.Auth.APIKEY)
|
||||
|
||||
if regData.APIKey == "" {
|
||||
logger.Error.Println("API Key is missing")
|
||||
c.JSON(http.StatusBadRequest, "API Key is missing")
|
||||
return
|
||||
}
|
||||
if regData.APIKey != config.LoadConfig().Auth.APIKEY {
|
||||
if regData.APIKey != config.Auth.APIKEY {
|
||||
logger.Error.Printf("API Key not valid: %v", regData.APIKey)
|
||||
c.JSON(http.StatusExpectationFailed, "API Key is missing")
|
||||
return
|
||||
|
||||
@@ -42,8 +42,8 @@ func TestUserController(t *testing.T) {
|
||||
t.Errorf("Failed to create DB: %#v", err)
|
||||
}
|
||||
|
||||
cfg := config.LoadConfig()
|
||||
emailService := services.NewEmailService(cfg.SMTP.Host, cfg.SMTP.Port, cfg.SMTP.User, cfg.SMTP.Password, cfg.SMTP.AdminEmail)
|
||||
config.LoadConfig()
|
||||
emailService := services.NewEmailService(config.SMTP.Host, config.SMTP.Port, config.SMTP.User, config.SMTP.Password, config.SMTP.AdminEmail)
|
||||
var consentRepo repositories.ConsentRepositoryInterface = &repositories.ConsentRepository{}
|
||||
consentService := &services.ConsentService{Repo: consentRepo}
|
||||
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"GoMembership/internal/config"
|
||||
"GoMembership/internal/utils"
|
||||
"GoMembership/pkg/logger"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"GoMembership/internal/config"
|
||||
"GoMembership/internal/server"
|
||||
"GoMembership/internal/utils"
|
||||
"GoMembership/pkg/logger"
|
||||
)
|
||||
|
||||
// GenerateCSRFToken generates HMAC-signed CSRF token
|
||||
@@ -46,7 +48,7 @@ func CSRFMiddleware(next http.Handler) http.Handler {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
csrfSecret := config.LoadConfig().Auth.CSRFSecret
|
||||
csrfSecret := config.Auth.CSRFSecret
|
||||
// Retrieve CSRF token from request (e.g., from cookie, header, or form data)
|
||||
csrfToken := r.Header.Get("X-CSRF-Token")
|
||||
|
||||
@@ -78,7 +80,7 @@ func GenerateCSRFTokenHandler(w http.ResponseWriter, r *http.Request) {
|
||||
sessionID := "exampleSessionID123"
|
||||
|
||||
// Generate HMAC-signed CSRF token
|
||||
csrfToken := GenerateCSRFToken(sessionID, config.LoadConfig().Auth.CSRFSecret)
|
||||
csrfToken := GenerateCSRFToken(sessionID, config.Auth.CSRFSecret)
|
||||
|
||||
// Set CSRF token in a cookie (example)
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
|
||||
@@ -17,14 +17,15 @@ import (
|
||||
)
|
||||
|
||||
func Run() {
|
||||
cfg := config.LoadConfig()
|
||||
logger.Info.Printf("Config: %+v", cfg)
|
||||
err := database.InitDB(cfg.DB.Path)
|
||||
config.LoadConfig()
|
||||
logger.Info.Printf("Config loaded: %#v", config.CFG)
|
||||
|
||||
err := database.InitDB(config.DB.Path)
|
||||
if err != nil {
|
||||
logger.Error.Fatalf("Couldn't init database: %v", err)
|
||||
}
|
||||
|
||||
emailService := services.NewEmailService(cfg.SMTP.Host, cfg.SMTP.Port, cfg.SMTP.User, cfg.SMTP.Password, cfg.SMTP.AdminEmail)
|
||||
emailService := services.NewEmailService(config.SMTP.Host, config.SMTP.Port, config.SMTP.User, config.SMTP.Password, config.SMTP.AdminEmail)
|
||||
var consentRepo repositories.ConsentRepositoryInterface = &repositories.ConsentRepository{}
|
||||
consentService := &services.ConsentService{Repo: consentRepo}
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ func (s *EmailService) SendEmail(to string, subject string, body string) error {
|
||||
func ParseTemplate(filename string, data interface{}) (string, error) {
|
||||
// Read the email template file
|
||||
|
||||
templateDir := config.LoadConfig().Templates.MailDir
|
||||
templateDir := config.Templates.MailDir
|
||||
tpl, err := template.ParseFiles(templateDir + "/" + filename)
|
||||
if err != nil {
|
||||
logger.Error.Printf("Failed to parse email template: %v", err)
|
||||
@@ -106,20 +106,20 @@ func (s *EmailService) SendWelcomeEmail(user *models.User) error {
|
||||
func (s *EmailService) NotifyAdminOfNewUser(user *models.User) error {
|
||||
// Prepare data to be injected into the template
|
||||
data := struct {
|
||||
Company string
|
||||
FirstName string
|
||||
City string
|
||||
Email string
|
||||
LastName string
|
||||
MembershipModel string
|
||||
MembershipID int64
|
||||
MembershipFee float32
|
||||
RentalFee float32
|
||||
Address string
|
||||
ZipCode string
|
||||
City string
|
||||
DateOfBirth string
|
||||
Email string
|
||||
Phone string
|
||||
IBAN string
|
||||
FirstName string
|
||||
Phone string
|
||||
DateOfBirth string
|
||||
Company string
|
||||
ZipCode string
|
||||
MembershipID int64
|
||||
RentalFee float32
|
||||
MembershipFee float32
|
||||
}{
|
||||
Company: *user.Company,
|
||||
FirstName: user.FirstName,
|
||||
@@ -143,5 +143,5 @@ func (s *EmailService) NotifyAdminOfNewUser(user *models.User) error {
|
||||
logger.Error.Print("Couldn't send admin notification mail")
|
||||
return err
|
||||
}
|
||||
return s.SendEmail(config.LoadConfig().SMTP.AdminEmail, subject, body)
|
||||
return s.SendEmail(config.SMTP.AdminEmail, subject, body)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user