Files
auth-proxy/src/config.go
db123-test c3869f4f10 feat: add env file support and parameterize SQL queries
Add .env and .env.local loading with InitEnv() helper that reads
environment variables from config files without overwriting existing
values.

Refactor SQL queries to use parameterized arguments instead of
string formatting for LIMIT/OFFSET clauses, improving query security
and preventing SQL injection vulnerabilities.

Clean up unnecessary rows.Close() calls and simplify error handling
in database query functions.
2026-05-05 19:13:42 +03:30

115 lines
2.0 KiB
Go

package main
import (
"os"
"path/filepath"
"time"
)
type Config struct {
Port string
APIToken string
DataDir string
CleanupInterval time.Duration
DBPath string
}
func loadConfig() Config {
return Config{
Port: getEnv("AUTH_PROXY_PORT", "8080"),
APIToken: getEnv("AUTH_PROXY_API_TOKEN", ""),
DataDir: getEnv("DATA_DIR", "/data"),
CleanupInterval: parseDuration("CLEANUP_INTERVAL", 60*time.Second),
DBPath: getEnv("AUTH_PROXY_DB_PATH", "/data/auth-proxy.db"),
}
}
func loadEnvFile(envFile string) {
if _, err := os.Stat(envFile); err != nil {
return
}
data, err := os.ReadFile(envFile)
if err != nil {
return
}
for _, line := range splitLines(data) {
parts := splitKV(line)
if len(parts) == 2 {
key := parts[0]
value := unquote(parts[1])
if os.Getenv(key) == "" {
os.Setenv(key, value)
}
}
}
}
func getEnv(key, defaultValue string) string {
if v := os.Getenv(key); v != "" {
return v
}
return defaultValue
}
func parseDuration(key string, defaultVal time.Duration) time.Duration {
if v := os.Getenv(key); v != "" {
d, err := time.ParseDuration(v)
if err == nil {
return d
}
}
return defaultVal
}
func splitLines(data []byte) []string {
lines := make([]string, 0)
var line string
for _, b := range data {
if b == '\n' {
lines = append(lines, line)
line = ""
} else if b != '\r' {
line += string(b)
}
}
if line != "" {
lines = append(lines, line)
}
return lines
}
func splitKV(line string) []string {
for i, b := range line {
if b == '=' {
return []string{line[:i], line[i+1:]}
}
}
return nil
}
func unquote(s string) string {
if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' {
return s[1 : len(s)-1]
}
if len(s) >= 2 && s[0] == '\'' && s[len(s)-1] == '\'' {
return s[1 : len(s)-1]
}
return s
}
func InitEnv() {
possibleFiles := []string{
".env",
".env.local",
}
for _, f := range possibleFiles {
abs, err := filepath.Abs(f)
if err == nil {
loadEnvFile(abs)
return
}
}
}