add admin path prefix.

This commit is contained in:
Miroslav Šedivý
2023-10-05 21:03:00 +02:00
parent 7da975473f
commit 6e8bcf90e9
2 changed files with 73 additions and 37 deletions
+9
View File
@@ -1,12 +1,15 @@
package config
import (
"path"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
type Admin struct {
Static string
PathPrefix string
ProxyAuth string
Username string
Password string
@@ -55,6 +58,11 @@ func (Server) Init(cmd *cobra.Command) error {
return err
}
cmd.PersistentFlags().String("admin.path_prefix", "/", "path prefix for admin client and API")
if err := viper.BindPFlag("admin.path_prefix", cmd.PersistentFlags().Lookup("admin.path_prefix")); err != nil {
return err
}
cmd.PersistentFlags().String("admin.proxy_auth", "", "require auth: proxy authentication URL, only allow if it returns 200")
if err := viper.BindPFlag("admin.proxy_auth", cmd.PersistentFlags().Lookup("admin.proxy_auth")); err != nil {
return err
@@ -81,6 +89,7 @@ func (s *Server) Set() {
s.PProf = viper.GetBool("pprof")
s.Admin.Static = viper.GetString("admin.static")
s.Admin.PathPrefix = path.Join("/", path.Clean(viper.GetString("admin.path_prefix")))
s.Admin.ProxyAuth = viper.GetString("admin.proxy_auth")
s.Admin.Username = viper.GetString("admin.username")
s.Admin.Password = viper.GetString("admin.password")
+27
View File
@@ -2,7 +2,9 @@ package server
import (
"context"
"errors"
"io"
"io/fs"
"net"
"net/http"
"os"
@@ -170,6 +172,8 @@ func New(ApiManager types.ApiManager, roomConfig *config.Room, config *config.Se
return next
}
// DEPRECATED: admin should not be served from the same path as rooms
if config.Admin.PathPrefix == "/" {
// cache static file paths
staticFiles := map[string]struct{}{}
if config.Admin.Static != "" {
@@ -208,6 +212,29 @@ func New(ApiManager types.ApiManager, roomConfig *config.Room, config *config.Se
// serve protected API
router.With(protected).Route("/api", ApiManager.Mount)
} else {
router.With(protected).Route(config.Admin.PathPrefix+"/", func(r chi.Router) {
// serve protected API
r.Route("/api", ApiManager.Mount)
// serve static files
r.Get("/*", func(w http.ResponseWriter, r *http.Request) {
filePath := chi.URLParam(r, "*")
if filePath == "" {
filePath = "index.html"
}
filePath = filepath.Clean(filePath)
filePath = filepath.Join(config.Admin.Static, filePath)
if _, err := os.Stat(filePath); err == nil {
http.ServeFile(w, r, filePath)
} else if errors.Is(err, fs.ErrNotExist) {
http.NotFound(w, r)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
})
}
// handle all remaining paths with proxy
router.Handle("/*", proxyHandler)