2023-02-12 23:13:04 +01:00
|
|
|
package handlers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"embed"
|
|
|
|
"fmt"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/h44z/wg-portal/internal/app"
|
2023-06-14 23:03:24 +02:00
|
|
|
"html/template"
|
2023-07-07 15:36:07 +02:00
|
|
|
"net"
|
2023-06-14 23:03:24 +02:00
|
|
|
"net/http"
|
2023-07-07 15:36:07 +02:00
|
|
|
"net/url"
|
2023-02-12 23:13:04 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
//go:embed frontend_config.js.gotpl
|
|
|
|
var frontendJs embed.FS
|
|
|
|
|
|
|
|
type configEndpoint struct {
|
|
|
|
app *app.App
|
|
|
|
authenticator *authenticationHandler
|
|
|
|
|
|
|
|
tpl *template.Template
|
|
|
|
}
|
|
|
|
|
|
|
|
func newConfigEndpoint(app *app.App, authenticator *authenticationHandler) configEndpoint {
|
|
|
|
ep := configEndpoint{
|
|
|
|
app: app,
|
|
|
|
authenticator: authenticator,
|
|
|
|
tpl: template.Must(template.ParseFS(frontendJs, "frontend_config.js.gotpl")),
|
|
|
|
}
|
|
|
|
|
|
|
|
return ep
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e configEndpoint) GetName() string {
|
|
|
|
return "ConfigEndpoint"
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e configEndpoint) RegisterRoutes(g *gin.RouterGroup, authenticator *authenticationHandler) {
|
|
|
|
apiGroup := g.Group("/config")
|
|
|
|
|
|
|
|
apiGroup.GET("/frontend.js", e.handleConfigJsGet())
|
|
|
|
}
|
|
|
|
|
|
|
|
// handleConfigJsGet returns a gorm handler function.
|
|
|
|
//
|
|
|
|
// @ID config_handleConfigJsGet
|
|
|
|
// @Tags Configuration
|
|
|
|
// @Summary Get the dynamic frontend configuration javascript.
|
|
|
|
// @Produce text/javascript
|
|
|
|
// @Success 200 string javascript "The JavaScript contents"
|
|
|
|
// @Router /config/frontend.js [get]
|
|
|
|
func (e configEndpoint) handleConfigJsGet() gin.HandlerFunc {
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
backendUrl := fmt.Sprintf("%s/api/v0", e.app.Config.Web.ExternalUrl)
|
|
|
|
if c.GetHeader("x-wg-dev") != "" {
|
2023-07-07 15:36:07 +02:00
|
|
|
referer := c.Request.Header.Get("Referer")
|
|
|
|
host := "localhost"
|
|
|
|
port := "5000"
|
|
|
|
parsedReferer, err := url.Parse(referer)
|
|
|
|
if err == nil {
|
|
|
|
host, port, _ = net.SplitHostPort(parsedReferer.Host)
|
|
|
|
}
|
|
|
|
backendUrl = fmt.Sprintf("http://%s:%s/api/v0", host, port) // override if request comes from frontend started with npm run dev
|
2023-02-12 23:13:04 +01:00
|
|
|
}
|
|
|
|
buf := &bytes.Buffer{}
|
|
|
|
err := e.tpl.ExecuteTemplate(buf, "frontend_config.js.gotpl", gin.H{
|
|
|
|
"BackendUrl": backendUrl,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
c.Status(http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
c.Data(http.StatusOK, "application/javascript", buf.Bytes())
|
|
|
|
}
|
|
|
|
}
|