vaulterm/server/utils/config.go

51 lines
967 B
Go
Raw Normal View History

2024-11-16 02:34:07 +07:00
package utils
import (
"fmt"
"os"
2024-11-16 05:36:54 +07:00
"path/filepath"
2024-11-16 02:34:07 +07:00
)
2024-11-16 05:36:54 +07:00
func GetDataPath(resolveFile string) string {
2024-11-16 23:50:02 +07:00
dataDir := os.Getenv("DATA_DIR")
if dataDir != "" {
return filepath.Join(dataDir, resolveFile)
}
2024-11-16 05:36:54 +07:00
// Resolve the app directory
2024-11-16 23:50:02 +07:00
cwd, err := os.Getwd()
2024-11-16 05:36:54 +07:00
if err != nil {
return ""
}
2024-11-16 23:50:02 +07:00
return filepath.Join(cwd, resolveFile)
2024-11-16 05:36:54 +07:00
}
2024-11-16 02:34:07 +07:00
func CheckAndCreateEnvFile() error {
2024-11-16 05:36:54 +07:00
// Skip if ENCRYPTION_KEY is set
if os.Getenv("ENCRYPTION_KEY") != "" {
return nil
}
2024-11-16 02:34:07 +07:00
// Check if .env file exists
2024-11-16 05:36:54 +07:00
envFile := GetDataPath(".env")
if _, err := os.Stat(envFile); !os.IsNotExist(err) {
2024-11-16 02:34:07 +07:00
return nil
}
// File doesn't exist, so create it
2024-11-17 19:49:42 +07:00
randomKey, err := GenerateRandomKey()
2024-11-16 02:34:07 +07:00
if err != nil {
return err
}
// Write the random key to the .env file
envContent := fmt.Sprintf("ENCRYPTION_KEY=%s\n", randomKey)
2024-11-16 05:36:54 +07:00
err = os.WriteFile(envFile, []byte(envContent), 0644)
2024-11-16 02:34:07 +07:00
if err != nil {
return err
}
2024-11-16 05:36:54 +07:00
fmt.Println(".env file created with ENCRYPTION_KEY.")
2024-11-16 02:34:07 +07:00
return nil
}