github.com/miguelangel-nubla/oauth2commander@v0.3.7/main.go (about)

     1  package main
     2  
     3  import (
     4  	_ "embed"
     5  	"encoding/json"
     6  	"log"
     7  	"net/http"
     8  	"net/url"
     9  	"os"
    10  
    11  	"github.com/miguelangel-nubla/oauth2commander/oauth2server"
    12  	"github.com/xeipuuv/gojsonschema"
    13  )
    14  
    15  //go:embed schema.json
    16  var configSchema []byte
    17  
    18  type Config struct {
    19  	ClientID     string                  `json:"clientID"`
    20  	ClientSecret string                  `json:"clientSecret"`
    21  	OidcIssuer   string                  `json:"oidcIssuer"`
    22  	CallbackURL  string                  `json:"callbackURL"`
    23  	Endpoints    []oauth2server.Endpoint `json:"endpoints"`
    24  	TLSCert      string                  `json:"tlsCert,omitempty"`
    25  	TLSKey       string                  `json:"tlsKey,omitempty"`
    26  	ListenAddr   string                  `json:"listenAddr"`
    27  }
    28  
    29  func main() {
    30  	// Load configuration from JSON
    31  	config := loadConfig("config.json")
    32  
    33  	app := oauth2server.NewOauth2Commander(config.ClientID, config.ClientSecret, config.OidcIssuer, config.CallbackURL)
    34  
    35  	for _, endpoint := range config.Endpoints {
    36  		handler := func(e oauth2server.Endpoint) http.HandlerFunc {
    37  			return func(w http.ResponseWriter, r *http.Request) {
    38  				// If it's a GET request, serve the HTML file
    39  				if r.Method == http.MethodGet {
    40  					app.HandleCommandConfirm(w, r, e)
    41  					return
    42  				}
    43  
    44  				// If it's a POST request, handle the command
    45  				if r.Method == http.MethodPost {
    46  					app.HandleCommandRun(w, r, e)
    47  					return
    48  				}
    49  			}
    50  		}(endpoint)
    51  
    52  		if endpoint.Public {
    53  			http.HandleFunc(endpoint.Path, handler)
    54  		} else {
    55  			http.HandleFunc(endpoint.Path, app.AuthMiddleware(endpoint.RequiredGroups, handler))
    56  		}
    57  	}
    58  
    59  	u, err := url.Parse(config.CallbackURL)
    60  	if err != nil {
    61  		log.Fatalf("Failed to parse callbackURL: %s", err)
    62  	}
    63  
    64  	http.HandleFunc("/values", app.AuthMiddleware([]string{}, app.EndpointValues))
    65  	http.HandleFunc(u.Path, app.Oauth2Callback)
    66  
    67  	server := &http.Server{
    68  		Addr:    config.ListenAddr,
    69  		Handler: app.SessionMiddleware(http.DefaultServeMux),
    70  	}
    71  
    72  	if config.TLSCert != "" && config.TLSKey != "" {
    73  		log.Printf("listening on https://%s/", config.ListenAddr)
    74  		log.Fatal(server.ListenAndServeTLS(config.TLSCert, config.TLSKey))
    75  	} else {
    76  		log.Printf("listening on http://%s/", config.ListenAddr)
    77  		log.Fatal(server.ListenAndServe())
    78  	}
    79  }
    80  
    81  func loadConfig(filename string) Config {
    82  	file, err := os.Open(filename)
    83  	if err != nil {
    84  		log.Fatalf("Failed to open config file: %s", err)
    85  	}
    86  	defer file.Close()
    87  
    88  	// Load the JSON content
    89  	var config Config
    90  	decoder := json.NewDecoder(file)
    91  	err = decoder.Decode(&config)
    92  	if err != nil {
    93  		log.Fatalf("Failed to decode config file: %s", err)
    94  	}
    95  
    96  	// Load the schema and document
    97  	schemaLoader := gojsonschema.NewBytesLoader(configSchema)
    98  	documentLoader := gojsonschema.NewGoLoader(config)
    99  
   100  	result, err := gojsonschema.Validate(schemaLoader, documentLoader)
   101  	if err != nil {
   102  		log.Fatalf("Failed to validate config: %s", err)
   103  	}
   104  
   105  	if !result.Valid() {
   106  		for _, desc := range result.Errors() {
   107  			// Print error description, for example
   108  			log.Printf("- %s\n", desc)
   109  		}
   110  		log.Fatal("Config validation failed")
   111  	}
   112  
   113  	return config
   114  }