gitea-github-proxy/config/config.go

106 lines
2.4 KiB
Go
Raw Normal View History

package config
import (
"encoding"
"encoding/base64"
"github.com/mitchellh/mapstructure"
"github.com/spf13/viper"
"go.uber.org/fx"
"go.uber.org/zap"
)
import (
"crypto/ed25519"
)
type PrivateKey ed25519.PrivateKey
var (
_ encoding.TextUnmarshaler = (*PrivateKey)(nil)
)
func (p *PrivateKey) UnmarshalText(text []byte) error {
dec, err := base64.StdEncoding.DecodeString(string(text))
if err != nil {
return err
}
*p = dec
return nil
}
type Config struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
GiteaUrl string `mapstructure:"gitea_url"`
DbPath string `mapstructure:"db_path"`
Oauth OauthConfig
JwtPrivateKey PrivateKey
Domain string `mapstructure:"domain"`
GiteaWebHookSecret string `mapstructure:"gitea_webhook_secret"`
}
type OauthConfig struct {
Authorization string `mapstructure:"authorization"`
Token string `mapstructure:"token"`
ClientId string `mapstructure:"client_id"`
ClientSecret string `mapstructure:"client_secret"`
RefreshToken string `mapstructure:"refresh_token"`
}
var Module = fx.Module("config",
fx.Options(
fx.Provide(NewConfig),
),
)
func NewConfig(logger *zap.Logger) *Config {
c := &Config{}
cfg := viper.New()
_, sk, err := ed25519.GenerateKey(nil)
if err != nil {
logger.Fatal("Error generating private key", zap.Error(err))
}
// Set the default values
cfg.SetDefault("host", "localhost")
cfg.SetDefault("port", 8080)
cfg.SetDefault("gitea_url", "")
cfg.SetDefault("db_path", "data.db")
cfg.SetDefault("jwt_private_key", base64.StdEncoding.EncodeToString(sk))
cfg.SetDefault("oauth.client_id", "")
cfg.SetDefault("oauth.client_secret", "")
cfg.AddConfigPath(".")
cfg.AddConfigPath("/etc/gitea-github-proxy")
cfg.SetConfigName("config")
cfg.SetConfigType("yaml")
err = cfg.ReadInConfig()
if err != nil {
err = cfg.SafeWriteConfig()
if err != nil {
logger.Fatal("Error writing config file", zap.Error(err))
}
}
err = cfg.Unmarshal(c)
if err != nil {
logger.Fatal("Error unmarshalling config", zap.Error(err))
}
err = cfg.UnmarshalKey("jwt_private_key", &c.JwtPrivateKey, viper.DecodeHook(mapstructure.TextUnmarshallerHookFunc()))
if err != nil {
logger.Fatal("Error unmarshalling jwtPrivateKey", zap.Error(err))
}
if len(c.GiteaUrl) == 0 {
logger.Fatal("Gitea URL is required")
}
return c
}