feat: Add JWT configuration to environment and refactor JWT middleware to use new config structure

This commit is contained in:
2025-03-11 23:37:15 +00:00
parent 9057adebdd
commit b545392f27
4 changed files with 56 additions and 90 deletions
+35 -3
View File
@@ -6,6 +6,7 @@ import (
"log"
"os"
"strconv"
"time"
"github.com/joho/godotenv"
"github.com/timetracker/backend/internal/models"
@@ -14,8 +15,9 @@ import (
// Config represents the application configuration
type Config struct {
Database models.DatabaseConfig
APIKey string
Database models.DatabaseConfig
JWTConfig models.JWTConfig
APIKey string
}
// LoadConfig loads configuration from environment variables and .env file
@@ -24,7 +26,8 @@ func LoadConfig() (*Config, error) {
_ = godotenv.Load()
cfg := &Config{
Database: models.DefaultDatabaseConfig(),
Database: models.DefaultDatabaseConfig(),
JWTConfig: models.JWTConfig{},
}
// Load database configuration
@@ -32,12 +35,41 @@ func LoadConfig() (*Config, error) {
return nil, fmt.Errorf("failed to load database config: %w", err)
}
// Load JWT configuration
if err := loadJWTConfig(cfg); err != nil {
return nil, fmt.Errorf("failed to load JWT config: %w", err)
}
// Load API key
cfg.APIKey = getEnv("API_KEY", "")
return cfg, nil
}
// loadJWTConfig loads JWT configuration from environment
func loadJWTConfig(cfg *Config) error {
cfg.JWTConfig.Secret = getEnv("JWT_SECRET", "default-secret")
defaultDuration := 24 * time.Hour
durationStr := getEnv("JWT_TOKEN_DURATION", defaultDuration.String())
duration, err := time.ParseDuration(durationStr)
if err != nil {
return fmt.Errorf("invalid JWT_TOKEN_DURATION: %w", err)
}
cfg.JWTConfig.TokenDuration = duration
keyGenerateStr := getEnv("JWT_KEY_GENERATE", "false")
keyGenerate, err := strconv.ParseBool(keyGenerateStr)
if err != nil {
return fmt.Errorf("invalid JWT_KEY_GENERATE: %w", err)
}
cfg.JWTConfig.KeyGenerate = keyGenerate
cfg.JWTConfig.KeyDir = getEnv("JWT_KEY_DIR", "./keys")
return nil
}
// loadDatabaseConfig loads database configuration from environment
func loadDatabaseConfig(cfg *Config) error {
// Required fields