oauth-guard/config.go
2025-07-03 17:07:35 -07:00

72 lines
1.9 KiB
Go

package main
import (
"fmt"
"github.com/BurntSushi/toml"
"golang.org/x/oauth2"
"golang.org/x/oauth2/endpoints"
)
type Upstream struct {
Addr string `toml:"addr"`
Program string `toml:"program"`
Args []string `toml:"args"`
}
type OAuthProvider struct {
Kind string `toml:"kind"`
ClientID string `toml:"client_id"`
ClientSecret string `toml:"client_secret"`
RedirectURL string `toml:"redirect_url"`
// Only for custom OAuth provider
AuthURL string `toml:"auth_url"`
TokenURL string `toml:"token_url"`
Scopes []string `toml:"scopes"`
Script string `toml:"info_script"`
}
type Config struct {
ListenURL string `toml:"listen_url"`
GuardedPaths []string `toml:"guarded_paths"`
AllowedUsers []string `toml:"allowed_users"`
Upstream Upstream `toml:"upstream"`
OAuthProvider OAuthProvider `toml:"provider"`
}
func LoadConfig() (Config, oauth2.Config, error) {
config := Config{}
oa2 := oauth2.Config{}
_, err := toml.DecodeFile("config.toml", &config)
if err != nil {
return config, oa2, fmt.Errorf("unable to parse 'config.toml' tompl decoding error: %w", err)
}
oa2.ClientID = config.OAuthProvider.ClientID
oa2.ClientSecret = config.OAuthProvider.ClientSecret
oa2.Endpoint = oauth2.Endpoint{}
oa2.RedirectURL = config.OAuthProvider.RedirectURL
oa2.Scopes = []string{}
switch config.OAuthProvider.Kind {
case "github":
oa2.Endpoint = endpoints.GitHub
oa2.Scopes = []string{"read:user"}
case "google":
oa2.Endpoint = endpoints.Google
oa2.Scopes = []string{"https://www.googleapis.com/auth/userinfo.email"}
default:
oa2.Endpoint = oauth2.Endpoint{
AuthURL: config.OAuthProvider.AuthURL,
TokenURL: config.OAuthProvider.TokenURL,
}
oa2.Scopes = config.OAuthProvider.Scopes
if config.OAuthProvider.Script == "" {
panic("no script provided")
}
}
return config, oa2, err
}