2026-01-28 12:50:11 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"os"
|
|
|
|
|
|
|
|
|
|
"github.com/pelletier/go-toml/v2"
|
2026-01-30 14:14:54 +00:00
|
|
|
"golang.org/x/oauth2"
|
2026-01-28 12:50:11 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type (
|
2026-01-30 14:14:54 +00:00
|
|
|
GoogleConfig struct {
|
|
|
|
|
ApiKey string `toml:"api_key"`
|
|
|
|
|
ClientID string `toml:"client_id"`
|
|
|
|
|
ClientSecret string `toml:"client_secret"`
|
2026-01-28 12:50:11 +00:00
|
|
|
}
|
|
|
|
|
|
2026-01-30 14:14:54 +00:00
|
|
|
Config struct {
|
|
|
|
|
Host string `toml:"host" comment:"Address to host OAuth2 redirect flow"`
|
|
|
|
|
RedirectUri string `toml:"redirect_uri" comment:"URI to use in Google OAuth2 flow"`
|
|
|
|
|
Google GoogleConfig `toml:"google"`
|
|
|
|
|
Token *oauth2.Token `toml:"token" comment:"This section is filled in automatically on a successful authentication flow."`
|
2026-01-28 12:50:11 +00:00
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var defaultConfig = Config{
|
2026-01-30 14:14:54 +00:00
|
|
|
Host: "localhost:8090",
|
|
|
|
|
RedirectUri: "http://localhost:8090",
|
2026-01-28 12:50:11 +00:00
|
|
|
Google: GoogleConfig{
|
|
|
|
|
ApiKey: "<your API key here>",
|
|
|
|
|
ClientID: "<your client ID here>",
|
|
|
|
|
ClientSecret: "<your client secret here>",
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const CONFIG_FILENAME = "config.toml"
|
|
|
|
|
|
|
|
|
|
func ReadConfig(filename string) (*Config, error) {
|
|
|
|
|
cfgBytes, err := os.ReadFile(filename)
|
|
|
|
|
if err != nil {
|
|
|
|
|
if err == os.ErrNotExist {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
return nil, fmt.Errorf("failed to open file: %v", err)
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-30 14:14:54 +00:00
|
|
|
var config Config
|
2026-01-28 12:50:11 +00:00
|
|
|
err = toml.Unmarshal(cfgBytes, &config)
|
|
|
|
|
if err != nil { return &config, fmt.Errorf("failed to parse: %v", err) }
|
|
|
|
|
|
|
|
|
|
return &config, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-30 14:14:54 +00:00
|
|
|
func WriteConfig(cfg *Config, filename string) error {
|
|
|
|
|
file, err := os.OpenFile(filename, os.O_CREATE | os.O_RDWR, 0644)
|
2026-01-28 12:50:11 +00:00
|
|
|
if err != nil { return err }
|
|
|
|
|
|
2026-01-30 14:14:54 +00:00
|
|
|
err = toml.NewEncoder(file).Encode(cfg)
|
|
|
|
|
return err
|
|
|
|
|
}
|
2026-01-28 12:50:11 +00:00
|
|
|
|
2026-01-30 14:14:54 +00:00
|
|
|
func GenerateConfig(filename string) error {
|
|
|
|
|
return WriteConfig(&defaultConfig, filename)
|
2026-01-28 12:50:11 +00:00
|
|
|
}
|