busybar / pkg / config / config.go
config.go
Raw
package config

import (
	"fmt"
	"log"
	"os"

	"github.com/joho/godotenv"
	"golang.org/x/oauth2"
)

var Config *ConfigType

type OAuthProvider struct {
	Config      oauth2.Config
	UserInfoURL string
}

type ConfigType struct {
	OAuth       map[string]OAuthProvider
	Endpoint    string
	DatabaseURL string
	FrontendURL string
}

func init() {
	err := godotenv.Load()
	if err != nil {
		log.Println("Warning: No .env file found, using environment variables.")
	}

	apiEndpoint := getEnv("ENDPOINT", "http://localhost:4000")

	oauthConfigMap := make(map[string]OAuthProvider)

	if clientID := getEnv("AUTH_DISCORD_CLIENT_ID", ""); clientID != "" {
		oauthConfigMap["discord"] = OAuthProvider{
			Config: oauth2.Config{
				ClientID:     clientID,
				ClientSecret: getEnvRequired("AUTH_DISCORD_CLIENT_SECRET"),
				Endpoint: oauth2.Endpoint{
					AuthURL:  "https://discord.com/api/oauth2/authorize",
					TokenURL: "https://discord.com/api/oauth2/token",
				},
				RedirectURL: apiEndpoint + "/v1/auth/discord/callback",
				Scopes:      []string{"identify", "email"},
			},
			UserInfoURL: "https://discord.com/api/users/@me",
		}
	}

	Config = &ConfigType{
		OAuth:       oauthConfigMap,
		Endpoint:    apiEndpoint,
		DatabaseURL: getEnvRequired("DATABASE_URL"),
		FrontendURL: getEnv("FRONTEND_URL", "http://localhost:8081"),
	}
}

func getEnv(key string, defaultValue string) string {
	value, exists := os.LookupEnv(key)
	if !exists {
		return defaultValue
	}
	return value
}

func getEnvRequired(key string) string {
	value, exists := os.LookupEnv(key)
	if !exists {
		panic(fmt.Sprintf("Environment variable %s is required but not set", key))
	}
	return value
}